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
others
496
TimefoldAI
zepfred
@@ -39,5 +39,4 @@ quarkus.swagger-ui.always-include=true # Test overrides ######################## # Effectively disable spent-time termination in favor of the best-score-limit -%test.quarkus.timefold.solver.termination.spent-limit=1h -%test.quarkus.timefold.solver.termination.best-score-limit=0hard/*medium/*soft \ No newline at end of file +%test.quarkus.timefold.solver.termination.spent-limit=10s
Is this change correct?
timefold-quickstarts
github_2023
java
495
TimefoldAI
triceo
@@ -22,8 +22,8 @@ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { return new Constraint[] { // Hard constraints crewConflict(constraintFactory), - readyDate(constraintFactory), - dueDate(constraintFactory), + minDate(constraintFactory), + maxDate(constraintFactory),
Shouldn't this be `minStartDate` and `maxEndDate`? Either way, it should be consistent with food packaging, which is also being updated in this PR, but for some reason it is being updated to something else.
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -76,48 +71,33 @@ Constraint atLeast10HoursBetweenTwoShifts(ConstraintFactory constraintFactory) { Constraint oneShiftPerDay(ConstraintFactory constraintFactory) { return constraintFactory.forEachUniquePair(Shift.class, Joiners.equal(Shift::getEmployee), - Joiners.equal(shift -> shift.getStart().toLocalDate())) + Joiners.equal(shift -> shift.getStart().toLocalDate())) .penalize(HardSoftScore.ONE_HARD) .asConstraint("Max one shift per day"); } Constraint unavailableEmployee(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) - .filter(shift -> { - Set<LocalDate> unavailableDates = shift.getEmployee().getUnavailableDates(); - return unavailableDates.contains(shift.getStart().toLocalDate()) - // The contains() check is ignored for a shift ends at midnight (00:00:00). - || (shift.getEnd().isAfter(shift.getStart().toLocalDate().plusDays(1).atStartOfDay()) - && unavailableDates.contains(shift.getEnd().toLocalDate())); - }) - .penalize(HardSoftScore.ONE_HARD, EmployeeSchedulingConstraintProvider::getShiftDurationInMinutes) + .expand(shift -> shift.getEmployee().getUnavailableDates())
Using `expand` is not necessary; I think you've done that, so that later in the `filter`, you can use a method reference. Is that a good enough reason to introduce a functionality that slows down the constraint and, arguably, makes it more complex to understand? In my opinion, it is not.
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -89,6 +96,41 @@ public void setEmployee(Employee employee) { this.employee = employee; } + @JsonIgnore + public boolean isOverlappingWith(Collection<LocalDate> dates) { + return !getOverlappingDatesForShift(dates).isEmpty(); + }
Although this is a simple way of implementing the requirement, it is also an anti-pattern. Let us not teach our users that abandoning incrementality and turning everything into collection processing is the right way of doing things; they already think that anyway. There is a simple rule of thumb when working with constraint streams: if you see a collection or a for-loop anywhere, you're probably doing it wrong. You have to process each of `LocalDate` individually. You can use `flattenLast(...)` to get it out of the `Shift`. (Here, the use of `expand(...)` may actually be necessary.)
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -75,49 +74,41 @@ Constraint atLeast10HoursBetweenTwoShifts(ConstraintFactory constraintFactory) { } Constraint oneShiftPerDay(ConstraintFactory constraintFactory) { - return constraintFactory.forEachUniquePair(Shift.class, Joiners.equal(Shift::getEmployee), - Joiners.equal(shift -> shift.getStart().toLocalDate())) + return constraintFactory.forEachUniquePair(Shift.class, equal(Shift::getEmployee), + equal(shift -> shift.getStart().toLocalDate())) .penalize(HardSoftScore.ONE_HARD) .asConstraint("Max one shift per day"); } Constraint unavailableEmployee(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) - .filter(shift -> { - Set<LocalDate> unavailableDates = shift.getEmployee().getUnavailableDates(); - return unavailableDates.contains(shift.getStart().toLocalDate()) - // The contains() check is ignored for a shift ends at midnight (00:00:00). - || (shift.getEnd().isAfter(shift.getStart().toLocalDate().plusDays(1).atStartOfDay()) - && unavailableDates.contains(shift.getEnd().toLocalDate())); - }) - .penalize(HardSoftScore.ONE_HARD, EmployeeSchedulingConstraintProvider::getShiftDurationInMinutes) + .join(Employee.class, equal(Shift::getEmployee, Function.identity())) + .flattenLast(Employee::getUnavailableDates) + .filter((shift, unavailableDate) -> shift.getOverlappingDurationInMinutes(unavailableDate) > 0) + .penalize(HardSoftScore.ONE_HARD, + (shift, unavailableDate) -> (int) shift.getOverlappingDurationInMinutes(unavailableDate))
In this case, I think that `expand(...)` actually has value. `getOverlappingDurationInMinutes()` has quite a lot of logic, which is now being run twice.
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -75,49 +74,44 @@ Constraint atLeast10HoursBetweenTwoShifts(ConstraintFactory constraintFactory) { } Constraint oneShiftPerDay(ConstraintFactory constraintFactory) { - return constraintFactory.forEachUniquePair(Shift.class, Joiners.equal(Shift::getEmployee), - Joiners.equal(shift -> shift.getStart().toLocalDate())) + return constraintFactory.forEachUniquePair(Shift.class, equal(Shift::getEmployee), + equal(shift -> shift.getStart().toLocalDate())) .penalize(HardSoftScore.ONE_HARD) .asConstraint("Max one shift per day"); } Constraint unavailableEmployee(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) - .filter(shift -> { - Set<LocalDate> unavailableDates = shift.getEmployee().getUnavailableDates(); - return unavailableDates.contains(shift.getStart().toLocalDate()) - // The contains() check is ignored for a shift ends at midnight (00:00:00). - || (shift.getEnd().isAfter(shift.getStart().toLocalDate().plusDays(1).atStartOfDay()) - && unavailableDates.contains(shift.getEnd().toLocalDate())); - }) - .penalize(HardSoftScore.ONE_HARD, EmployeeSchedulingConstraintProvider::getShiftDurationInMinutes) + .join(Employee.class, equal(Shift::getEmployee, Function.identity())) + .flattenLast(Employee::getUnavailableDates) + .filter((shift, unavailableDate) -> shift.getStart().toLocalDate().equals(unavailableDate) + || shift.getEnd().toLocalDate().equals(unavailableDate))
The filter body should be extracted to a method on `Shift` and reused; it's non-trivial logic which is repeated in 3 constraints.
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -89,6 +92,24 @@ public void setEmployee(Employee employee) { this.employee = employee; } + public boolean isOverlappingWithDate(LocalDate date) { + return getStart().toLocalDate().equals(date) || getEnd().toLocalDate().equals(date); + } + + public long getOverlappingDurationInMinutes(LocalDate date) { + LocalDateTime startDateTime = LocalDateTime.of(date, LocalTime.MIN); + LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX); + return getOverlappingDurationInMinutes(startDateTime, endDateTime, getStart(), getEnd()); + } + + private long getOverlappingDurationInMinutes(LocalDateTime firstStartDateTime, LocalDateTime firstEndDateTime, + LocalDateTime secondStartDateTime, LocalDateTime secondEndDateTime) { + LocalDateTime maxStartTime = firstStartDateTime.isAfter(secondStartDateTime) ? firstStartDateTime : secondStartDateTime; + LocalDateTime minEndTime = firstEndDateTime.isBefore(secondEndDateTime) ? firstEndDateTime : secondEndDateTime; + long minutes = maxStartTime.until(minEndTime, ChronoUnit.MINUTES); + return minutes > 0 ? minutes : 0;
Any reason why this can't return an `int`? I doubt there will ever be 2 billion minutes of overlap. (`long` causes casting in the `penalize(...)` calls.)
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -54,18 +52,19 @@ Constraint requiredSkill(ConstraintFactory constraintFactory) { } Constraint noOverlappingShifts(ConstraintFactory constraintFactory) { - return constraintFactory.forEachUniquePair(Shift.class, Joiners.equal(Shift::getEmployee), - Joiners.overlapping(Shift::getStart, Shift::getEnd)) + return constraintFactory.forEachUniquePair(Shift.class, equal(Shift::getEmployee), + Joiners.overlapping(Shift::getStart, Shift::getEnd)) .penalize(HardSoftScore.ONE_HARD, EmployeeSchedulingConstraintProvider::getMinuteOverlap) .asConstraint("Overlapping shift"); } Constraint atLeast10HoursBetweenTwoShifts(ConstraintFactory constraintFactory) { return constraintFactory.forEachUniquePair(Shift.class, - Joiners.equal(Shift::getEmployee), - Joiners.lessThanOrEqual(Shift::getEnd, Shift::getStart)) - .filter((firstShift, secondShift) -> Duration.between(firstShift.getEnd(), secondShift.getStart()).toHours() < 10) + equal(Shift::getEmployee), + Joiners.lessThanOrEqual(Shift::getEnd, Shift::getStart))
Are you sure about `forEachUniquePair` here? It is useful, but not in situations where the order of the two elements actually matters, such as here. Consider shifts A, B. This will produce [A, B], but not [B, A]. This clashes with `A.end() < B.start()`; some of the pairs will not be selected and therefore not penalized. A well-written test will catch this.
timefold-quickstarts
github_2023
java
484
TimefoldAI
triceo
@@ -54,18 +52,18 @@ Constraint requiredSkill(ConstraintFactory constraintFactory) { } Constraint noOverlappingShifts(ConstraintFactory constraintFactory) { - return constraintFactory.forEachUniquePair(Shift.class, Joiners.equal(Shift::getEmployee), - Joiners.overlapping(Shift::getStart, Shift::getEnd)) + return constraintFactory.forEachUniquePair(Shift.class, equal(Shift::getEmployee), + Joiners.overlapping(Shift::getStart, Shift::getEnd)) .penalize(HardSoftScore.ONE_HARD, EmployeeSchedulingConstraintProvider::getMinuteOverlap) .asConstraint("Overlapping shift"); } Constraint atLeast10HoursBetweenTwoShifts(ConstraintFactory constraintFactory) { - return constraintFactory.forEachUniquePair(Shift.class, - Joiners.equal(Shift::getEmployee), - Joiners.lessThanOrEqual(Shift::getEnd, Shift::getStart)) - .filter((firstShift, secondShift) -> Duration.between(firstShift.getEnd(), secondShift.getStart()).toHours() < 10) + return constraintFactory.forEach(Shift.class) + .join(Shift.class, equal(Shift::getEmployee), Joiners.lessThanOrEqual(Shift::getEnd, Shift::getStart))
One joiner is statically imported, the other isn't. Let's either consistently do static imports, or consistently don't.
timefold-quickstarts
github_2023
others
483
TimefoldAI
triceo
@@ -2,7 +2,7 @@ <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta content="width=device-width, initial-scale=1" name="viewport"> - <title>School timetabling - Timefold Quarkus</title> + <title>School timetabling - Timefold Python</title>
```suggestion <title>School timetabling - Timefold Solver for Python</title> ```
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -49,6 +49,28 @@ Then try _live coding_: Notice that those changes are immediately in effect. +[[enterprise]] +== Run the application with the Enterprise Edition
This is not the entire description. Even though you link to the docs, I think it's still better to mention here that: - They need to configure username and password. - And the way to get username and password is to [contact us](https://timefold.ai/contact) to get a license.
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -49,6 +49,28 @@ Then try _live coding_: Notice that those changes are immediately in effect. +[[enterprise]] +== Run the application with the Enterprise Edition + +For high-scalability use cases, try the paid https://docs.timefold.ai/timefold-solver/latest/enterprise-edition/enterprise-edition[Enterprise Edition] instead:
```suggestion For high-scalability use cases, try https://docs.timefold.ai/timefold-solver/latest/enterprise-edition/enterprise-edition[Timefold Solver Enterprise Edition], our commercial offering, instead: ```
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -50,9 +50,60 @@ Then try _live coding_: Notice that those changes are immediately in effect. [[enterprise]] -== Run the application with the Enterprise Edition +== Run the application with Timefold Solver Enterprise Edition -For high-scalability use cases, try the paid https://docs.timefold.ai/timefold-solver/latest/enterprise-edition/enterprise-edition[Enterprise Edition] instead: +For high-scalability use cases, switch to https://docs.timefold.ai/timefold-solver/latest/enterprise-edition/enterprise-edition[Timefold Solver Enterprise Edition], +our commercial offering. +https://timefold.ai/contact[Contact Timefold] to obtain the credentials required to access our private Enterprise Maven repository. + +. Create `.m2/settings.xml` in your home directory with the following content: ++ +[tabs] +==== +Maven::
Do tabs work on Github? Arguably if the quickstart doesn't have support for Gradle, this can be simplified by not including Gradle instructions.
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -49,6 +49,79 @@ Then try _live coding_: Notice that those changes are immediately in effect. +[[enterprise]] +== Run the application with Timefold Solver Enterprise Edition + +For high-scalability use cases, switch to https://docs.timefold.ai/timefold-solver/latest/enterprise-edition/enterprise-edition[Timefold Solver Enterprise Edition], +our commercial offering. +https://timefold.ai/contact[Contact Timefold] to obtain the credentials required to access our private Enterprise Maven repository. + +. Create `.m2/settings.xml` in your home directory with the following content:
This is a Maven-specific instruction, it belongs in the Maven tab. Gradle does this differently.
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -1,15 +1,3 @@ -######################## -# 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
```suggestion # Timefold Solver properties ```
timefold-quickstarts
github_2023
others
476
TimefoldAI
triceo
@@ -19,19 +7,35 @@ quarkus.timefold.solver.termination.spent-limit=30s # To change how many solvers to run in parallel # timefold.solver-manager.parallel-solver-count=4 -# To run increase CPU cores usage per solver -# quarkus.timefold.solver.move-thread-count=2 # Temporary comment this out to detect bugs in your code (lowers performance) # quarkus.timefold.solver.environment-mode=FULL_ASSERT + +# Temporary comment this out to return a feasible solution as soon as possible +# quarkus.timefold.solver.termination.best-score-limit=0hard/0medium/*soft + # To see what Timefold is doing, turn on DEBUG or TRACE logging. -quarkus.log.category."ai.timefold.solver".level=DEBUG +quarkus.log.category."ai.timefold.solver".level=INFO %test.quarkus.log.category."ai.timefold.solver".level=INFO %prod.quarkus.log.category."ai.timefold.solver".level=INFO # XML file for power tweaking, defaults to solverConfig.xml (directly under src/main/resources) # quarkus.timefold.solver-config-xml=org/.../bedSchedulingSolverConfig.xml +######################## +# Timefold Enterprise properties
```suggestion # Timefold Solver Enterprise Edition properties ```
timefold-quickstarts
github_2023
python
477
TimefoldAI
Christopher-Chianelli
@@ -21,7 +21,7 @@ def test_required_skill(): Shift(id="1", start=DAY_START_TIME, end=DAY_END_TIME, location="Location", required_skill="Skill", employee=employee)) .penalizes(1)) - employee = Employee(name="Beth", skills={"Skill"}) + employee = Employee(name="Beth", skills={"Skill"}, unavailable_dates=set(), undesired_dates=set(), desired_dates=set())
```suggestion employee = Employee(name="Beth", skills={"Skill"}) ```
timefold-quickstarts
github_2023
python
477
TimefoldAI
Christopher-Chianelli
@@ -1,16 +1,18 @@ from timefold.solver.score import ConstraintFactory, HardSoftScore, constraint_provider -from .domain import Vehicle -from .justifications import VehicleCapacityJustification, MinimizeTravelTimeJustification +from .domain import * +from .score_analysis import * VEHICLE_CAPACITY = "vehicleCapacity" MINIMIZE_TRAVEL_TIME = "minimizeTravelTime" @constraint_provider -def vehicle_routing_constraints(factory: ConstraintFactory): +def define_constraints(factory: ConstraintFactory):
I strongly disagree with this change. Why?
timefold-quickstarts
github_2023
python
474
TimefoldAI
Christopher-Chianelli
@@ -15,210 +15,174 @@ def test_required_skill(): - employee = Employee(name="Amy", skills=set()) + employee = Employee(name="Amy", skills=set(), unavailable_dates=set(), undesired_dates=set(), desired_dates=set())
Using `Field(default_factory=set)` would make unavailable_dates, etc. empty if unspecified (https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.Field)
timefold-quickstarts
github_2023
others
459
TimefoldAI
zepfred
@@ -0,0 +1,79 @@ += Employee Scheduling (Python)
Let's fix the title.
timefold-quickstarts
github_2023
python
459
TimefoldAI
zepfred
@@ -0,0 +1,53 @@ +from timefold.solver.score import ConstraintFactory, HardSoftScore, constraint_provider + +from .domain import Vehicle +from .justifications import VehicleCapacityJustification, MinimizeTravelTimeJustification + +VEHICLE_CAPACITY = "vehicleCapacity" +MINIMIZE_TRAVEL_TIME = "minimizeTravelTime" + + +@constraint_provider +def vehicle_routing_constraints(factory: ConstraintFactory): + return [ + vehicle_capacity(factory), + minimize_travel_time(factory) + ] + +############################################## +# Hard constraints +############################################## + + +def vehicle_capacity(factory: ConstraintFactory): + return (factory.for_each(Vehicle) + .filter(lambda vehicle: vehicle.calculate_total_demand() > vehicle.capacity) + .penalize(HardSoftScore.ONE_HARD, + lambda vehicle: vehicle.calculate_total_demand() - vehicle.capacity) + .justify_with(lambda vehicle, score: + VehicleCapacityJustification(
It looks like the capacity param comes first.
timefold-quickstarts
github_2023
javascript
459
TimefoldAI
zepfred
@@ -0,0 +1,165 @@ +function addNewVisit(id, lat, lng, map, marker) {
Do we need this file?
timefold-quickstarts
github_2023
others
466
TimefoldAI
triceo
@@ -0,0 +1,128 @@ +name: Maven
```suggestion name: Python ```
timefold-quickstarts
github_2023
javascript
458
TimefoldAI
zepfred
@@ -0,0 +1,435 @@ +var autoRefreshIntervalId = null; +const dateTimeFormatter = JSJoda.DateTimeFormatter.ofPattern('HH:mm') + +let demoDataId = null; +let scheduleId = null; +let loadedSchedule = null; + +$(document).ready(function () { + replaceQuickstartTimefoldAutoHeaderFooter(); + + $("#solveButton").click(function () { + solve(); + }); + $("#stopSolvingButton").click(function () { + stopSolving(); + }); + $("#analyzeButton").click(function () { + analyze(); + }); + + setupAjax(); + fetchDemoData(); +}); + +function setupAjax() { + $.ajaxSetup({ + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json,text/plain', // plain text is required by solve() returning UUID of the solver job + } + }); + + // Extend jQuery to support $.put() and $.delete() + jQuery.each(["put", "delete"], function (i, method) { + jQuery[method] = function (url, data, callback, type) { + if (jQuery.isFunction(data)) { + type = type || callback; + callback = data; + data = undefined; + } + return jQuery.ajax({ + url: url, + type: method, + dataType: type, + data: data, + success: callback + }); + }; + }); +} + +function fetchDemoData() { + $.get("/demo-data", function (data) { + data.forEach(item => { + $("#testDataButton").append($('<a id="' + item + 'TestData" class="dropdown-item" href="#">' + item + '</a>')); + + $("#" + item + "TestData").click(function () { + switchDataDropDownItemActive(item); + scheduleId = null; + demoDataId = item; + + refreshSchedule(); + }); + }); + + // load first data set + demoDataId = data[0]; + switchDataDropDownItemActive(demoDataId); + refreshSchedule(); + }).fail(function (xhr, ajaxOptions, thrownError) { + // disable this page as there is no data + let $demo = $("#demo"); + $demo.empty(); + $demo.html("<h1><p align=\"center\">No test data available</p></h1>") + }); +} + +function switchDataDropDownItemActive(newItem) { + activeCssClass = "active"; + $("#testDataButton > a." + activeCssClass).removeClass(activeCssClass); + $("#" + newItem + "TestData").addClass(activeCssClass); +} + +function refreshSchedule() { + let path = "/timetables/" + scheduleId; + if (scheduleId === null) { + if (demoDataId === null) { + alert("Please select a test data set."); + return; + } + + path = "/demo-data/" + demoDataId; + } + + $.getJSON(path, function (schedule) { + loadedSchedule = schedule; + renderSchedule(schedule); + }) + .fail(function (xhr, ajaxOptions, thrownError) { + showError("Getting the timetable has failed.", xhr); + refreshSolvingButtons(false); + }); +} + +function renderSchedule(timetable) { + refreshSolvingButtons(timetable.solverStatus != null && timetable.solverStatus !== "NOT_SOLVING"); + $("#score").text("Score: " + (timetable.score == null ? "?" : timetable.score)); + + const timetableByRoom = $("#timetableByRoom"); + timetableByRoom.children().remove(); + const timetableByTeacher = $("#timetableByTeacher"); + timetableByTeacher.children().remove(); + const timetableByStudentGroup = $("#timetableByStudentGroup"); + timetableByStudentGroup.children().remove(); + const unassignedLessons = $("#unassignedLessons"); + unassignedLessons.children().remove(); + + const theadByRoom = $("<thead>").appendTo(timetableByRoom); + const headerRowByRoom = $("<tr>").appendTo(theadByRoom); + headerRowByRoom.append($("<th>Timeslot</th>")); + + $.each(timetable.rooms, (index, room) => { + headerRowByRoom + .append($("<th/>") + .append($("<span/>").text(room.name)) + .append($(`<button type="button" class="ms-2 mb-1 btn btn-light btn-sm p-1"/>`))); + }); + const theadByTeacher = $("<thead>").appendTo(timetableByTeacher); + const headerRowByTeacher = $("<tr>").appendTo(theadByTeacher); + headerRowByTeacher.append($("<th>Timeslot</th>")); + const teachers = [...new Set(timetable.lessons.map(lesson => lesson.teacher))]; + $.each(teachers, (index, teacher) => { + headerRowByTeacher + .append($("<th/>") + .append($("<span/>").text(teacher))); + }); + const theadByStudentGroup = $("<thead>").appendTo(timetableByStudentGroup); + const headerRowByStudentGroup = $("<tr>").appendTo(theadByStudentGroup); + headerRowByStudentGroup.append($("<th>Timeslot</th>")); + const studentGroups = [...new Set(timetable.lessons.map(lesson => lesson.studentGroup))]; + $.each(studentGroups, (index, studentGroup) => { + headerRowByStudentGroup + .append($("<th/>") + .append($("<span/>").text(studentGroup))); + }); + + const tbodyByRoom = $("<tbody>").appendTo(timetableByRoom); + const tbodyByTeacher = $("<tbody>").appendTo(timetableByTeacher); + const tbodyByStudentGroup = $("<tbody>").appendTo(timetableByStudentGroup); + + const LocalTime = JSJoda.LocalTime; + + $.each(timetable.timeslots, (index, timeslot) => { + const rowByRoom = $("<tr>").appendTo(tbodyByRoom); + rowByRoom + .append($(`<th class="align-middle"/>`) + .append($("<span/>").text(` + ${timeslot.dayOfWeek.charAt(0) + timeslot.dayOfWeek.slice(1).toLowerCase()} + ${LocalTime.parse(timeslot.startTime).format(dateTimeFormatter)} + - + ${LocalTime.parse(timeslot.endTime).format(dateTimeFormatter)} + `))); + $.each(timetable.rooms, (index, room) => { + rowByRoom.append($("<td/>").prop("id", `timeslot${timeslot.id}room${room.id}`)); + }); + + const rowByTeacher = $("<tr>").appendTo(tbodyByTeacher); + rowByTeacher + .append($(`<th class="align-middle"/>`) + .append($("<span/>").text(` + ${timeslot.dayOfWeek.charAt(0) + timeslot.dayOfWeek.slice(1).toLowerCase()} + ${LocalTime.parse(timeslot.startTime).format(dateTimeFormatter)} + - + ${LocalTime.parse(timeslot.endTime).format(dateTimeFormatter)} + `))); + $.each(teachers, (index, teacher) => { + rowByTeacher.append($("<td/>").prop("id", `timeslot${timeslot.id}teacher${convertToId(teacher)}`)); + }); + + const rowByStudentGroup = $("<tr>").appendTo(tbodyByStudentGroup); + rowByStudentGroup + .append($(`<th class="align-middle"/>`) + .append($("<span/>").text(` + ${timeslot.dayOfWeek.charAt(0) + timeslot.dayOfWeek.slice(1).toLowerCase()} + ${LocalTime.parse(timeslot.startTime).format(dateTimeFormatter)} + - + ${LocalTime.parse(timeslot.endTime).format(dateTimeFormatter)} + `))); + $.each(studentGroups, (index, studentGroup) => { + rowByStudentGroup.append($("<td/>").prop("id", `timeslot${timeslot.id}studentGroup${convertToId(studentGroup)}`)); + }); + }); + + $.each(timetable.lessons, (index, lesson) => { + const color = pickColor(lesson.subject); + const lessonElement = $(`<div class="card" style="background-color: ${color}"/>`) + .append($(`<div class="card-body p-2"/>`) + .append($(`<h5 class="card-title mb-1"/>`).text(lesson.subject)) + .append($(`<p class="card-text ms-2 mb-1"/>`) + .append($(`<em/>`).text(`by ${lesson.teacher}`))) + .append($(`<small class="ms-2 mt-1 card-text text-muted align-bottom float-end"/>`).text(lesson.id)) + .append($(`<p class="card-text ms-2"/>`).text(lesson.studentGroup))); + if (lesson.timeslot == null || lesson.room == null) { + unassignedLessons.append($(`<div class="col"/>`).append(lessonElement)); + } else { + // In the JSON, the lesson.timeslot and lesson.room are only IDs of these objects. + $(`#timeslot${lesson.timeslot}room${lesson.room}`).append(lessonElement.clone()); + $(`#timeslot${lesson.timeslot}teacher${convertToId(lesson.teacher)}`).append(lessonElement.clone()); + $(`#timeslot${lesson.timeslot}studentGroup${convertToId(lesson.studentGroup)}`).append(lessonElement.clone()); + } + }); +} + +function solve() { + $.post("/timetables", JSON.stringify(loadedSchedule), function (data) { + scheduleId = data; + refreshSolvingButtons(true); + }).fail(function (xhr, ajaxOptions, thrownError) { + showError("Start solving failed.", xhr); + refreshSolvingButtons(false); + }, + "text"); +} + +function analyze() { + new bootstrap.Modal("#scoreAnalysisModal").show() + const scoreAnalysisModalContent = $("#scoreAnalysisModalContent"); + scoreAnalysisModalContent.children().remove(); + if (loadedSchedule.score == null || loadedSchedule.score.indexOf('init') != -1) { + scoreAnalysisModalContent.text("No score to analyze yet, please first press the 'solve' button."); + } else { + $('#scoreAnalysisScoreLabel').text(`(${loadedSchedule.score})`); + $.put("/timetables/analyze", JSON.stringify(loadedSchedule), 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-chevron-down')).click(e => { + matchesRow.collapse('toggle'); + let target = $(e.target); + if (target.hasClass('fa-chevron-down')) { + target.removeClass('fa-chevron-down').addClass('fa-chevron-up'); + } else { + target.removeClass('fa-chevron-up').addClass('fa-chevron-down'); + } + }))); + } else { + row.append($(`<td/>`)); + } + + }); + analysisTable.append(analysisTBody); + scoreAnalysisModalContent.append(analysisTable); + }).fail(function (xhr, ajaxOptions, thrownError) { + showError("Analyze failed.", xhr); + }, + "text"); + } +} + +function getScoreComponents(score) { + let components = {hard: 0, medium: 0, soft: 0}; + + $.each([...score.matchAll(/(-?[0-9]+)(hard|medium|soft)/g)], (i, parts) => { + components[parts[2]] = parseInt(parts[1], 10); + }); + + return components; +} + + +function refreshSolvingButtons(solving) { + if (solving) { + $("#solveButton").hide(); + $("#stopSolvingButton").show(); + if (autoRefreshIntervalId == null) { + autoRefreshIntervalId = setInterval(refreshSchedule, 2000); + } + } else { + $("#solveButton").show(); + $("#stopSolvingButton").hide(); + if (autoRefreshIntervalId != null) { + clearInterval(autoRefreshIntervalId); + autoRefreshIntervalId = null; + } + } +} + +function stopSolving() { + $.delete("/timetables/" + scheduleId, function () { + refreshSolvingButtons(false); + refreshSchedule(); + }).fail(function (xhr, ajaxOptions, thrownError) { + showError("Stop solving failed.", xhr); + }); +} + +function convertToId(str) { + // Base64 encoding without padding to avoid XSS + return btoa(str).replace(/=/g, ""); +} + +function copyTextToClipboard(id) { + var text = $("#" + id).text().trim(); + + var dummy = document.createElement("textarea"); + document.body.appendChild(dummy); + dummy.value = text; + dummy.select(); + document.execCommand("copy"); + document.body.removeChild(dummy); +} + +// TODO: move to the webjar +function replaceQuickstartTimefoldAutoHeaderFooter() { + const timefoldHeader = $("header#timefold-auto-header"); + if (timefoldHeader != null) { + timefoldHeader.addClass("bg-black") + timefoldHeader.append( + $(`<div class="container-fluid"> + <nav class="navbar sticky-top navbar-expand-lg navbar-dark shadow mb-3"> + <a class="navbar-brand" href="https://timefold.ai"> + <img src="/webjars/timefold/img/timefold-logo-horizontal-negative.svg" alt="Timefold logo" width="200"> + </a> + <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> + <span class="navbar-toggler-icon"></span> + </button> + <div class="collapse navbar-collapse" id="navbarNav"> + <ul class="nav nav-pills"> + <li class="nav-item active" id="navUIItem"> + <button class="nav-link active" id="navUI" data-bs-toggle="pill" data-bs-target="#demo" type="button">Demo UI</button> + </li> + <li class="nav-item" id="navRestItem"> + <button class="nav-link" id="navRest" data-bs-toggle="pill" data-bs-target="#rest" type="button">Guide</button> + </li> + <li class="nav-item" id="navOpenApiItem"> + <button class="nav-link" id="navOpenApi" data-bs-toggle="pill" data-bs-target="#openapi" type="button">REST API</button> + </li> + </ul> + </div> + <div class="ms-auto"> + <div class="dropdown"> + <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
This button is not working. Let's fix it.
timefold-quickstarts
github_2023
python
458
TimefoldAI
zepfred
@@ -0,0 +1,28 @@ +from timefold.solver import SolverFactory +from timefold.solver.config import (SolverConfig, ScoreDirectorFactoryConfig, + TerminationConfig, Duration, TerminationCompositionStyle) + +from school_timetabling.domain import Timetable, Lesson +from school_timetabling.constraints import school_timetabling_constraints +from school_timetabling.demo_data import generate_demo_data, DemoData + + +def test_feasible():
Let's either create a new test or update this one to enable API calls, allowing us to test the API with supported Python versions.
timefold-quickstarts
github_2023
python
451
TimefoldAI
zepfred
@@ -0,0 +1,61 @@ +from timefold.solver import SolverManager, SolverFactory, SolutionManager +from timefold.solver.config import (SolverConfig, ScoreDirectorFactoryConfig, + TerminationConfig, Duration) +from fastapi import FastAPI +from fastapi.staticfiles import StaticFiles + +from .domain import EmployeeSchedule, Shift +from .constraints import scheduling_constraints +from .demo_data import DemoData, generate_demo_data + + +solver_config = SolverConfig( + solution_class=EmployeeSchedule, + entity_class_list=[Shift], + score_director_factory_config=ScoreDirectorFactoryConfig( + constraint_provider_function=scheduling_constraints + ), + termination_config=TerminationConfig( + spent_limit=Duration(seconds=30) + ) +) + +solver_manager = SolverManager.create(SolverFactory.create(solver_config)) +solution_manager = SolutionManager.create(solver_manager) + +app = FastAPI(docs_url='/q/swagger-ui') +data_sets: dict[str, EmployeeSchedule] = {} + + +@app.get("/demo-data") +async def demo_data_list() -> list[DemoData]: + return [e for e in DemoData] + + +@app.get("/demo-data/{dataset_id}", response_model_exclude_none=True)
It looks like we always return the `SMALL` dataset
timefold-quickstarts
github_2023
others
451
TimefoldAI
zepfred
@@ -0,0 +1,135 @@ +<html lang="en"> +<head> + <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> + <meta content="width=device-width, initial-scale=1" name="viewport"> + <title>Employee scheduling - Timefold Python</title> + + <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="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css"/> + <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"/> + <link rel="stylesheet" href="/webjars/timefold/css/timefold-webui.css"/> + <style> + .vis-time-axis .vis-grid.vis-saturday, + .vis-time-axis .vis-grid.vis-sunday { + background: #D3D7CFFF; + } + </style> + <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" aria-live="polite" + aria-atomic="true"> + <div id="notificationPanel" style="position: absolute; top: .5rem;"></div> + </div> + <h1>Employee scheduling solver</h1> + <p>Generate the optimal schedule for your employees.</p> + + <div class="mb-4"> + <button id="solveButton" type="button" class="btn btn-success"> + <span class="fas fa-play"></span> Solve + </button> + <button id="stopSolvingButton" type="button" class="btn btn-danger"> + <span class="fas fa-stop"></span> Stop solving + </button> + <button id="publish" type="button" class="btn btn-primary">
This button is not used. Let's either remove it or add the necessary logic for publishing schedules.
timefold-quickstarts
github_2023
others
447
TimefoldAI
zepfred
@@ -0,0 +1,64 @@ += School Timetabling (Python) + +Assign lessons to timeslots and rooms to produce a better schedule for teachers and students. + +== Prerequisites + +. Install Python 3.10+ + +. Install JDK 17+, for example with https://sdkman.io[Sdkman]: ++ +---- +$ sdk install java
Do we have instructions on how to install Python?
timefold-quickstarts
github_2023
others
447
TimefoldAI
zepfred
@@ -0,0 +1,64 @@ += School Timetabling (Python) + +Assign lessons to timeslots and rooms to produce a better schedule for teachers and students. + +== Prerequisites + +. Install Python 3.10+ + +. Install JDK 17+, for example with https://sdkman.io[Sdkman]: ++ +---- +$ sdk install java +---- + +== Run the application + +. Git clone the timefold-quickstarts repo: ++ +[source, shell] +---- +$ git clone https://github.com/TimefoldAI/timefold-quickstarts.git +... +$ cd timefold-quickstarts/python/hello-world +---- + +. Create a virtual environment ++ +[source, shell] +---- +$ python -m venv .venv +---- + +. Activate the virtual environment ++ +[source, shell] +---- +$ . .venv/bin/activate +---- + +. Install requirements ++ +[source, shell] +---- +$ pip install -r requirements.txt
I can't install the dependencies. Do I need to run any additional commands? ``` (.venv) fred@fedora:~/Projects/timefold/timefold-quickstarts/python/hello-world$ pip install -r requirements.txt ERROR: Could not find a version that satisfies the requirement timefold-solver==999-dev0 (from versions: 1.10.0a0) ERROR: No matching distribution found for timefold-solver==999-dev0 ```
timefold-quickstarts
github_2023
python
447
TimefoldAI
zepfred
@@ -0,0 +1,126 @@ +from timefold.solver.config import (SolverConfig, ScoreDirectorFactoryConfig, + TerminationConfig, Duration) +from timefold.solver import SolverFactory +from domain import Lesson, Timeslot, Room, Timetable +from constraints import school_timetabling_constraints +from enum import Enum +from datetime import time +import logging + + +logging.basicConfig(level=logging.INFO) +LOGGER = logging.getLogger('app') + + +def main(): + solver_factory = SolverFactory.create( + SolverConfig( + solution_class=Timetable, + entity_class_list=[Lesson], + score_director_factory_config=ScoreDirectorFactoryConfig( + constraint_provider_function=school_timetabling_constraints + ), + termination_config=TerminationConfig( + # The solver runs only for 5 seconds on this small dataset. + # It's recommended to run for at least 5 minutes ("5m") otherwise. + spent_limit=Duration(seconds=5) + ) + )) + + # Load the problem + problem = generate_demo_data(DemoData.SMALL) + + # Solve the problem + solver = solver_factory.build_solver() + solution = solver.solve(problem) + + # Visualize the solution + print_timetable(solution) + + +def generate_demo_data(demo_data: 'DemoData') -> Timetable: + timeslots = [ + Timeslot(day, start, start.replace(hour=start.hour + 1)) + for day in ('MONDAY', 'TUESDAY') + for start in (time(8, 30), time(9, 30), time(10, 30), time(13, 30), time(14, 30)) + ] + rooms = [Room(f'Room {name}') for name in ('A', 'B', 'C')] + + lessons = [] + + def id_generator(): + current = 0 + while True: + yield str(current) + current += 1 + + ids = id_generator() + lessons.append(Lesson(next(ids), "Math", "A. Turing", "9th grade")) + lessons.append(Lesson(next(ids), "Math", "A. Turing", "9th grade")) + lessons.append(Lesson(next(ids), "Physics", "M. Curie", "9th grade")) + lessons.append(Lesson(next(ids), "Chemistry", "M. Curie", "9th grade")) + lessons.append(Lesson(next(ids), "Biology", "C. Darwin", "9th grade")) + lessons.append(Lesson(next(ids), "History", "I. Jones", "9th grade")) + lessons.append(Lesson(next(ids), "English", "I. Jones", "9th grade")) + lessons.append(Lesson(next(ids), "English", "I. Jones", "9th grade")) + lessons.append(Lesson(next(ids), "Spanish", "P. Cruz", "9th grade")) + lessons.append(Lesson(next(ids), "Spanish", "P. Cruz", "9th grade")) + + lessons.append(Lesson(next(ids), "Math", "A. Turing", "10th grade")) + lessons.append(Lesson(next(ids), "Math", "A. Turing", "10th grade")) + lessons.append(Lesson(next(ids), "Math", "A. Turing", "10th grade")) + lessons.append(Lesson(next(ids), "Physics", "M. Curie", "10th grade")) + lessons.append(Lesson(next(ids), "Chemistry", "M. Curie", "10th grade")) + lessons.append(Lesson(next(ids), "French", "M. Curie", "10th grade")) + lessons.append(Lesson(next(ids), "Geography", "C. Darwin", "10th grade")) + lessons.append(Lesson(next(ids), "History", "I. Jones", "10th grade")) + lessons.append(Lesson(next(ids), "English", "P. Cruz", "10th grade")) + lessons.append(Lesson(next(ids), "Spanish", "P. Cruz", "10th grade")) + + return Timetable(demo_data.name, timeslots, rooms, lessons) + + +def print_timetable(time_table: Timetable) -> None: + LOGGER.info("") + rooms = time_table.rooms + timeslots = time_table.timeslots + lessons = time_table.lessons + lesson_map = { + (lesson.room.name, lesson.timeslot.day_of_week, lesson.timeslot.start_time): lesson + for lesson in lessons + if lesson.room is not None and lesson.timeslot is not None + } + row_format ="|{:<15}" * (len(rooms) + 1) + "|" + sep_format = "+" + ((("-" * 15) + "+") * (len(rooms) + 1)) + + LOGGER.info(sep_format) + LOGGER.info(row_format.format('', *[room.name for room in rooms])) + LOGGER.info(sep_format) + + for timeslot in timeslots: + def get_row_lessons(): + for room in rooms: + yield lesson_map.get((room.name, timeslot.day_of_week, timeslot.start_time), + Lesson('', '', '', '')) + + row_lessons = [*get_row_lessons()] + LOGGER.info(row_format.format(str(timeslot), *[lesson.subject for lesson in row_lessons])) + LOGGER.info(row_format.format('', *[lesson.teacher for lesson in row_lessons])) + LOGGER.info(row_format.format('', *[lesson.student_group for lesson in row_lessons])) + LOGGER.info(sep_format) + + unassigned_lessons = [lesson for lesson in lessons if lesson.room is None or lesson.timeslot is None] + if len(unassigned_lessons) > 0: + LOGGER.info("") + LOGGER.info("Unassigned lessons") + for lesson in unassigned_lessons: + LOGGER.info(f' {lesson.subject} - {lesson.teacher} - {lesson.student_group}') + + +class DemoData(Enum): + SMALL = 'SMALL' + LARGE = 'LARGE'
We are not using the `LARGE` type to create a different dataset.
timefold-quickstarts
github_2023
others
447
TimefoldAI
zepfred
@@ -0,0 +1,3 @@ +timefold-solver==999-dev0
This version is failing to be installed.
timefold-quickstarts
github_2023
python
447
TimefoldAI
zepfred
@@ -0,0 +1,28 @@ +from timefold.solver import SolverFactory
Nice!
timefold-quickstarts
github_2023
others
434
TimefoldAI
triceo
@@ -3,7 +3,7 @@ plugins { id "io.quarkus" version "3.9.4"
```suggestion id "io.quarkus" version "3.10.1" ```
timefold-quickstarts
github_2023
others
421
TimefoldAI
triceo
@@ -77,6 +77,9 @@ jobs: - name: Quickly build timefold-solver working-directory: ./timefold-solver run: mvn -B -Dquickly clean install - - name: Test timefold-quickstarts in Native mode + - name: Test timefold-quickstarts (slowly tests)
```suggestion - name: Test timefold-quickstarts (slow tests) ```
timefold-quickstarts
github_2023
others
421
TimefoldAI
triceo
@@ -1,137 +1,181 @@ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> + <modelVersion>4.0.0</modelVersion> - <groupId>org.acme</groupId> - <artifactId>hello-world-school-timetabling</artifactId> - <version>1.0-SNAPSHOT</version> + <groupId>org.acme</groupId> + <artifactId>hello-world-school-timetabling</artifactId> + <version>1.0-SNAPSHOT</version>
These changes are unrelated and unnecessary. Probably your IDE messed up? Please remove from this file and others.
timefold-quickstarts
github_2023
others
421
TimefoldAI
triceo
@@ -0,0 +1,152 @@ +name: Long-Running + +on: + pull_request: + branches: [stable, development, '*.x'] + paths-ignore: + - 'LICENSE*' + - '.gitignore' + - '**.md' + - '**.adoc' + - '*.txt' + +jobs: +# build-quarkus:
Please re-enable.
timefold-quickstarts
github_2023
java
421
TimefoldAI
triceo
@@ -0,0 +1,41 @@ +package org.acme.schooltimetabling.solver; + +import static org.acme.schooltimetabling.TimetableApp.generateDemoData; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; + +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.EnvironmentMode; +import ai.timefold.solver.core.config.solver.SolverConfig; + +import org.acme.schooltimetabling.TimetableApp; +import org.acme.schooltimetabling.domain.Lesson; +import org.acme.schooltimetabling.domain.Timetable; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("slowly") +class TimetableFastAssertTest {
So we are no longer doing `FULL_ASSERT`? I thought we'd be doing both.
timefold-quickstarts
github_2023
others
421
TimefoldAI
triceo
@@ -154,8 +149,53 @@ <plugin> <groupId>org.graalvm.buildtools</groupId> <artifactId>native-maven-plugin</artifactId> + <configuration> + <imageName>app.native</imageName> + <buildArgs> + <!-- Ob == fast build --> + <buildArg>-Ob</buildArg> + <buildArg>--no-fallback</buildArg> + <buildArg>--trace-class-initialization=org.junit.platform.engine.TestTag</buildArg> + </buildArgs> + </configuration> </plugin> </plugins> </build> + <profiles> + <profile> + <id>default</id> + <activation> + <activeByDefault>true</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <version>${version.surefire.plugin}</version> + <configuration> + <excludedGroups>slowly</excludedGroups>
By using the following, you'll be able to remove the entire `default` profile, possibly even both the profiles: https://junit.org/junit5/docs/5.1.0/api/org/junit/jupiter/api/condition/EnabledIfSystemProperty.html
timefold-quickstarts
github_2023
java
421
TimefoldAI
triceo
@@ -0,0 +1,45 @@ +package org.acme.schooltimetabling.solver; + +import static org.acme.schooltimetabling.TimetableApp.generateDemoData; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; + +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.EnvironmentMode; +import ai.timefold.solver.core.config.solver.SolverConfig; + +import org.acme.schooltimetabling.TimetableApp; +import org.acme.schooltimetabling.domain.Lesson; +import org.acme.schooltimetabling.domain.Timetable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +@EnabledIfSystemProperty(named = "slowly", matches = "true") +class TimetableEnvironmentTest { + + @Test + void solve() { + solve(EnvironmentMode.FULL_ASSERT); + solve(EnvironmentMode.FAST_ASSERT); + }
I like this. Simple, no boilerplate, no profiles. Do you mind propagating this to the rest of the assert tests? (Spring Boot can do it differently, if this causes trouble.) Maybe I'd make two methods out of this? So that you see in the log whether it was the full or the fast that failed.
timefold-quickstarts
github_2023
java
421
TimefoldAI
triceo
@@ -1,14 +1,16 @@ package org.acme.schooltimetabling.solver; +import java.time.DayOfWeek; +import java.time.LocalTime; + import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; + import org.acme.schooltimetabling.domain.Lesson; import org.acme.schooltimetabling.domain.Room; import org.acme.schooltimetabling.domain.Timeslot; import org.acme.schooltimetabling.domain.Timetable; import org.junit.jupiter.api.Test; -import java.time.DayOfWeek; -import java.time.LocalTime;
Please reformat the imports using the order we use in the Solver. (Alternatively: remove these unrelated changes, which will equal to the same result.)
timefold-quickstarts
github_2023
java
421
TimefoldAI
triceo
@@ -0,0 +1,48 @@ +package org.acme.schooltimetabling.solver; + +import static org.acme.schooltimetabling.TimetableApp.generateDemoData; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; + +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.EnvironmentMode; +import ai.timefold.solver.core.config.solver.SolverConfig; + +import org.acme.schooltimetabling.TimetableApp; +import org.acme.schooltimetabling.domain.Lesson; +import org.acme.schooltimetabling.domain.Timetable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +@EnabledIfSystemProperty(named = "slowly", matches = "true") +class TimetableEnvironmentTest { + + @Test + void solveFullAssert() { + solve(EnvironmentMode.FULL_ASSERT); + } + + @Test + void solveFastAssert() { + solve(EnvironmentMode.FAST_ASSERT); + } + + void solve(EnvironmentMode environmentMode) { + SolverFactory<Timetable> solverFactory = SolverFactory.create(new SolverConfig() + .withSolutionClass(Timetable.class) + .withEntityClasses(Lesson.class) + .withConstraintProviderClass(TimetableConstraintProvider.class) + .withEnvironmentMode(environmentMode) + .withTerminationSpentLimit(Duration.ofSeconds(30))); + + // Load the problem + Timetable problem = generateDemoData(TimetableApp.DemoData.SMALL); + + // Solve the problem + Solver<Timetable> solver = solverFactory.buildSolver(); + Timetable solution = solver.solve(problem); +assertThat(solution.getScore()).isNotNull(); }
```suggestion assertThat(solution.getScore()).isNotNull(); } ```
timefold-quickstarts
github_2023
java
421
TimefoldAI
triceo
@@ -0,0 +1,48 @@ +package org.acme.schooltimetabling.solver; + +import static org.acme.schooltimetabling.TimetableApp.generateDemoData; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; + +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.EnvironmentMode; +import ai.timefold.solver.core.config.solver.SolverConfig; + +import org.acme.schooltimetabling.TimetableApp; +import org.acme.schooltimetabling.domain.Lesson; +import org.acme.schooltimetabling.domain.Timetable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +@EnabledIfSystemProperty(named = "slowly", matches = "true") +class TimetableEnvironmentTest { + + @Test + void solveFullAssert() { + solve(EnvironmentMode.FULL_ASSERT); + } + + @Test + void solveFastAssert() { + solve(EnvironmentMode.FAST_ASSERT); + } + + void solve(EnvironmentMode environmentMode) { + SolverFactory<Timetable> solverFactory = SolverFactory.create(new SolverConfig() + .withSolutionClass(Timetable.class) + .withEntityClasses(Lesson.class) + .withConstraintProviderClass(TimetableConstraintProvider.class) + .withEnvironmentMode(environmentMode) + .withTerminationSpentLimit(Duration.ofSeconds(30))); + + // Load the problem + Timetable problem = generateDemoData(TimetableApp.DemoData.SMALL); + + // Solve the problem + Solver<Timetable> solver = solverFactory.buildSolver(); + Timetable solution = solver.solve(problem); + assertThat(solution.getScore()).isNotNull(); }
```suggestion assertThat(solution.getScore()).isNotNull(); } ```
timefold-quickstarts
github_2023
java
418
TimefoldAI
triceo
@@ -541,22 +535,6 @@ public void setCrowdControlRisk(int crowdControlRisk) { this.crowdControlRisk = crowdControlRisk; } - public Timeslot getPublishedTimeslot() { - return publishedTimeslot; - } - - public void setPublishedTimeslot(Timeslot publishedTimeslot) { - this.publishedTimeslot = publishedTimeslot; - } - - public Room getPublishedRoom() { - return publishedRoom; - } - - public void setPublishedRoom(Room publishedRoom) { - this.publishedRoom = publishedRoom; - } - public boolean isPinnedByUser() { return pinnedByUser; }
This is also related to publishing, isn't it? We don't have a feature in the UI to pin anything, so arguably the entire support for pinning can go too.
timefold-quickstarts
github_2023
java
402
TimefoldAI
triceo
@@ -0,0 +1,80 @@ +package org.acme.tournamentschedule.rest; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.stream.IntStream; + +import jakarta.enterprise.context.ApplicationScoped; + +import org.acme.tournamentschedule.domain.Day; +import org.acme.tournamentschedule.domain.Team; +import org.acme.tournamentschedule.domain.TeamAssignment; +import org.acme.tournamentschedule.domain.TournamentSchedule; +import org.acme.tournamentschedule.domain.UnavailabilityPenalty; + +@ApplicationScoped +public class DemoDataGenerator { + + private final Random random = new Random(0); + + public TournamentSchedule generateDemoData() { + TournamentSchedule schedule = new TournamentSchedule(); + // Teams + List<Team> teams = generateTeams(); + // Days + int countDays = 18; + List<Day> days = IntStream.range(0, countDays) + .mapToObj(Day::new) + .toList(); + // Unavailability penalty + int countUnavailabilityPenalties = 12; + List<UnavailabilityPenalty> unavailabilityPenalties = + generateUnavailabilityPenalties(countUnavailabilityPenalties, teams, days); + // Assignments + int countAssignmentsPerDay = 4; + List<TeamAssignment> teamAssignments = generateTeamAssignments(countAssignmentsPerDay, days); + // Update schedule + schedule.setTeams(teams); + schedule.setDays(days); + schedule.setUnavailabilityPenalties(unavailabilityPenalties); + schedule.setTeamAssignments(teamAssignments); + return schedule; + } + + private List<Team> generateTeams() { + return List.of( + new Team(0, "Micha"), + new Team(1, "Angelika"), + new Team(2, "Katrin"), + new Team(3, "Susi"), + new Team(4, "Irene"), + new Team(5, "Kristina"), + new Team(6, "Tobias"));
Maybe we want to use our own names? :-) Maarten, Geoffrey, Lukas, Chris, Fred, Radek, Maciej, ...
timefold-quickstarts
github_2023
others
402
TimefoldAI
triceo
@@ -0,0 +1,223 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.acme</groupId> + <artifactId>timefold-solver-quarkus-tournament-scheduling-quickstart</artifactId> + <version>1.0-SNAPSHOT</version> + + <properties> + <maven.compiler.release>17</maven.compiler.release> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + + <version.io.quarkus>3.9.3</version.io.quarkus>
```suggestion <version.io.quarkus>3.9.4</version.io.quarkus> ```
timefold-quickstarts
github_2023
others
397
TimefoldAI
triceo
@@ -0,0 +1,223 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.acme</groupId> + <artifactId>timefold-solver-quarkus-project-job-scheduling-quickstart</artifactId> + <version>1.0-SNAPSHOT</version> + + <properties> + <maven.compiler.release>17</maven.compiler.release> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + + <version.io.quarkus>3.8.3</version.io.quarkus>
```suggestion <version.io.quarkus>3.9.3</version.io.quarkus> ```
timefold-quickstarts
github_2023
java
397
TimefoldAI
triceo
@@ -0,0 +1,69 @@ +package org.acme.projectjobschedule.solver; + +import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.Joiners; + +import org.acme.projectjobschedule.domain.Allocation; +import org.acme.projectjobschedule.domain.JobType; +import org.acme.projectjobschedule.domain.ResourceRequirement; + +public class ProjectJobSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + nonRenewableResourceCapacity(constraintFactory), + renewableResourceCapacity(constraintFactory), + totalProjectDelay(constraintFactory), + totalMakespan(constraintFactory) + }; + } + + protected Constraint nonRenewableResourceCapacity(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ResourceRequirement.class) + .filter(resource -> !resource.isResourceRenewable()) + .join(Allocation.class, + Joiners.equal(ResourceRequirement::getExecutionMode, Allocation::getExecutionMode)) + .groupBy((requirement, allocation) -> requirement.getResource(), + ConstraintCollectors.sum((requirement, allocation) -> requirement.getRequirement())) + .filter((resource, requirements) -> requirements > resource.getCapacity()) + .penalize(HardMediumSoftScore.ONE_HARD, + (resource, requirements) -> requirements - resource.getCapacity()) + .asConstraint("Non-renewable resource capacity"); + } + + protected Constraint renewableResourceCapacity(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ResourceRequirement.class) + .filter(ResourceRequirement::isResourceRenewable) + .join(Allocation.class, + Joiners.equal(ResourceRequirement::getExecutionMode, Allocation::getExecutionMode)) + .flattenLast(Allocation::getBusyDates) + .groupBy((resourceReq, date) -> resourceReq.getResource(), + (resourceReq, date) -> date, + ConstraintCollectors.sum((resourceReq, date) -> resourceReq.getRequirement())) + .filter((resourceReq, date, totalRequirement) -> totalRequirement > resourceReq.getCapacity()) + .penalize(HardMediumSoftScore.ONE_HARD, + (resourceReq, date, totalRequirement) -> totalRequirement - resourceReq.getCapacity()) + .asConstraint("Renewable resource capacity"); + } + + protected Constraint totalProjectDelay(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Allocation.class) + .filter(allocation -> allocation.getEndDate() != null && allocation.getJobType() == JobType.SINK) + .impact(HardMediumSoftScore.ONE_MEDIUM, allocation -> allocation.getProjectCriticalPathEndDate() - allocation.getEndDate()) + .asConstraint("Total project delay"); + } +
I'm not exactly sure why we decided to make this an `impact` instead of a penalty, all those years ago. Can you think why this should be a positive number? If not, let's change the semantics and make it a penalty like anything else.
timefold-quickstarts
github_2023
java
390
TimefoldAI
triceo
@@ -0,0 +1,88 @@ +package org.acme.taskassigning.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.bendable.BendableScore; +import ai.timefold.solver.core.api.solver.SolverStatus; + +@PlanningSolution +public class TaskAssigningSolution { + + private List<TaskType> taskTypes; + + @ProblemFactCollectionProperty + private List<Customer> customers; + + @ValueRangeProvider + @PlanningEntityCollectionProperty + private List<Task> tasks; + + @PlanningEntityCollectionProperty + private List<Employee> employees; + + @PlanningScore(bendableHardLevelsSize = 1, bendableSoftLevelsSize = 5)
This is a bit crazy. I suggest we spend a bit of time thinking about the constraints and how they should be weighted against each other, and based on that, replace this with a normal `HardMediumSoftScore`.
timefold-quickstarts
github_2023
others
390
TimefoldAI
triceo
@@ -0,0 +1,229 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.acme</groupId> + <artifactId>timefold-solver-quarkus-task-assigning-quickstart</artifactId> + <version>1.0-SNAPSHOT</version> + + <properties> + <maven.compiler.release>17</maven.compiler.release> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + + <version.io.quarkus>3.8.3</version.io.quarkus>
```suggestion <version.io.quarkus>3.9.3</version.io.quarkus> ```
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,174 @@ +package org.acme.flighcrewscheduling.domain; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.SortedSet; +import java.util.TreeSet; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.lookup.PlanningId; +import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@PlanningEntity +@JsonIdentityInfo(scope = Employee.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") +public class Employee { + + @PlanningId + private String id; + private String name; + private Airport homeAirport; + + private List<String> skills; + private List<LocalDate> unavailableDays; + + @JsonIgnore + @InverseRelationShadowVariable(sourceVariableName = "employee") + private SortedSet<FlightAssignment> flightAssignments;
Do we need this to be `SortedSet`? Honestly it's the first time I'm seeing it used for this. Isn't `List` enough?
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,116 @@ +package org.acme.flighcrewscheduling.domain; + +import java.util.Comparator; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.lookup.PlanningId; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@PlanningEntity +public class FlightAssignment implements Comparable<FlightAssignment> { + + // Needs to be kept consistent with equals on account of Employee's flightAssignmentSet, which is a SortedSet. + private static final Comparator<FlightAssignment> COMPARATOR = Comparator.comparing(FlightAssignment::getFlight) + .thenComparing(FlightAssignment::getIndexInFlight);
And if we're no longer using `SortedSet`, we don't need these comparators, no? I'm really curious why we're using the sorted set.
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,280 @@ +package org.acme.flighcrewscheduling.rest; + +import static java.util.Collections.unmodifiableList; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.IntStream; + +import jakarta.enterprise.context.ApplicationScoped; + +import ai.timefold.solver.core.impl.util.MutableInt; + +import org.acme.flighcrewscheduling.domain.Airport; +import org.acme.flighcrewscheduling.domain.Employee; +import org.acme.flighcrewscheduling.domain.Flight; +import org.acme.flighcrewscheduling.domain.FlightAssignment; +import org.acme.flighcrewscheduling.domain.FlightCrewSchedule; + +@ApplicationScoped +public class DemoDataGenerator { + + private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay", + "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose", "Dena", "Jana", "Dave", + "Russ", "Josh", "Dana", "Katy" }; + private static final String[] LAST_NAMES = + { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe", "Lowe", "Wise", "Clay", + "Carr", "Hood", "Long", "Horn", "Haas", "Meza" }; + private static final String ATTENDANT_SKILL = "Flight attendant"; + private static final String PILOT_SKILL = "Pilot"; + private final Random random = new Random(0); + + public FlightCrewSchedule generateDemoData() { + FlightCrewSchedule schedule = new FlightCrewSchedule(); + // Airports + List<Airport> airports = List.of( + new Airport("LHR", "LHR", 51.4775, -0.461389), + new Airport("JFK", "JFK", 40.639722, -73.778889), + new Airport("CNF", "CNF", -19.624444, -43.971944), + new Airport("BRU", "BRU", 50.901389, 4.484444));
Let's add two more airports, to have move variety in the flights. `ATL` is massive, and `BNE` for Australia.
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,280 @@ +package org.acme.flighcrewscheduling.rest; + +import static java.util.Collections.unmodifiableList; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.IntStream; + +import jakarta.enterprise.context.ApplicationScoped; + +import ai.timefold.solver.core.impl.util.MutableInt; + +import org.acme.flighcrewscheduling.domain.Airport; +import org.acme.flighcrewscheduling.domain.Employee; +import org.acme.flighcrewscheduling.domain.Flight; +import org.acme.flighcrewscheduling.domain.FlightAssignment; +import org.acme.flighcrewscheduling.domain.FlightCrewSchedule; + +@ApplicationScoped +public class DemoDataGenerator { + + private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay", + "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose", "Dena", "Jana", "Dave", + "Russ", "Josh", "Dana", "Katy" }; + private static final String[] LAST_NAMES = + { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe", "Lowe", "Wise", "Clay", + "Carr", "Hood", "Long", "Horn", "Haas", "Meza" }; + private static final String ATTENDANT_SKILL = "Flight attendant"; + private static final String PILOT_SKILL = "Pilot"; + private final Random random = new Random(0); + + public FlightCrewSchedule generateDemoData() { + FlightCrewSchedule schedule = new FlightCrewSchedule(); + // Airports + List<Airport> airports = List.of( + new Airport("LHR", "LHR", 51.4775, -0.461389), + new Airport("JFK", "JFK", 40.639722, -73.778889), + new Airport("CNF", "CNF", -19.624444, -43.971944), + new Airport("BRU", "BRU", 50.901389, 4.484444)); + Map<String, Integer> distances = new HashMap<>();
You can use an arguably nicer syntax for this: Map.of( key, value, key, value, key, value, ...);
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,77 @@ +package org.acme.flighcrewscheduling.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.overlapping; + +import java.util.Collections; + +import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +import org.acme.flighcrewscheduling.domain.Employee; +import org.acme.flighcrewscheduling.domain.FlightAssignment; + +public class FlightCrewSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + requiredSkill(constraintFactory), + flightConflict(constraintFactory), + transferBetweenTwoFlights(constraintFactory), + employeeUnavailability(constraintFactory), + firstAssignmentNotDepartingFromHome(constraintFactory), + lastAssignmentNotArrivingAtHome(constraintFactory) + }; + } + + public Constraint requiredSkill(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(FlightAssignment.class) + .filter(flightAssignment -> !flightAssignment.hasRequiredSkills()) + .penalize(HardSoftLongScore.ofHard(100)) + .asConstraint("Required skill"); + } + + public Constraint flightConflict(ConstraintFactory constraintFactory) { + return constraintFactory.forEachUniquePair(FlightAssignment.class, + equal(FlightAssignment::getEmployee), + overlapping(flightAssignment -> flightAssignment.getFlight().getDepartureUTCDateTime(), + flightAssignment -> flightAssignment.getFlight().getArrivalUTCDateTime())) + .penalize(HardSoftLongScore.ofHard(10)) + .asConstraint("Flight conflict"); + } + + public Constraint transferBetweenTwoFlights(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Employee.class) + .expand(Employee::countInvalidConnections) + .filter((employee, invalidConnections) -> invalidConnections > 0) + .penalizeLong(HardSoftLongScore.ofHard(1), + (employee, invalidConnections) -> invalidConnections) + .indictWith((employee, invalidConnections) -> Collections.singleton(employee)) + .asConstraint("Transfer between two flights"); + } + + public Constraint employeeUnavailability(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(FlightAssignment.class) + .filter(FlightAssignment::isUnavailableEmployee) + .penalize(HardSoftLongScore.ofHard(10)) + .asConstraint("Employee unavailable"); + } + + public Constraint firstAssignmentNotDepartingFromHome(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Employee.class) + .filter(employee -> !employee.isFirstAssignmentDepartingFromHome()) + .penalize(HardSoftLongScore.ofSoft(1_000_000))
I'm wondering if we need so many significant digits. We've got 10, 100, so this could be 1_000.
timefold-quickstarts
github_2023
java
373
TimefoldAI
triceo
@@ -0,0 +1,77 @@ +package org.acme.flighcrewscheduling.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.overlapping; + +import java.util.Collections; + +import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +import org.acme.flighcrewscheduling.domain.Employee; +import org.acme.flighcrewscheduling.domain.FlightAssignment; + +public class FlightCrewSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + requiredSkill(constraintFactory), + flightConflict(constraintFactory), + transferBetweenTwoFlights(constraintFactory), + employeeUnavailability(constraintFactory), + firstAssignmentNotDepartingFromHome(constraintFactory), + lastAssignmentNotArrivingAtHome(constraintFactory) + }; + } + + public Constraint requiredSkill(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(FlightAssignment.class) + .filter(flightAssignment -> !flightAssignment.hasRequiredSkills()) + .penalize(HardSoftLongScore.ofHard(100)) + .asConstraint("Required skill"); + } + + public Constraint flightConflict(ConstraintFactory constraintFactory) { + return constraintFactory.forEachUniquePair(FlightAssignment.class, + equal(FlightAssignment::getEmployee), + overlapping(flightAssignment -> flightAssignment.getFlight().getDepartureUTCDateTime(), + flightAssignment -> flightAssignment.getFlight().getArrivalUTCDateTime())) + .penalize(HardSoftLongScore.ofHard(10)) + .asConstraint("Flight conflict"); + } + + public Constraint transferBetweenTwoFlights(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Employee.class) + .expand(Employee::countInvalidConnections) + .filter((employee, invalidConnections) -> invalidConnections > 0) + .penalizeLong(HardSoftLongScore.ofHard(1), + (employee, invalidConnections) -> invalidConnections) + .indictWith((employee, invalidConnections) -> Collections.singleton(employee)) + .asConstraint("Transfer between two flights"); + } + + public Constraint employeeUnavailability(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(FlightAssignment.class) + .filter(FlightAssignment::isUnavailableEmployee) + .penalize(HardSoftLongScore.ofHard(10)) + .asConstraint("Employee unavailable"); + } + + public Constraint firstAssignmentNotDepartingFromHome(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Employee.class) + .filter(employee -> !employee.isFirstAssignmentDepartingFromHome()) + .penalize(HardSoftLongScore.ofSoft(1_000_000)) + .asConstraint("First assignment not departing from home"); + } + + public Constraint lastAssignmentNotArrivingAtHome(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Employee.class) + .filter(employee -> !employee.isLastAssignmentArrivingAtHome()) + .penalize(HardSoftLongScore.ofSoft(1_000_000))
Dtto.
timefold-quickstarts
github_2023
others
380
TimefoldAI
triceo
@@ -0,0 +1,229 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.acme</groupId> + <artifactId>timefold-solver-quarkus-meeting-scheduling-quickstart</artifactId> + <version>1.0-SNAPSHOT</version> + + <properties> + <maven.compiler.release>17</maven.compiler.release> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + + <version.io.quarkus>3.9.1</version.io.quarkus>
We're back to 3.8.3 for now.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,255 @@ +package org.acme.meetingschedule.rest; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import jakarta.enterprise.context.ApplicationScoped; + +import ai.timefold.solver.core.impl.util.MutableInt; +import ai.timefold.solver.core.impl.util.Pair;
Let's not use internal classes from the solver. If you need a `Pair`, write the record yourself - it's trivial. The `MutableInt` is unnecessary.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,224 @@ +package org.acme.meetingschedule.solver; + +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 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.meetingschedule.domain.Attendance; +import org.acme.meetingschedule.domain.MeetingAssignment; +import org.acme.meetingschedule.domain.PreferredAttendance; +import org.acme.meetingschedule.domain.RequiredAttendance; +import org.acme.meetingschedule.domain.Room; +import org.acme.meetingschedule.domain.TimeGrain; + +public class MeetingSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + roomConflict(constraintFactory), + avoidOvertime(constraintFactory), + requiredAttendanceConflict(constraintFactory), + requiredRoomCapacity(constraintFactory), + startAndEndOnSameDay(constraintFactory), + requiredAndPreferredAttendanceConflict(constraintFactory), + preferredAttendanceConflict(constraintFactory), + doMeetingsAsSoonAsPossible(constraintFactory), + oneBreakBetweenConsecutiveMeetings(constraintFactory), + overlappingMeetings(constraintFactory), + assignLargerRoomsFirst(constraintFactory), + roomStability(constraintFactory) + }; + } + + // ************************************************************************ + // Hard constraints + // ************************************************************************ + + public Constraint roomConflict(ConstraintFactory constraintFactory) { + return constraintFactory.forEachUniquePair(MeetingAssignment.class, + equal(MeetingAssignment::getRoom), + overlapping(assignment -> assignment.getStartingTimeGrain().getGrainIndex(), + assignment -> assignment.getStartingTimeGrain().getGrainIndex() + + assignment.getMeeting().getDurationInGrains())) + .penalizeConfigurable((leftAssignment, rightAssignment) -> rightAssignment.calculateOverlap(leftAssignment)) + .asConstraint("Room conflict"); + } + + public Constraint avoidOvertime(ConstraintFactory constraintFactory) { + return constraintFactory.forEachIncludingUnassigned(MeetingAssignment.class) + .filter(meetingAssignment -> meetingAssignment.getStartingTimeGrain() != null) + .ifNotExists(TimeGrain.class, + equal(MeetingAssignment::getLastTimeGrainIndex, TimeGrain::getGrainIndex)) + .penalizeConfigurable(MeetingAssignment::getLastTimeGrainIndex) + .asConstraint("Don't go in overtime"); + } + + public Constraint requiredAttendanceConflict(ConstraintFactory constraintFactory) { + return constraintFactory.forEachUniquePair(RequiredAttendance.class, + equal(RequiredAttendance::getPerson)) + .join(MeetingAssignment.class, + equal((leftRequiredAttendance, rightRequiredAttendance) -> leftRequiredAttendance.getMeeting(), + MeetingAssignment::getMeeting)) + .join(MeetingAssignment.class, + equal((leftRequiredAttendance, rightRequiredAttendance, leftAssignment) -> rightRequiredAttendance + .getMeeting(), + MeetingAssignment::getMeeting), + overlapping((attendee1, attendee2, assignment) -> assignment.getStartingTimeGrain().getGrainIndex(), + (attendee1, attendee2, assignment) -> assignment.getStartingTimeGrain().getGrainIndex() + + assignment.getMeeting().getDurationInGrains(), + assignment -> assignment.getStartingTimeGrain().getGrainIndex(), + assignment -> assignment.getStartingTimeGrain().getGrainIndex() +
the grainIndex+durationInGrains is repeated so often that I think it would warrant a getter on assignment.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -333,4 +331,51 @@ private <T, L> void applyRandomValue(int count, List<T> values, L secondParam, P } } } + + private record Pair<Key_, Value_>(Key_ key, Value_ value) { + public Pair(Key_ key, Value_ value) { + this.key = key; + this.value = value; + } + + public Key_ key() { + return this.key; + } + + public Value_ value() { + return this.value; + } + } + + private final class MutableReference<Value_> { + private Value_ value; + + public MutableReference(Value_ value) { + this.value = value; + } + + public Value_ getValue() { + return this.value; + } + + public void setValue(Value_ value) { + this.value = value; + } + + public boolean equals(Object o) { + if (o instanceof MutableReference<?> other) { + return this.value.equals(other.value); + } else { + return false; + } + } + + public int hashCode() { + return Objects.hash(this.value); + } + + public String toString() { + return this.value.toString(); + } + }
Considering that this is a quickstart, let's refactor the code so that mutable references aren't necessary. Every time you have to ask yourself "why is this here?" and the answer is not directly related to the idea you want to show the users, remove the thing.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -333,4 +331,51 @@ private <T, L> void applyRandomValue(int count, List<T> values, L secondParam, P } } } + + private record Pair<Key_, Value_>(Key_ key, Value_ value) { + public Pair(Key_ key, Value_ value) { + this.key = key; + this.value = value; + } + + public Key_ key() { + return this.key; + } + + public Value_ value() { + return this.value; + }
It's a record; these are not necessary.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,135 @@ +package org.acme.meetingschedule.domain; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@JsonIdentityInfo(scope = Meeting.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") +public class Meeting { + + private String id; + private String topic; + private List<Person> speakers; + private String content; + private boolean entireGroupMeeting; + /** + * Multiply by {@link TimeGrain#GRAIN_LENGTH_IN_MINUTES} to get duration in minutes. + */ + private int durationInGrains; + + private List<RequiredAttendance> requiredAttendances; + private List<PreferredAttendance> preferredAttendances; + + public Meeting() { + } + + public Meeting(String id) { + this.id = id; + this.requiredAttendances = new ArrayList<>(); + this.preferredAttendances = new ArrayList<>(); + } + + public Meeting(String id, String topic) { + this(id); + this.topic = topic; + } + + public Meeting(String id, String topic, int durationInGrains) { + this(id); + this.topic = topic; + this.durationInGrains = durationInGrains; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public List<Person> getSpeakers() { + return speakers; + } + + public void setSpeakers(List<Person> speakers) { + this.speakers = speakers; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public boolean isEntireGroupMeeting() { + return entireGroupMeeting; + } + + public void setEntireGroupMeeting(boolean entireGroupMeeting) { + this.entireGroupMeeting = entireGroupMeeting; + } + + public int getDurationInGrains() { + return durationInGrains; + } + + public void setDurationInGrains(int durationInGrains) { + this.durationInGrains = durationInGrains; + } + + public List<RequiredAttendance> getRequiredAttendances() { + return requiredAttendances; + } + + public void setRequiredAttendances(List<RequiredAttendance> requiredAttendances) { + this.requiredAttendances = requiredAttendances; + } + + public List<PreferredAttendance> getPreferredAttendances() { + return preferredAttendances; + } + + public void setPreferredAttendances(List<PreferredAttendance> preferredAttendances) { + this.preferredAttendances = preferredAttendances; + } + + // ************************************************************************ + // Complex methods + // ************************************************************************ + + @JsonIgnore + public int getRequiredCapacity() { + return requiredAttendances.size() + preferredAttendances.size(); + } + + public void addAttendant(String id, Person person, boolean isRequired) { + if (isRequired) { + if (requiredAttendances.stream().noneMatch(r -> r.getPerson().equals(person))) { + requiredAttendances.add(new RequiredAttendance(id, this, person)); + } + } else { + if (preferredAttendances.stream().noneMatch(r -> r.getPerson().equals(person))) { + preferredAttendances.add(new PreferredAttendance(id, this, person)); + } + } + }
I see two options here: - Either don't check if the person is already present. - Or if you want to check for that, do something if the person is already present. Fail, perhaps. Also, instead of this if switch, I'd rather turn this into two methods - add required attendant, add preferred attendant. See how the `isRequired` method parameter effectively makes it two different methods? There is no shared code inside of the method.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,152 @@ +package org.acme.meetingschedule.domain; + +import java.util.Objects; + +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.variable.PlanningVariable; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@PlanningEntity +public class MeetingAssignment { + + private String id; + private Meeting meeting; + private boolean pinned; + + // Planning variables: changes during planning, between score calculations. + private TimeGrain startingTimeGrain; + private Room room; + + public MeetingAssignment() { + } + + public MeetingAssignment(String id) { + this.id = id; + } + + public MeetingAssignment(String id, Meeting meeting) { + this(id); + this.meeting = meeting; + } + + public MeetingAssignment(String id, Meeting meeting, TimeGrain startingTimeGrain, Room room) { + this(id, meeting); + this.startingTimeGrain = startingTimeGrain; + this.room = room; + } + + @PlanningId + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Meeting getMeeting() { + return meeting; + } + + public void setMeeting(Meeting meeting) { + this.meeting = meeting; + } + + @PlanningPin + public boolean isPinned() { + return pinned; + } + + public void setPinned(boolean pinned) { + this.pinned = pinned; + } + + @PlanningVariable + public TimeGrain getStartingTimeGrain() { + return startingTimeGrain; + } + + public void setStartingTimeGrain(TimeGrain startingTimeGrain) { + this.startingTimeGrain = startingTimeGrain; + } + + @PlanningVariable + public Room getRoom() { + return room; + } + + public void setRoom(Room room) { + this.room = room; + } + + // ************************************************************************ + // Complex methods + // ************************************************************************ + + @JsonIgnore + public int getGrainIndex() { + return getStartingTimeGrain().getGrainIndex(); + } + + @JsonIgnore + public int calculateOverlap(MeetingAssignment other) { + if (startingTimeGrain == null || other.getStartingTimeGrain() == null) { + return 0; + } + // start is inclusive, end is exclusive + int start = startingTimeGrain.getGrainIndex(); + int otherStart = other.startingTimeGrain.getGrainIndex(); + int otherEnd = otherStart + other.meeting.getDurationInGrains();
Didn't we add a method for this?
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,152 @@ +package org.acme.meetingschedule.domain; + +import java.util.Objects; + +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.variable.PlanningVariable; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@PlanningEntity +public class MeetingAssignment { + + private String id; + private Meeting meeting; + private boolean pinned; + + // Planning variables: changes during planning, between score calculations. + private TimeGrain startingTimeGrain; + private Room room; + + public MeetingAssignment() { + } + + public MeetingAssignment(String id) { + this.id = id; + } + + public MeetingAssignment(String id, Meeting meeting) { + this(id); + this.meeting = meeting; + } + + public MeetingAssignment(String id, Meeting meeting, TimeGrain startingTimeGrain, Room room) { + this(id, meeting); + this.startingTimeGrain = startingTimeGrain; + this.room = room; + } + + @PlanningId + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Meeting getMeeting() { + return meeting; + } + + public void setMeeting(Meeting meeting) { + this.meeting = meeting; + } + + @PlanningPin + public boolean isPinned() { + return pinned; + } + + public void setPinned(boolean pinned) { + this.pinned = pinned; + } + + @PlanningVariable + public TimeGrain getStartingTimeGrain() { + return startingTimeGrain; + } + + public void setStartingTimeGrain(TimeGrain startingTimeGrain) { + this.startingTimeGrain = startingTimeGrain; + } + + @PlanningVariable + public Room getRoom() { + return room; + } + + public void setRoom(Room room) { + this.room = room; + } + + // ************************************************************************ + // Complex methods + // ************************************************************************ + + @JsonIgnore + public int getGrainIndex() { + return getStartingTimeGrain().getGrainIndex(); + } + + @JsonIgnore + public int calculateOverlap(MeetingAssignment other) { + if (startingTimeGrain == null || other.getStartingTimeGrain() == null) { + return 0; + } + // start is inclusive, end is exclusive + int start = startingTimeGrain.getGrainIndex(); + int otherStart = other.startingTimeGrain.getGrainIndex(); + int otherEnd = otherStart + other.meeting.getDurationInGrains(); + if (otherEnd < start) { + return 0; + } + int end = start + meeting.getDurationInGrains();
Dtto.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,152 @@ +package org.acme.meetingschedule.domain; + +import java.util.Objects; + +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.variable.PlanningVariable; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@PlanningEntity +public class MeetingAssignment { + + private String id; + private Meeting meeting; + private boolean pinned; + + // Planning variables: changes during planning, between score calculations. + private TimeGrain startingTimeGrain; + private Room room; + + public MeetingAssignment() { + } + + public MeetingAssignment(String id) { + this.id = id; + } + + public MeetingAssignment(String id, Meeting meeting) { + this(id); + this.meeting = meeting; + } + + public MeetingAssignment(String id, Meeting meeting, TimeGrain startingTimeGrain, Room room) { + this(id, meeting); + this.startingTimeGrain = startingTimeGrain; + this.room = room; + } + + @PlanningId + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Meeting getMeeting() { + return meeting; + } + + public void setMeeting(Meeting meeting) { + this.meeting = meeting; + } + + @PlanningPin + public boolean isPinned() { + return pinned; + } + + public void setPinned(boolean pinned) { + this.pinned = pinned; + } + + @PlanningVariable + public TimeGrain getStartingTimeGrain() { + return startingTimeGrain; + } + + public void setStartingTimeGrain(TimeGrain startingTimeGrain) { + this.startingTimeGrain = startingTimeGrain; + } + + @PlanningVariable + public Room getRoom() { + return room; + } + + public void setRoom(Room room) { + this.room = room; + } + + // ************************************************************************ + // Complex methods + // ************************************************************************ + + @JsonIgnore + public int getGrainIndex() { + return getStartingTimeGrain().getGrainIndex(); + } + + @JsonIgnore + public int calculateOverlap(MeetingAssignment other) { + if (startingTimeGrain == null || other.getStartingTimeGrain() == null) { + return 0; + } + // start is inclusive, end is exclusive + int start = startingTimeGrain.getGrainIndex(); + int otherStart = other.startingTimeGrain.getGrainIndex(); + int otherEnd = otherStart + other.meeting.getDurationInGrains(); + if (otherEnd < start) { + return 0; + } + int end = start + meeting.getDurationInGrains(); + if (end < otherStart) { + return 0; + } + return Math.min(end, otherEnd) - Math.max(start, otherStart); + } + + @JsonIgnore + public Integer getLastTimeGrainIndex() {
Arguably if the counterpart to this is called `getStarting...`, this one should be `getEnding...`. Or they should be first/last. But it should be mutually consistent.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,134 @@ +package org.acme.meetingschedule.domain; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Comparator; +import java.util.Locale; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.lookup.PlanningId; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@JsonIdentityInfo(scope = TimeGrain.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") +public class TimeGrain implements Comparable<TimeGrain> { + + private static final Comparator<TimeGrain> COMPARATOR = Comparator.comparing(TimeGrain::getDayOfYear) + .thenComparingInt(TimeGrain::getStartingMinuteOfDay);
Why is `TimeGrain` comparable and can we do anything to stop it?
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,134 @@ +package org.acme.meetingschedule.domain; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Comparator; +import java.util.Locale; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.lookup.PlanningId; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@JsonIdentityInfo(scope = TimeGrain.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") +public class TimeGrain implements Comparable<TimeGrain> { + + private static final Comparator<TimeGrain> COMPARATOR = Comparator.comparing(TimeGrain::getDayOfYear) + .thenComparingInt(TimeGrain::getStartingMinuteOfDay); + + private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("E", Locale.ENGLISH); + + /** + * Time granularity is 15 minutes (which is often recommended when dealing with humans for practical purposes). + */ + public static final int GRAIN_LENGTH_IN_MINUTES = 15; + + @PlanningId + private String id; + private int grainIndex; + private Integer dayOfYear; + private int startingMinuteOfDay; + + public TimeGrain() { + } + + public TimeGrain(String id) { + this.id = id; + } + + public TimeGrain(String id, int grainIndex, Integer dayOfYear, int startingMinuteOfDay) { + this(id); + this.grainIndex = grainIndex; + this.dayOfYear = dayOfYear; + this.startingMinuteOfDay = startingMinuteOfDay; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getGrainIndex() { + return grainIndex; + } + + public void setGrainIndex(int grainIndex) { + this.grainIndex = grainIndex; + } + + public Integer getDayOfYear() { + return dayOfYear; + } + + public void setDayOfYear(Integer dayOfYear) { + this.dayOfYear = dayOfYear; + } + + public int getStartingMinuteOfDay() { + return startingMinuteOfDay; + } + + public void setStartingMinuteOfDay(int startingMinuteOfDay) { + this.startingMinuteOfDay = startingMinuteOfDay; + } + + @JsonIgnore + public LocalDate getDate() { + return LocalDate.now().withDayOfYear(dayOfYear); + } + + @JsonIgnore + public LocalTime getTime() { + return LocalTime.of(startingMinuteOfDay / 60, startingMinuteOfDay % 60); + } + + @JsonIgnore + public String getTimeString() { + int hourOfDay = startingMinuteOfDay / 60; + int minuteOfHour = startingMinuteOfDay % 60; + return (hourOfDay < 10 ? "0" : "") + hourOfDay + + ":" + (minuteOfHour < 10 ? "0" : "") + minuteOfHour; + } + + @JsonIgnore + public String getDateTimeString() { + return DAY_FORMATTER.format(getDate()) + " " + getTimeString(); + }
Do we need this anywhere? What for?
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,268 @@ +package org.acme.meetingschedule.rest; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import jakarta.enterprise.context.ApplicationScoped; + +import org.acme.meetingschedule.domain.Meeting; +import org.acme.meetingschedule.domain.MeetingAssignment; +import org.acme.meetingschedule.domain.MeetingConstraintConfiguration; +import org.acme.meetingschedule.domain.MeetingSchedule; +import org.acme.meetingschedule.domain.Person; +import org.acme.meetingschedule.domain.Room; +import org.acme.meetingschedule.domain.TimeGrain; +import org.apache.commons.lang3.mutable.MutableInt; + +@ApplicationScoped +public class DemoDataGenerator { + + private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay", + "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose", "Dena", "Jana", "Dave", + "Russ", "Josh", "Dana", "Katy" }; + private static final String[] LAST_NAMES = + { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe", "Lowe", "Wise", "Clay", + "Carr", "Hood", "Long", "Horn", "Haas", "Meza" }; + private final Random random = new Random(0); + + public MeetingSchedule generateDemoData() { + MeetingSchedule schedule = new MeetingSchedule(); + schedule.setConstraintConfiguration(new MeetingConstraintConfiguration()); + // People + int countPeople = 40; + List<Person> people = generatePeople(countPeople); + // Time grain + List<TimeGrain> timeGrains = generateTimeGrain(); + // Rooms + List<Room> rooms = List.of( + new Room("R1", "Room 1", 30), + new Room("R2", "Room 2", 20), + new Room("R3", "Room 3", 16), + new Room("R4", "Room 4", 14), + new Room("R5", "Room 5", 12)); + // Meetings + List<Meeting> meetings = generateMeetings(people); + // Meeting assignments + List<MeetingAssignment> meetingAssignments = generateMeetingAssignments(meetings); + // Update schedule + schedule.setRooms(rooms); + schedule.setPeople(people); + schedule.setTimeGrains(timeGrains); + schedule.setMeetings(meetings); + schedule.setMeetingAssignments(meetingAssignments); + schedule.setAttendances(Stream.concat( + schedule.getMeetings().stream().flatMap(m -> m.getRequiredAttendances().stream()), + schedule.getMeetings().stream().flatMap(m -> m.getPreferredAttendances().stream())) + .toList()); + return schedule; + } + + private List<Person> generatePeople(int countPeople) { + 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; + }; + + return IntStream.range(0, countPeople) + .mapToObj(i -> new Person(String.valueOf(i), nameSupplier.get())) + .toList(); + } + + private List<TimeGrain> generateTimeGrain() { + List<TimeGrain> timeGrains = new ArrayList<>(); + LocalDate currentDate = LocalDate.now().plusDays(1); + int count = 0; + while (currentDate.isBefore(LocalDate.now().plusDays(6))) { + LocalTime currentTime = LocalTime.of(8, 0); + timeGrains.add(new TimeGrain(String.valueOf(++count), count, + LocalDateTime.of(currentDate, currentTime).getDayOfYear(), + currentTime.getHour() * 60 + currentTime.getMinute())); + while (currentTime.isBefore(LocalTime.of(17, 45))) { + currentTime = currentTime.plusMinutes(15); + timeGrains.add(new TimeGrain(String.valueOf(++count), count, + LocalDateTime.of(currentDate, currentTime).getDayOfYear(), + currentTime.getHour() * 60 + currentTime.getMinute())); + } + currentDate = currentDate.plusDays(1); + } + return timeGrains; + } + + private List<Meeting> generateMeetings(List<Person> people) { + int count = 0; + List<Meeting> meetings = List.of( + new Meeting(String.valueOf(count++), "Strategize B2B"), + new Meeting(String.valueOf(count++), "Fast track e-business"), + new Meeting(String.valueOf(count++), "Cross sell virtualization"), + new Meeting(String.valueOf(count++), "Profitize multitasking"), + new Meeting(String.valueOf(count++), "Transform one stop shop"), + new Meeting(String.valueOf(count++), "Engage braindumps"), + new Meeting(String.valueOf(count++), "Downsize data mining"), + new Meeting(String.valueOf(count++), "Ramp up policies"), + new Meeting(String.valueOf(count++), "On board synergies"), + new Meeting(String.valueOf(count++), "Reinvigorate user experience"), + new Meeting(String.valueOf(count++), "Strategize e-business"), + new Meeting(String.valueOf(count++), "Fast track virtualization"), + new Meeting(String.valueOf(count++), "Cross sell multitasking"), + new Meeting(String.valueOf(count++), "Profitize one stop shop"), + new Meeting(String.valueOf(count++), "Transform braindumps"), + new Meeting(String.valueOf(count++), "Engage data mining"), + new Meeting(String.valueOf(count++), "Downsize policies"), + new Meeting(String.valueOf(count++), "Ramp up synergies"), + new Meeting(String.valueOf(count++), "On board user experience"), + new Meeting(String.valueOf(count++), "Reinvigorate B2B"), + new Meeting(String.valueOf(count++), "Strategize virtualization"), + new Meeting(String.valueOf(count++), "Fast track multitasking"), + new Meeting(String.valueOf(count++), "Cross sell one stop shop"), + new Meeting(String.valueOf(count++), "Profitize braindumps"), + new Meeting(String.valueOf(count++), "Transform data mining"), + new Meeting(String.valueOf(count++), "Engage policies"), + new Meeting(String.valueOf(count++), "Downsize synergies"), + new Meeting(String.valueOf(count++), "Ramp up user experience"), + new Meeting(String.valueOf(count++), "On board B2B"), + new Meeting(String.valueOf(count++), "Reinvigorate e-business"), + new Meeting(String.valueOf(count++), "Strategize multitasking"), + new Meeting(String.valueOf(count++), "Fast track one stop shop"), + new Meeting(String.valueOf(count++), "Cross sell braindumps"), + new Meeting(String.valueOf(count++), "Profitize data mining"), + new Meeting(String.valueOf(count++), "Transform policies"), + new Meeting(String.valueOf(count++), "Engage synergies"), + new Meeting(String.valueOf(count++), "Downsize user experience"), + new Meeting(String.valueOf(count++), "Ramp up B2B"), + new Meeting(String.valueOf(count++), "On board e-business"), + new Meeting(String.valueOf(count), "Reinvigorate multitasking")); + // Duration + List<Pair<Float, Integer>> durationGrainsCount = List.of( + new Pair<>(0.33f, 8), + new Pair<>(0.33f, 12), + new Pair<>(0.33f, 16)); + durationGrainsCount.forEach(p -> applyRandomValue((int) (p.key() * meetings.size()), meetings, + m -> m.getDurationInGrains() == 0, m -> m.setDurationInGrains(p.value()))); + // Ensure there are no empty duration + meetings.stream() + .filter(m -> m.getDurationInGrains() == 0) + .forEach(m -> m.setDurationInGrains(8)); + // Attendants + MutableInt attendantCount = new MutableInt();
If you don't use lambdas so much, you won't have to complicate your code with mutable references.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,268 @@ +package org.acme.meetingschedule.rest; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import jakarta.enterprise.context.ApplicationScoped; + +import org.acme.meetingschedule.domain.Meeting; +import org.acme.meetingschedule.domain.MeetingAssignment; +import org.acme.meetingschedule.domain.MeetingConstraintConfiguration; +import org.acme.meetingschedule.domain.MeetingSchedule; +import org.acme.meetingschedule.domain.Person; +import org.acme.meetingschedule.domain.Room; +import org.acme.meetingschedule.domain.TimeGrain; +import org.apache.commons.lang3.mutable.MutableInt; + +@ApplicationScoped +public class DemoDataGenerator { + + private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay", + "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose", "Dena", "Jana", "Dave", + "Russ", "Josh", "Dana", "Katy" }; + private static final String[] LAST_NAMES = + { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe", "Lowe", "Wise", "Clay", + "Carr", "Hood", "Long", "Horn", "Haas", "Meza" }; + private final Random random = new Random(0); + + public MeetingSchedule generateDemoData() { + MeetingSchedule schedule = new MeetingSchedule(); + schedule.setConstraintConfiguration(new MeetingConstraintConfiguration()); + // People + int countPeople = 40; + List<Person> people = generatePeople(countPeople); + // Time grain + List<TimeGrain> timeGrains = generateTimeGrain(); + // Rooms + List<Room> rooms = List.of( + new Room("R1", "Room 1", 30), + new Room("R2", "Room 2", 20), + new Room("R3", "Room 3", 16), + new Room("R4", "Room 4", 14), + new Room("R5", "Room 5", 12)); + // Meetings + List<Meeting> meetings = generateMeetings(people); + // Meeting assignments + List<MeetingAssignment> meetingAssignments = generateMeetingAssignments(meetings); + // Update schedule + schedule.setRooms(rooms); + schedule.setPeople(people); + schedule.setTimeGrains(timeGrains); + schedule.setMeetings(meetings); + schedule.setMeetingAssignments(meetingAssignments); + schedule.setAttendances(Stream.concat( + schedule.getMeetings().stream().flatMap(m -> m.getRequiredAttendances().stream()), + schedule.getMeetings().stream().flatMap(m -> m.getPreferredAttendances().stream())) + .toList()); + return schedule; + } + + private List<Person> generatePeople(int countPeople) { + 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; + }; + + return IntStream.range(0, countPeople) + .mapToObj(i -> new Person(String.valueOf(i), nameSupplier.get())) + .toList(); + } + + private List<TimeGrain> generateTimeGrain() { + List<TimeGrain> timeGrains = new ArrayList<>(); + LocalDate currentDate = LocalDate.now().plusDays(1); + int count = 0; + while (currentDate.isBefore(LocalDate.now().plusDays(6))) { + LocalTime currentTime = LocalTime.of(8, 0); + timeGrains.add(new TimeGrain(String.valueOf(++count), count, + LocalDateTime.of(currentDate, currentTime).getDayOfYear(), + currentTime.getHour() * 60 + currentTime.getMinute())); + while (currentTime.isBefore(LocalTime.of(17, 45))) { + currentTime = currentTime.plusMinutes(15); + timeGrains.add(new TimeGrain(String.valueOf(++count), count, + LocalDateTime.of(currentDate, currentTime).getDayOfYear(), + currentTime.getHour() * 60 + currentTime.getMinute())); + } + currentDate = currentDate.plusDays(1); + } + return timeGrains; + } + + private List<Meeting> generateMeetings(List<Person> people) { + int count = 0; + List<Meeting> meetings = List.of( + new Meeting(String.valueOf(count++), "Strategize B2B"), + new Meeting(String.valueOf(count++), "Fast track e-business"), + new Meeting(String.valueOf(count++), "Cross sell virtualization"), + new Meeting(String.valueOf(count++), "Profitize multitasking"), + new Meeting(String.valueOf(count++), "Transform one stop shop"), + new Meeting(String.valueOf(count++), "Engage braindumps"), + new Meeting(String.valueOf(count++), "Downsize data mining"), + new Meeting(String.valueOf(count++), "Ramp up policies"), + new Meeting(String.valueOf(count++), "On board synergies"), + new Meeting(String.valueOf(count++), "Reinvigorate user experience"), + new Meeting(String.valueOf(count++), "Strategize e-business"), + new Meeting(String.valueOf(count++), "Fast track virtualization"), + new Meeting(String.valueOf(count++), "Cross sell multitasking"), + new Meeting(String.valueOf(count++), "Profitize one stop shop"), + new Meeting(String.valueOf(count++), "Transform braindumps"), + new Meeting(String.valueOf(count++), "Engage data mining"), + new Meeting(String.valueOf(count++), "Downsize policies"), + new Meeting(String.valueOf(count++), "Ramp up synergies"), + new Meeting(String.valueOf(count++), "On board user experience"), + new Meeting(String.valueOf(count++), "Reinvigorate B2B"), + new Meeting(String.valueOf(count++), "Strategize virtualization"), + new Meeting(String.valueOf(count++), "Fast track multitasking"), + new Meeting(String.valueOf(count++), "Cross sell one stop shop"), + new Meeting(String.valueOf(count++), "Profitize braindumps"), + new Meeting(String.valueOf(count++), "Transform data mining"), + new Meeting(String.valueOf(count++), "Engage policies"), + new Meeting(String.valueOf(count++), "Downsize synergies"), + new Meeting(String.valueOf(count++), "Ramp up user experience"), + new Meeting(String.valueOf(count++), "On board B2B"), + new Meeting(String.valueOf(count++), "Reinvigorate e-business"), + new Meeting(String.valueOf(count++), "Strategize multitasking"), + new Meeting(String.valueOf(count++), "Fast track one stop shop"), + new Meeting(String.valueOf(count++), "Cross sell braindumps"), + new Meeting(String.valueOf(count++), "Profitize data mining"), + new Meeting(String.valueOf(count++), "Transform policies"), + new Meeting(String.valueOf(count++), "Engage synergies"), + new Meeting(String.valueOf(count++), "Downsize user experience"), + new Meeting(String.valueOf(count++), "Ramp up B2B"), + new Meeting(String.valueOf(count++), "On board e-business"), + new Meeting(String.valueOf(count), "Reinvigorate multitasking")); + // Duration + List<Pair<Float, Integer>> durationGrainsCount = List.of( + new Pair<>(0.33f, 8), + new Pair<>(0.33f, 12), + new Pair<>(0.33f, 16)); + durationGrainsCount.forEach(p -> applyRandomValue((int) (p.key() * meetings.size()), meetings, + m -> m.getDurationInGrains() == 0, m -> m.setDurationInGrains(p.value()))); + // Ensure there are no empty duration + meetings.stream() + .filter(m -> m.getDurationInGrains() == 0) + .forEach(m -> m.setDurationInGrains(8)); + // Attendants + MutableInt attendantCount = new MutableInt(); + // Required + BiConsumer<Meeting, Integer> requiredAttendantConsumer = (meeting, size) -> { + do { + int nextPerson = random.nextInt(people.size()); + meeting.addAttendant(String.valueOf(attendantCount.incrementAndGet()), people.get(nextPerson), true); + } while (meeting.getRequiredAttendances().size() < size); + }; + List<Pair<Float, Integer>> requiredAttendantsCount = List.of( + new Pair<>(0.36f, 2), // 36% with two attendants + new Pair<>(0.08f, 3), // 8% with three attendants, etc + new Pair<>(0.02f, 4), + new Pair<>(0.08f, 5), + new Pair<>(0.08f, 6), + new Pair<>(0.03f, 7), + new Pair<>(0.02f, 8), + new Pair<>(0.02f, 11), + new Pair<>(0.03f, 12), + new Pair<>(0.02f, 13), + new Pair<>(0.03f, 14), + new Pair<>(0.02f, 15), + new Pair<>(0.02f, 17), + new Pair<>(0.02f, 19)); + requiredAttendantsCount.forEach(p -> applyRandomValue((int) (p.key() * meetings.size()), meetings, p.value(), + m -> m.getRequiredAttendances().isEmpty(), requiredAttendantConsumer)); + // Ensure there are no empty required attendants + meetings.stream() + .filter(m -> m.getRequiredAttendances() == null) + .forEach(m -> requiredAttendantConsumer.accept(m, 2)); + // Preferred + BiConsumer<Meeting, Integer> preferredAttendantConsumer = (meeting, size) -> { + do { + int nextPerson = random.nextInt(people.size()); + if (meeting.getRequiredAttendances().stream() + .noneMatch(requiredAttendance -> requiredAttendance.getPerson().equals(people.get(nextPerson)))) { + meeting.addAttendant(String.valueOf(attendantCount.incrementAndGet()), people.get(nextPerson), false); + } + } while (meeting.getPreferredAttendances().size() < size); + }; + List<Pair<Float, Integer>> preferredAttendantsCount = List.of( + new Pair<>(0.06f, 1), // 6% with one attendant + new Pair<>(0.2f, 2), // 20% with two attendants, etc + new Pair<>(0.18f, 3), + new Pair<>(0.06f, 4), + new Pair<>(0.04f, 5), + new Pair<>(0.02f, 6), + new Pair<>(0.02f, 7), + new Pair<>(0.02f, 8), + new Pair<>(0.06f, 9), + new Pair<>(0.02f, 10), + new Pair<>(0.04f, 11), + new Pair<>(0.02f, 14), + new Pair<>(0.02f, 15), + new Pair<>(0.02f, 19), + new Pair<>(0.02f, 24)); + preferredAttendantsCount.forEach(p -> applyRandomValue((int) (p.key() * meetings.size()), meetings, p.value(), + m -> m.getPreferredAttendances().isEmpty(), preferredAttendantConsumer)); + return meetings; + } + + private List<MeetingAssignment> generateMeetingAssignments(List<Meeting> meetings) { + return IntStream.range(0, meetings.size()) + .mapToObj(i -> new MeetingAssignment(String.valueOf(i), meetings.get(i))) + .toList(); + } + + private <T> void applyRandomValue(int count, List<T> values, Predicate<T> filter, Consumer<T> consumer) { + int size = (int) values.stream().filter(filter).count(); + for (int i = 0; i < count; i++) { + values.stream() + .filter(filter) + .skip(size > 0 ? random.nextInt(size) : 0).findFirst() + .ifPresent(consumer::accept); + size--; + if (size < 0) { + break; + } + } + } + + private <T, L> void applyRandomValue(int count, List<T> values, L secondParam, Predicate<T> filter, + BiConsumer<T, L> consumer) { + int size = (int) values.stream().filter(filter).count(); + for (int i = 0; i < count; i++) { + values.stream() + .filter(filter) + .skip(size > 0 ? random.nextInt(size) : 0).findFirst() + .ifPresent(v -> consumer.accept(v, secondParam)); + size--; + if (size < 0) { + break; + } + } + } + + private record Pair<Key_, Value_>(Key_ key, Value_ value) { + public Pair(Key_ key, Value_ value) { + this.key = key; + this.value = value; + } + + public Key_ key() { + return this.key; + } + + public Value_ value() { + return this.value; + }
Records don't need these.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -0,0 +1,224 @@ +package org.acme.meetingschedule.solver; + +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 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.meetingschedule.domain.Attendance; +import org.acme.meetingschedule.domain.MeetingAssignment; +import org.acme.meetingschedule.domain.PreferredAttendance; +import org.acme.meetingschedule.domain.RequiredAttendance; +import org.acme.meetingschedule.domain.Room; +import org.acme.meetingschedule.domain.TimeGrain; + +public class MeetingSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + roomConflict(constraintFactory), + avoidOvertime(constraintFactory), + requiredAttendanceConflict(constraintFactory), + requiredRoomCapacity(constraintFactory), + startAndEndOnSameDay(constraintFactory), + requiredAndPreferredAttendanceConflict(constraintFactory), + preferredAttendanceConflict(constraintFactory), + doMeetingsAsSoonAsPossible(constraintFactory), + oneBreakBetweenConsecutiveMeetings(constraintFactory), + overlappingMeetings(constraintFactory), + assignLargerRoomsFirst(constraintFactory), + roomStability(constraintFactory) + }; + } + + // ************************************************************************ + // Hard constraints + // ************************************************************************ + + public Constraint roomConflict(ConstraintFactory constraintFactory) { + return constraintFactory.forEachUniquePair(MeetingAssignment.class, + equal(MeetingAssignment::getRoom), + overlapping(MeetingAssignment::getGrainIndex, + assignment -> assignment.getGrainIndex() + + assignment.getMeeting().getDurationInGrains()))
Don't we have a method for this? If not, let's add it. It's used very often. Please check the rest of the constraint provider too.
timefold-quickstarts
github_2023
java
380
TimefoldAI
triceo
@@ -99,23 +105,30 @@ public int calculateOverlap(MeetingAssignment other) { // start is inclusive, end is exclusive int start = startingTimeGrain.getGrainIndex(); int otherStart = other.startingTimeGrain.getGrainIndex(); - int otherEnd = otherStart + other.meeting.getDurationInGrains(); - if (otherEnd < start) { + if (other.getEndingTimeGrainDuration() < start) { return 0; } - int end = start + meeting.getDurationInGrains(); - if (end < otherStart) { + if (getEndingTimeGrainDuration() < otherStart) { return 0; } - return Math.min(end, otherEnd) - Math.max(start, otherStart); + return Math.min(getEndingTimeGrainDuration(), other.getEndingTimeGrainDuration()) - Math.max(start, otherStart); } @JsonIgnore - public Integer getLastTimeGrainIndex() { - if (startingTimeGrain == null) { + public Integer getEndingTimeGrainIndex() { + int duration = getEndingTimeGrainDuration(); + if (duration == 0) { return null; } - return startingTimeGrain.getGrainIndex() + meeting.getDurationInGrains() - 1; + return duration - 1; + } + + @JsonIgnore + public int getEndingTimeGrainDuration() { + if (startingTimeGrain == null) { + return 0; + } + return startingTimeGrain.getGrainIndex() + meeting.getDurationInGrains(); }
Now this is confusing. `lastTimeGrainIndex` makes perfect sense - it is the last index. But `endingTimeGrainDuration` is also a grain index; arguably it's not a duration at all, because it starts from zero, not from the starting time grain. The difference between the two is effectively `-1`. And that, arguably, isn't worth the confusion, or worth us sitting down and figuring out a better name for the method. Therefore my proposal: - Keep `lastTimeGrainIndex` as that's consistent with `firstTimeGrainIndex`. - Make `endingTimeGrainDuration` be `lastTimeGrainIndex + 1`. - Inline all uses of `endingTimeGrainDuration`, removing the method entirely. Can be done with IntelliJ refactoring tools.
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,90 @@ +package org.acme.sportsleagueschedule.domain; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.lookup.PlanningId; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@PlanningEntity +public class Match { + + @PlanningId + private String id; + private Team homeTeam; + private Team awayTeam; + private boolean classicMatch;
I would add a comment explaining what this means. Assume not everyone knows as much about football as you. For example, me. :-)
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,61 @@ +package org.acme.sportsleagueschedule.domain; + +import ai.timefold.solver.core.api.domain.lookup.PlanningId; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@JsonIdentityInfo(scope = Round.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "index") +public class Round { + + @PlanningId + private int index; + private boolean importantRound;
This is even more important to explain. In fact, maybe it's better to simply rename it to describe its function. `isOnWeekendOrHoliday`.
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,61 @@ +package org.acme.sportsleagueschedule.domain; + +import ai.timefold.solver.core.api.domain.lookup.PlanningId; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +@JsonIdentityInfo(scope = Round.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "index") +public class Round { + + @PlanningId + private int index; + private boolean importantRound; + + public Round() { + } + + public Round(int index) { + this.index = index; + } + + public Round(int index, boolean importantRound) { + this(index); + this.importantRound = importantRound; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public boolean isImportantRound() { + return importantRound; + } + + public void setImportantRound(boolean importantRound) { + this.importantRound = importantRound; + } + + @Override + public String toString() { + return "Day-" + index;
Round?
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,127 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day"); + } + + protected Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 2, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 3, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive home matches"); + } + + protected Constraint fourConsecutiveAwayMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifExists(Match.class, equal(Match::getAwayTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getAwayTeam), + equal(match -> match.getRoundIndex() + 2, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getAwayTeam), + equal(match -> match.getRoundIndex() + 3, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive away matches"); + } + + protected Constraint repeatMatchOnTheNextDay(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifExists(Match.class, equal(Match::getHomeTeam, Match::getAwayTeam), + equal(Match::getAwayTeam, Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("Repeat match on the next day"); + } + + protected Constraint startToAwayHop(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifNotExists(Round.class, + equal(match -> match.getRoundIndex() - 1, Round::getIndex)) + .penalize(HardSoftScore.ONE_SOFT, + match -> match.getAwayTeam().getDistance(match.getHomeTeam())) + .asConstraint("Start to away hop"); + } + + protected Constraint homeToAwayHop(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Match.class, equal(Match::getHomeTeam, Match::getAwayTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_SOFT, + (match, otherMatch) -> match.getHomeTeam().getDistance(otherMatch.getHomeTeam())) + .asConstraint("Home to away hop"); + } + + protected Constraint awayToAwayHop(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Match.class, equal(Match::getAwayTeam, Match::getAwayTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_SOFT, + (match, otherMatch) -> match.getHomeTeam().getDistance(otherMatch.getHomeTeam())) + .asConstraint("Away to away hop"); + } + + protected Constraint awayToHomeHop(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Match.class, equal(Match::getAwayTeam, Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .penalize(HardSoftScore.ONE_SOFT, + (match, otherMatch) -> match.getHomeTeam().getDistance(match.getAwayTeam())) + .asConstraint("Away to home hop"); + } + + protected Constraint awayToEndHop(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifNotExists(Round.class, equal(match -> match.getRoundIndex() + 1, Round::getIndex)) + .penalize(HardSoftScore.ONE_SOFT, + match -> match.getHomeTeam().getDistance(match.getAwayTeam())) + .asConstraint("Away to end hop"); + } + + protected Constraint classicMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .filter(match -> match.isClassicMatch() && !match.getRound().isImportantRound()) + .penalize(HardSoftScore.ofSoft(1000)) + .asConstraint("Classic matches played on important rounds");
Based on my comments above, this will need to be renamed too.
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,127 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day"); + } + + protected Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 1, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 2, Match::getRoundIndex)) + .ifExists(Match.class, equal(Match::getHomeTeam), + equal(match -> match.getRoundIndex() + 3, Match::getRoundIndex))
Consider using the consecutive collector for this. (See either docs or nurse rostering.) Otherwise we really don't have an example to showcase it anymore.
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,130 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import java.util.function.Function; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.common.SequenceChain; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; +import org.acme.sportsleagueschedule.domain.Team; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day"); + } + + protected Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Team.class, equal(Match::getHomeTeam, Function.identity())) + .groupBy((match, team) -> team, + ConstraintCollectors.toConsecutiveSequences((match, team) -> match.getRound(), Round::getIndex)) + .flattenLast(SequenceChain::getConsecutiveSequences) + .filter((team, matches) -> matches.getItems().size() >= 4) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive home matches"); + } + + protected Constraint fourConsecutiveAwayMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Team.class, equal(Match::getAwayTeam, Function.identity())) + .groupBy((match, team) -> team, + ConstraintCollectors.toConsecutiveSequences((match, team) -> match.getRound(), Round::getIndex)) + .flattenLast(SequenceChain::getConsecutiveSequences) + .filter((team, matches) -> matches.getItems().size() >= 4) + .penalize(HardSoftScore.ONE_HARD)
This is now a score trap. If the result is 5 or 50, it doesn't matter, the penalty will be 1. Make the solver's job easier, and penalize by the difference between the minimum and the actual value.
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,131 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import java.util.function.Function; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.common.SequenceChain; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; +import org.acme.sportsleagueschedule.domain.Team; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getHomeTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day");
```suggestion .asConstraint("Matches on the same day"); ```
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,131 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import java.util.function.Function; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.common.SequenceChain; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; +import org.acme.sportsleagueschedule.domain.Team; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getHomeTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day"); + } + + protected Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Team.class, equal(Match::getHomeTeam, Function.identity())) + .groupBy((match, team) -> team, + ConstraintCollectors.toConsecutiveSequences((match, team) -> match.getRound(), Round::getIndex)) + .flattenLast(SequenceChain::getConsecutiveSequences) + .filter((team, matches) -> matches.getItems().size() >= 4) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive home matches");
```suggestion .asConstraint("4 or more consecutive home matches"); ```
timefold-quickstarts
github_2023
java
388
TimefoldAI
triceo
@@ -0,0 +1,131 @@ +package org.acme.sportsleagueschedule.solver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; +import static ai.timefold.solver.core.api.score.stream.Joiners.filtering; + +import java.util.function.Function; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.common.SequenceChain; + +import org.acme.sportsleagueschedule.domain.Match; +import org.acme.sportsleagueschedule.domain.Round; +import org.acme.sportsleagueschedule.domain.Team; + +public class SportsLeagueSchedulingConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + matchesOnSameDay(constraintFactory), + fourConsecutiveHomeMatches(constraintFactory), + fourConsecutiveAwayMatches(constraintFactory), + repeatMatchOnTheNextDay(constraintFactory), + startToAwayHop(constraintFactory), + homeToAwayHop(constraintFactory), + awayToAwayHop(constraintFactory), + awayToHomeHop(constraintFactory), + awayToEndHop(constraintFactory), + classicMatches(constraintFactory) + }; + } + + protected Constraint matchesOnSameDay(ConstraintFactory constraintFactory) { + return constraintFactory + .forEachUniquePair(Match.class, + equal(Match::getRoundIndex), + filtering((match1, match2) -> match1.getHomeTeam().equals(match2.getHomeTeam()) + || match1.getHomeTeam().equals(match2.getAwayTeam()) + || match1.getAwayTeam().equals(match2.getHomeTeam()) + || match1.getAwayTeam().equals(match2.getAwayTeam()))) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("matches on the same day"); + } + + protected Constraint fourConsecutiveHomeMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Team.class, equal(Match::getHomeTeam, Function.identity())) + .groupBy((match, team) -> team, + ConstraintCollectors.toConsecutiveSequences((match, team) -> match.getRound(), Round::getIndex)) + .flattenLast(SequenceChain::getConsecutiveSequences) + .filter((team, matches) -> matches.getItems().size() >= 4) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive home matches"); + } + + protected Constraint fourConsecutiveAwayMatches(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Match.class) + .join(Team.class, equal(Match::getAwayTeam, Function.identity())) + .groupBy((match, team) -> team, + ConstraintCollectors.toConsecutiveSequences((match, team) -> match.getRound(), Round::getIndex)) + .flattenLast(SequenceChain::getConsecutiveSequences) + .filter((team, matches) -> matches.getItems().size() >= 4) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("4 consecutive away matches");
```suggestion .asConstraint("4 or more consecutive away matches"); ```
timefold-quickstarts
github_2023
java
366
TimefoldAI
triceo
@@ -130,22 +129,21 @@ public Constraint preferredMaximumRoomCapacity(ConstraintFactory constraintFacto public Constraint departmentSpecialty(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Stay.class) - .ifNotExists(DepartmentSpecialty.class, - equal(Stay::getDepartment, DepartmentSpecialty::getDepartment), - equal(Stay::getSpecialty, DepartmentSpecialty::getSpecialty)) + .filter(st -> !st.hasDepartmentSpecialty()) .penalize(HardMediumSoftScore.ofSoft(10), Stay::getNightCount) .asConstraint("departmentSpecialty"); } public Constraint departmentSpecialtyNotFirstPriority(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Stay.class) - .filter(st -> st.getSpecialty() != null) - .join(constraintFactory.forEach(DepartmentSpecialty.class) - .filter(ds -> ds.getPriority() > 1), - equal(Stay::getDepartment, DepartmentSpecialty::getDepartment), - equal(Stay::getSpecialty, DepartmentSpecialty::getSpecialty)) - .penalize(HardMediumSoftScore.ofSoft(10), - (bd, rs) -> (rs.getPriority() - 1) * bd.getNightCount()) + .filter(st -> st.getSpecialtyPriority() > 1) + .penalize(HardMediumSoftScore.ofSoft(10), stay -> (stay.getSpecialtyPriority() - 1) * stay.getNightCount()) +// .join(constraintFactory.forEach(DepartmentSpecialty.class) +// .filter(ds -> ds.getPriority() > 1), +// equal(Stay::getDepartment, DepartmentSpecialty::getDepartment), +// equal(Stay::getSpecialty, DepartmentSpecialty::getSpecialty)) +// .penalize(HardMediumSoftScore.ofSoft(10), +// (bd, rs) -> (rs.getPriority() - 1) * bd.getNightCount())
Let's not keep commented-out code around. That's what Git history is for.
timefold-quickstarts
github_2023
java
366
TimefoldAI
triceo
@@ -50,28 +45,21 @@ public void setDepartments(List<Department> departments) { this.departments = departments; } - public void setDepartmentSpecialties(List<DepartmentSpecialty> departmentSpecialties) { - this.departmentSpecialties = departmentSpecialties; - } - - public List<DepartmentSpecialty> getDepartmentSpecialties() { - return departmentSpecialties; - } - - public List<Room> getRooms() { - return rooms; - } - - public void setRooms(List<Room> rooms) { - this.rooms = rooms; - } - - public List<Bed> getBeds() { - return beds; + @JsonIgnore + @ProblemFactCollectionProperty + public List<Room> extractRooms() { + return departments.stream().filter(d -> d.getRooms() != null).flatMap(d -> d.getRooms().stream()).toList();
The next getter formats the stream better. Let's do the same thing, stay consistent.
timefold-quickstarts
github_2023
java
205
TimefoldAI
rsynek
@@ -45,7 +45,7 @@ private void pinCallAssignedToAgents(List<Call> calls) { public void startSolving(CallCenter inputProblem, Consumer<CallCenter> bestSolutionConsumer, Consumer<Throwable> errorHandler) { solverManager.solveAndListen(SINGLETON_ID, id -> inputProblem, bestSolution -> { - if (bestSolution.getScore().isSolutionInitialized()) { + if (bestSolution.getScore().isSolutionInitialized() && bestSolution.isFeasible()) {
`Score.isFeasible()` already covers (un)initialized solutions. ```suggestion if (bestSolution.isFeasible()) { ```
timefold-quickstarts
github_2023
java
205
TimefoldAI
rsynek
@@ -41,7 +42,8 @@ private static Set<Skill> buildSkillSet(Skill... skills) { } public CallCenter generateCallCenter() { - return new CallCenter(EnumSet.allOf(Skill.class), Arrays.asList(AGENTS), new ArrayList<>()); + return new CallCenter(EnumSet.allOf(Skill.class), Arrays.stream(AGENTS).map(Agent::copy).collect(Collectors.toList()),
If the intention is to avoid reusing the same `Agent` instances, I suggest creating them in this method directly and removing the static array is more straightforward than copying the array.
timefold-quickstarts
github_2023
java
205
TimefoldAI
rsynek
@@ -96,6 +105,63 @@ void removeCall() { assertThat(call.getId()).isEqualTo(call2.getId()); } + @Test + @Timeout(60) + void removeCallWithInfeasibleInitialSolution() { + // Invalid initial solution + CallCenter inputProblem = dataGenerator.generateCallCenter(); + Call call1 = new Call(1L, "123-456-7891", Skill.ENGLISH, Skill.CAR_INSURANCE); + Call call2 = new Call(2L, "123-456-7892", Skill.ENGLISH, Skill.CAR_INSURANCE); + inputProblem.getCalls().add(call1); + inputProblem.getCalls().add(call2); + inputProblem.getAgents().get(0).setNextCall(call2); + inputProblem.getAgents().get(1).setNextCall(call1); + call1.setAgent(inputProblem.getAgents().get(1)); + call1.setPreviousCallOrAgent(inputProblem.getAgents().get(1)); + call1.setEstimatedWaiting(Duration.ofSeconds(1)); + call2.setAgent(inputProblem.getAgents().get(0)); + call2.setPreviousCallOrAgent(inputProblem.getAgents().get(0)); + call2.setEstimatedWaiting(Duration.ofSeconds(1)); + inputProblem.setScore(HardSoftScore.ofUninitialized(0, -1, 0)); + + // We have an initial solution, then we run only LocalSearchPhaseConfig + SolverConfig solverConfig = new SolverConfig() + .withSolutionClass(CallCenter.class) + .withEntityClasses(Call.class, PreviousCallOrAgent.class) + .withConstraintProviderClass(CallCenterConstraintsProvider.class) + .withPhases(new LocalSearchPhaseConfig()) + .withTerminationConfig(new TerminationConfig().withSpentLimit(Duration.ofSeconds(30L))); + + // Create a custom manager + try (SolverManager<CallCenter, Long> solverManager2 = SolverManager.create(solverConfig, new SolverManagerConfig())) {
Numbering variables harms readability. While I am technically guilty of doing that as well, I see some sense in breaking the rule for test data (`call1`, `call2`), provided it does not have any specific purpose in the test. May I suggest renaming the variable to `localSearchSolverManager` ?
timefold-quickstarts
github_2023
java
197
TimefoldAI
rsynek
@@ -0,0 +1,92 @@ +package org.acme.callcenter.solver.retry; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; +import org.junit.jupiter.api.extension.TestTemplateInvocationContext; +import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; +import org.junit.platform.commons.support.AnnotationSupport; +import org.opentest4j.TestAbortedException; + +import java.lang.reflect.Method; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import static java.util.Spliterator.ORDERED; +import static java.util.Spliterators.spliteratorUnknownSize; + +public class RetryTestExtension implements TestTemplateInvocationContextProvider, TestExecutionExceptionHandler { + + private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(RetryTestExtension.class); + + public RetryTestExtension() { + } + + @Override + public boolean supportsTestTemplate(ExtensionContext extensionContext) { + return true; + } + + @Override + public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext extensionContext) { + TestExecutionContext executionContext = getExecutionContext(extensionContext.getRequiredTestMethod(), + extensionContext); + if (executionContext.failures == 0) { + throw new TestAbortedException("Retry execution ignored."); + } + // The stream executes one successful run or maxAttempts unsuccessful runs at most + return StreamSupport.stream(spliteratorUnknownSize(executionContext, ORDERED), false); + } + + @Override + public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable { + TestExecutionContext executionContext = getExecutionContext(extensionContext.getRequiredTestMethod(), + extensionContext.getParent().orElseThrow(() -> new IllegalStateException("The parent context is required."))); + executionContext.incFailures(); + throw throwable; + } + + private static TestExecutionContext getExecutionContext(Method method, ExtensionContext extensionContext) { + return extensionContext.getStore(NAMESPACE).getOrComputeIfAbsent(method.getName(), __ -> { + Retry retry = AnnotationSupport.findAnnotation(method, Retry.class) + .orElseThrow(() -> new IllegalStateException("@Retry is missing.")); + return new TestExecutionContext(Math.max(retry.value(), retry.maxAttempts())); + }, TestExecutionContext.class); + } + + private static class TestExecutionContext implements Iterator<TestTemplateInvocationContext> { + private final int maxAttempts; + private int executions = 0; + private int failures = 0; + + public TestExecutionContext(int maxAttempts) { + this.maxAttempts = maxAttempts; + } + + public void incExecutions() { + executions++; + } + + public void incFailures() { + failures++; + } + + @Override + public boolean hasNext() { + boolean hadSuccessful = executions > failures; + // Stop when there in one successful or the max attempts is exhausted
```suggestion // Stop when there is one successful or the max attempts is exhausted ```
timefold-quickstarts
github_2023
java
197
TimefoldAI
rsynek
@@ -77,6 +76,7 @@ void prolongCall() { @Test @Timeout(60) + @Retry(3)
While this approach lowers the risk of the test failing again, it does not fix the root cause. This is a not a problem with a random failure due to e.g. network latency, which would justify the retries. Suggestion: try reproducing the issue by running the test in a loop (perhaps with some very short random pauses) and see if it shows up.
timefold-quickstarts
github_2023
java
316
TimefoldAI
triceo
@@ -69,4 +62,16 @@ public void setAvailabilityType(AvailabilityType availabilityType) { public String toString() { return availabilityType + "(" + employee + ", " + date + ")"; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Availability that)) return false; + return Objects.equals(getId(), that.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId());
Let's not use [Objects.hash(...)](https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#hash-java.lang.Object...-). This method creates a varargs array on the heap every time it is invoked. When this `hashCode` method gets on a hot path (such as in constraints), this is a considerable slowdown. Let's not teach people this.
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -100,6 +96,50 @@ public String solve(VehicleRoutePlan problem) { return jobId; } + @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The list of fits for the given customer.", + 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())) + .findFirst().orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId()))); + List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFitList = solutionManager + .recommendFit(request.solution(), customer, c -> new VehicleRecommendation(c.getVehicle().getId(), + c.getVehicle().getCustomers().indexOf(c))); + if (!recommendedFitList.isEmpty()) { + return recommendedFitList.subList(0, Math.min(MAX_RECOMMENDED_FIT_LIST_SIZE, recommendedFitList.size())); + } + return recommendedFitList; + } + + @Operation(summary = "Applies a give recommentation.")
```suggestion @Operation(summary = "Applies a given recommentation.") ```
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -100,6 +96,50 @@ public String solve(VehicleRoutePlan problem) { return jobId; } + @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The list of fits for the given customer.", + content = @Content(mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = List.class)))}) + @POST + @Consumes({MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) + @Path("recommendation")
I'd use `GET` here, since you're asking for data.
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -100,6 +96,50 @@ public String solve(VehicleRoutePlan problem) { return jobId; } + @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The list of fits for the given customer.", + 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())) + .findFirst().orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId()))); + List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFitList = solutionManager + .recommendFit(request.solution(), customer, c -> new VehicleRecommendation(c.getVehicle().getId(), + c.getVehicle().getCustomers().indexOf(c))); + if (!recommendedFitList.isEmpty()) { + return recommendedFitList.subList(0, Math.min(MAX_RECOMMENDED_FIT_LIST_SIZE, recommendedFitList.size())); + } + return recommendedFitList; + } + + @Operation(summary = "Applies a give recommentation.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The new solution updated with the recommentation.", + content = @Content(mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = VehicleRoutePlan.class)))}) + @POST + @Consumes({MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) + @Path("recommendation/apply")
```suggestion @Path("recommendation") ``` And then you can use `recommendation` here, because `@POST` is no longer used to get the recommendations.
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -100,6 +96,50 @@ public String solve(VehicleRoutePlan problem) { return jobId; } + @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The list of fits for the given customer.", + 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())) + .findFirst().orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId())));
```suggestion Customer customer = request.solution().getCustomers().stream() .filter(c -> c.getId().equals(request.customerId())) .findFirst() .orElseThrow(() -> new IllegalStateException("Customer %s not found" .formatted(request.customerId()))); ``` Let's separate these long fluent calls into more lines. Easier to read what's happening.
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -100,6 +96,50 @@ public String solve(VehicleRoutePlan problem) { return jobId; } + @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The list of fits for the given customer.", + 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())) + .findFirst().orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId()))); + List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFitList = solutionManager + .recommendFit(request.solution(), customer, c -> new VehicleRecommendation(c.getVehicle().getId(), + c.getVehicle().getCustomers().indexOf(c))); + if (!recommendedFitList.isEmpty()) { + return recommendedFitList.subList(0, Math.min(MAX_RECOMMENDED_FIT_LIST_SIZE, recommendedFitList.size())); + } + return recommendedFitList; + } + + @Operation(summary = "Applies a give recommentation.") + @APIResponses(value = { + @APIResponse(responseCode = "200", + description = "The new solution updated with the recommentation.", + content = @Content(mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = VehicleRoutePlan.class)))}) + @POST + @Consumes({MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) + @Path("recommendation/apply") + public VehicleRoutePlan applyRecommendedFit(ApplyRecommendationRequest request) { + VehicleRoutePlan updatedSolution = request.solution(); + String vehicleId = request.vehicleId(); + Vehicle vehicleTarget = updatedSolution.getVehicles().stream().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())) + .findFirst().orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId())));
Same comment on formatting of fluent chains.
timefold-quickstarts
github_2023
java
259
TimefoldAI
triceo
@@ -1,31 +1,26 @@ package org.acme.vehiclerouting.rest; import java.util.Collection; +import java.util.List; 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.*;
Star imports are not allowed. Please configure your IDE not to allow them.
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID
If you take a look on the right, you will see that Github allows linking a Github issue. I think this should be enough and we don't need to include it in the PR description as well. WDYT?
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons).
```suggestion - [ ] UI and JS files are fully tested, the user interface works for all modules affected by your changes (e.g., solve and analyze buttons). ```
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons). +- [ ] The network calls work for all modules or those affected by your changes (e.g., solving a problem).
```suggestion - [ ] The network calls work for all modules affected by your changes (e.g., solving a problem). ```
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons). +- [ ] The network calls work for all modules or those affected by your changes (e.g., solving a problem). +- [ ] The console messages are validated for all modules or those affected by your changes.
```suggestion - [ ] The console messages are validated for all modules affected by your changes. ```
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons). +- [ ] The network calls work for all modules or those affected by your changes (e.g., solving a problem). +- [ ] The console messages are validated for all modules or those affected by your changes. + +### Code Review + +- [ ] This pull request includes an explicative title and description.
```suggestion - [ ] This pull request includes an explanatory title and description. ```
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons). +- [ ] The network calls work for all modules or those affected by your changes (e.g., solving a problem). +- [ ] The console messages are validated for all modules or those affected by your changes. + +### Code Review + +- [ ] This pull request includes an explicative title and description. +- [ ] The GitHub issue is linked. + +### Merging +
I'd remove the header. Merging will happen if code review is OK.
timefold-quickstarts
github_2023
others
222
TimefoldAI
triceo
@@ -0,0 +1,27 @@ +## Description of the change + +> Description here + +## Related Issue + +Issue #ID + +## Checklist + +### Development + +- [ ] The changes have been covered with tests, if necessary. +- [ ] You have a green build, with the exception of the flaky tests. +- [ ] UI and JS files are fully tested, and the UI buttons work for all modules or those affected by your changes (e.g., solve and analyze buttons). +- [ ] The network calls work for all modules or those affected by your changes (e.g., solving a problem). +- [ ] The console messages are validated for all modules or those affected by your changes. + +### Code Review + +- [ ] This pull request includes an explicative title and description. +- [ ] The GitHub issue is linked. + +### Merging + +- [ ] At least one other engineer has approved the changes. +- [ ] After merging the change, the issue requires you to follow up with the user.
What do you mean by this last point?