repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
timefold-solver | github_2023 | java | 171 | TimefoldAI | rsynek | @@ -38,23 +41,60 @@ public static HardMediumSoftScore parseScore(String scoreString) {
}
public static HardMediumSoftScore ofUninitialized(int initScore, int hardScore, int mediumScore, int softScore) {
+ if (initScore == 0) {
+ return of(hardScore, mediumScore, softScore);
+ }
return new HardMediumSoftScore(initScore, hardScore, mediumScore, softScore);
}
public static HardMediumSoftScore of(int hardScore, int mediumScore, int softScore) { | How often is this method called to express a single-level score that is either -1, 0, or 1? This `if-else-if` structure surely does not come for free.
Proposal: do this optimization only for single-level score factory methods, where the chance we hit the constant is much higher.
(applies to all Score types) |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump | ```suggestion
git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version
``` |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump
+ gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md
+ env:
+ GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- name: Switch back to source branch and set snapshot version
run: |
git checkout ${{ github.event.inputs.sourceBranch }}
- git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump2 | ```suggestion
git checkout -B ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version
``` |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump | ```suggestion
git push origin ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version
``` |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump
+ gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md | ```suggestion
gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump-to-next-micro-version --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md
``` |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump
+ gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md
+ env:
+ GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- name: Switch back to source branch and set snapshot version
run: |
git checkout ${{ github.event.inputs.sourceBranch }}
- git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump2
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
- mvn -Dfull verify -DskipTests=true
cp docs/target/antora-template.yml docs/src/antora.yml
git add docs/src/antora.yml
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
-
- # JReleaser will push the tag, but it will only show up after the release is undrafted.
- - name: Push branches to git
- run: |
- git push origin ${{ github.event.inputs.releaseBranch }}
- git push origin ${{ github.event.inputs.releaseBranch }}-bump
-
- # There are some follow-up steps to continue the release.
- # They will be listed in the PR body.
- - name: Create pull request to bump the version
- run: |
- gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.sourceBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body.md
+ git commit -am "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump2 | ```suggestion
git push origin ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version
``` |
timefold-solver | github_2023 | others | 158 | TimefoldAI | rsynek | @@ -88,31 +88,23 @@ jobs:
- name: Set micro snapshot version on the release branch
run: |
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git commit -am "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump
+ gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.releaseBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body-stable.md
+ env:
+ GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- name: Switch back to source branch and set snapshot version
run: |
git checkout ${{ github.event.inputs.sourceBranch }}
- git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump2
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
- mvn -Dfull verify -DskipTests=true
cp docs/target/antora-template.yml docs/src/antora.yml
git add docs/src/antora.yml
- find . -name 'pom.xml' | xargs git add
- git commit -m "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
-
- # JReleaser will push the tag, but it will only show up after the release is undrafted.
- - name: Push branches to git
- run: |
- git push origin ${{ github.event.inputs.releaseBranch }}
- git push origin ${{ github.event.inputs.releaseBranch }}-bump
-
- # There are some follow-up steps to continue the release.
- # They will be listed in the PR body.
- - name: Create pull request to bump the version
- run: |
- gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.sourceBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body.md
+ git commit -am "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump2
+ gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.sourceBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump2 --title "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body.md | ```suggestion
gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.sourceBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump-to-next-minor-version --title "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT" --body-file .github/workflows/release-pr-body.md
``` |
timefold-solver | github_2023 | others | 156 | TimefoldAI | rsynek | @@ -112,63 +113,77 @@ As you can see in the examples, most instances have a lot more possible solution
Timefold supports several optimization algorithms to efficiently wade through that incredibly large number of possible solutions.
Depending on the use case, some optimization algorithms perform better than others, but it's impossible to tell in advance. **With Timefold, it is easy to switch the optimization algorithm**, by changing the solver configuration in a few lines of XML or code.
-[[requirements]]
-== Requirements
+[[timefoldSolverStatus]]
+== Status of Timefold Solver
+
+Timefold Solver is 100% pure Java^TM^ and runs on Java {java-version} or higher.
+It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^ technologies.
+Timefold Solver works on any Java Virtual Machine and is compatible with the major JVM languages and all major platforms.
+
+image::introduction/compatibility.png[align="center"]
+
+Timefold Solver is stable, reliable and scalable.
+It has been heavily tested with unit, integration, and stress tests, and is used in production throughout the world.
+One example handles over 50 000 variables with 5000 values each, multiple constraint types and billions of possible constraint matches.
+
+We offer two editions of Timefold Solver.
+
+[[communityEdition]]
+=== Timefold Solver Community Edition
Timefold Solver Community Edition is _open source_ software,
released under http://www.apache.org/licenses/LICENSE-2.0.html[the Apache License 2.0].
This license is very liberal and allows reuse for commercial purposes.
Read http://www.apache.org/foundation/licence-FAQ.html#WhatDoesItMEAN[the layman's explanation].
-Timefold is 100% pure Java^TM^ and runs on Java {java-version} or higher.
-It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^ technologies.
-Timefold is available in <<useWithMavenGradleEtc,the Maven Central Repository>>.
-
-Timefold works on any Java Virtual Machine and is compatible with the major JVM languages and all major platforms.
+Timefold Solver Community Edition is available in <<useWithMavenGradleEtc,the Maven Central Repository>>.
+It is and will always be free.
+The overwhelming majority of solver features will always be available in the Community Edition. | Should we clearly say that every feature apart from scalability features is included? |
timefold-solver | github_2023 | others | 146 | TimefoldAI | triceo | @@ -16,7 +16,7 @@ with https://timefold.ai[Timefold]'s constraint solving Artificial Intelligence
You will build a REST application that optimizes a school timetable for students and teachers:
-image::quickstart/school-timetabling/schoolTimetablingScreenshot.png[]
+image::quickstart/school-timetabling/schoolTimetablingScreenshot_legacy.png[] | Why do we keep and reference an *old* version of the app? |
timefold-solver | github_2023 | others | 138 | TimefoldAI | rsynek | @@ -46,32 +46,30 @@ jobs:
distribution: 'temurin'
cache: 'maven'
+ # Need Maven 3.9.0+ to recognize MAVEN_ARGS.
+ - name: Set up Maven
+ uses: stCarolas/setup-maven@v4.5
+ with:
+ maven-version: 3.9.3
+
# We skip tests in dry run, to make the process faster.
# Technically, this goes against the main reason for doing a dry run; to eliminate potential problems.
# But unless something catastrophic happened, PR checks on source branch already ensured that all tests pass.
- name: Set release version and build release
run: |
mvn -Dfull versions:set -DnewVersion=${{ github.event.inputs.version }}
mvn -Dfull deploy -DskipTests=${{ github.event.inputs.dryRun }} -DaltDeploymentRepository=local::default::file://`pwd`/target/staging-deploy
-
- - name: Update release branch and commit the changes
- run: |
cp docs/target/antora-template.yml docs/src/antora.yml
git add docs/src/antora.yml
find . -name 'pom.xml' | xargs git add
git commit -m "chore: release version ${{ github.event.inputs.version }}"
-
- # JReleaser requires the release branch to exist, so we need to push it before releasing.
- # Once this is pushed, branch protection rules apply.
- # So if any of the subsequent steps should fail, the release branch is there to stay; cannot be deleted.
- # To minimize that chance, do a dry run first, with a branch named in a way that the protection rules don't apply.
- - name: Push release branch to Git
- run: |
git push origin ${{ github.event.inputs.releaseBranch }}
- name: Run JReleaser
- run: mvn -Dfull -Djreleaser.dry.run=${{ github.event.inputs.dryRun }} -pl . jreleaser:full-release
+ uses: jreleaser/release-action@v2 | There is a dedicated GHA? Interesting. |
timefold-solver | github_2023 | others | 138 | TimefoldAI | rsynek | @@ -242,7 +242,7 @@ public class CloudBalance ... {
[[cloudBalancingMainMethod]]
== Run the cloud balancing Hello World
-. xref:introduction/introduction.adoc#runTheExamplesInAnIDE[Download and configure the examples in your preferred IDE.]
+. xref:introduction/introduction.adoc#buildFromSource[Download and configure the examples in your preferred IDE.] | Nice catch. |
timefold-solver | github_2023 | others | 115 | TimefoldAI | rsynek | @@ -1,16 +1,27 @@
-# TODO release XSD to timefold.ai/xsd/
-# TODO reset timefold-quickstarts stable branch
-# TODO adjust website pom.yml release date and version
-# TODO tag github issues with version
name: Release
on:
workflow_dispatch:
inputs:
version:
- description: 'Release version'
+ description: 'Release version (e.g. 1.0.0)'
required: true
nextVersion:
- description: 'Next version after release (-SNAPSHOT will be added automatically)'
+ description: 'Next version after release (e.g. 1.1.0, -SNAPSHOT will be added automatically)'
+ required: true
+ nextMicroVersion:
+ description: 'Next version after release for release branch (e.g. 1.0.1, -SNAPSHOT will be added automatically)'
+ required: true
+ sourceBranch:
+ description: 'Branch to cut the release from'
+ default: main
+ required: true
+ releaseBranch:
+ description: 'Release branch to create (e.g. 1.0.x for version 1.0.0; once created, branch protection rules apply)'
+ default: dry_run
+ required: true | Let's move these two before the "Next version..." parameters to define these branches before referring to them. |
timefold-solver | github_2023 | others | 115 | TimefoldAI | rsynek | @@ -19,79 +30,94 @@ jobs:
- name: Checkout timefold-solver
uses: actions/checkout@v3
with:
- path: 'timefold-solver'
- repository: 'TimefoldAI/timefold-solver'
fetch-depth: 0
- - name: Checkout timefold-quickstarts
- uses: actions/checkout@v3
- with:
- path: 'timefold-quickstarts'
- repository: 'TimefoldAI/timefold-quickstarts'
- ref: development
- fetch-depth: 0
+ - name: Create release branch and switch to it
+ run: |
+ git config user.name "Timefold Release Bot"
+ git config user.email "release@timefold.ai"
+ git checkout -b ${{ github.event.inputs.releaseBranch }}
- uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
- - name: Set release version timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.version }}
-
- - name: Commit and push release version timefold-solver
- uses: actions-js/push@v1.4
- with:
- directory: ./timefold-solver
- github_token: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- message: Set release version ${{ github.event.inputs.version }}
-
- - name: Build release timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull clean deploy -DaltDeploymentRepository=local::default::file://`pwd`/target/staging-deploy
+ # We skip tests in dry run, to make the process faster.
+ # Technically, this goes against the main reason for doing a dry run; to eliminate potential problems.
+ # But unless something catastrophic happened, PR checks on source branch already ensured that all tests pass.
+ - name: Set release version and build release
+ run: |
+ mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.version }}
+ mvn --no-transfer-progress --batch-mode -Dfull deploy -DskipTests=${{ github.event.inputs.dryRun }} -DaltDeploymentRepository=local::default::file://`pwd`/target/staging-deploy
- - name: Update antora.yml timefold-solver
- working-directory: ./timefold-solver
+ - name: Update release branch and commit the changes
run: |
cp docs/target/antora-template.yml docs/src/antora.yml
+ git add docs/src/antora.yml
+ find . -name 'pom.xml' | xargs git add
+ git commit -m "chore: release version ${{ github.event.inputs.version }}"
- - name: Commit and push update antora.yml timefold-solver
- uses: actions-js/push@v1.4
- with:
- directory: ./timefold-solver
- github_token: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- message: Update antora.yml for release ${{ github.event.inputs.version }}
+ # JReleaser requires the release branch to exist, so we need to push it before releasing.
+ # Once this is pushed, branch protection rules apply.
+ # So if any of the subsequent steps should fail, the release branch is there to stay; cannot be deleted.
+ # To minimize that chance, do a dry run first, with a branch named in a way that the protection rules don't apply.
+ - name: Push release branch to Git
+ run: |
+ git push origin ${{ github.event.inputs.releaseBranch }}
- - name: Run JReleaser timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull -pl . jreleaser:full-release
+ - name: Run JReleaser
+ run: mvn --no-transfer-progress --batch-mode -Dfull -Djreleaser.dry.run=${{ github.event.inputs.dryRun }} -pl . jreleaser:full-release
env:
JRELEASER_GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
JRELEASER_GPG_PASSPHRASE: ${{ secrets.JRELEASER_GPG_PASSPHRASE }}
JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.JRELEASER_GPG_PUBLIC_KEY }}
JRELEASER_GPG_SECRET_KEY: ${{ secrets.JRELEASER_GPG_SECRET_KEY }}
- JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME: ${{ secrets.JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME }}
- JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD }}
+ JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME: ${{ secrets.JRELEASER_NEXUS2_USERNAME }}
+ JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_PASSWORD }}
- - name: JReleaser release output timefold-solver
- if: always()
+ - name: JReleaser release output
uses: actions/upload-artifact@v3
+ if: always()
with:
name: jreleaser-release
path: |
- timefold-solver/target/jreleaser/trace.log
- timefold-solver/target/jreleaser/output.properties
+ target/jreleaser/trace.log
+ target/jreleaser/output.properties
- - name: Set snapshot version timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
+ - name: Set micro snapshot version on the release branch
+ run: |
+ mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT | Something for consideration: define some MAVEN_OPTIONS (?) env var to keep the `-no-transfer-progress --batch-mode` in a single place. |
timefold-solver | github_2023 | others | 115 | TimefoldAI | rsynek | @@ -19,79 +30,94 @@ jobs:
- name: Checkout timefold-solver
uses: actions/checkout@v3
with:
- path: 'timefold-solver'
- repository: 'TimefoldAI/timefold-solver'
fetch-depth: 0
- - name: Checkout timefold-quickstarts
- uses: actions/checkout@v3
- with:
- path: 'timefold-quickstarts'
- repository: 'TimefoldAI/timefold-quickstarts'
- ref: development
- fetch-depth: 0
+ - name: Create release branch and switch to it
+ run: |
+ git config user.name "Timefold Release Bot"
+ git config user.email "release@timefold.ai"
+ git checkout -b ${{ github.event.inputs.releaseBranch }}
- uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
- - name: Set release version timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.version }}
-
- - name: Commit and push release version timefold-solver
- uses: actions-js/push@v1.4
- with:
- directory: ./timefold-solver
- github_token: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- message: Set release version ${{ github.event.inputs.version }}
-
- - name: Build release timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull clean deploy -DaltDeploymentRepository=local::default::file://`pwd`/target/staging-deploy
+ # We skip tests in dry run, to make the process faster.
+ # Technically, this goes against the main reason for doing a dry run; to eliminate potential problems.
+ # But unless something catastrophic happened, PR checks on source branch already ensured that all tests pass.
+ - name: Set release version and build release
+ run: |
+ mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.version }}
+ mvn --no-transfer-progress --batch-mode -Dfull deploy -DskipTests=${{ github.event.inputs.dryRun }} -DaltDeploymentRepository=local::default::file://`pwd`/target/staging-deploy
- - name: Update antora.yml timefold-solver
- working-directory: ./timefold-solver
+ - name: Update release branch and commit the changes
run: |
cp docs/target/antora-template.yml docs/src/antora.yml
+ git add docs/src/antora.yml
+ find . -name 'pom.xml' | xargs git add
+ git commit -m "chore: release version ${{ github.event.inputs.version }}"
- - name: Commit and push update antora.yml timefold-solver
- uses: actions-js/push@v1.4
- with:
- directory: ./timefold-solver
- github_token: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- message: Update antora.yml for release ${{ github.event.inputs.version }}
+ # JReleaser requires the release branch to exist, so we need to push it before releasing.
+ # Once this is pushed, branch protection rules apply.
+ # So if any of the subsequent steps should fail, the release branch is there to stay; cannot be deleted.
+ # To minimize that chance, do a dry run first, with a branch named in a way that the protection rules don't apply.
+ - name: Push release branch to Git
+ run: |
+ git push origin ${{ github.event.inputs.releaseBranch }}
- - name: Run JReleaser timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull -pl . jreleaser:full-release
+ - name: Run JReleaser
+ run: mvn --no-transfer-progress --batch-mode -Dfull -Djreleaser.dry.run=${{ github.event.inputs.dryRun }} -pl . jreleaser:full-release
env:
JRELEASER_GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
JRELEASER_GPG_PASSPHRASE: ${{ secrets.JRELEASER_GPG_PASSPHRASE }}
JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.JRELEASER_GPG_PUBLIC_KEY }}
JRELEASER_GPG_SECRET_KEY: ${{ secrets.JRELEASER_GPG_SECRET_KEY }}
- JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME: ${{ secrets.JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME }}
- JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD }}
+ JRELEASER_NEXUS2_MAVEN_CENTRAL_USERNAME: ${{ secrets.JRELEASER_NEXUS2_USERNAME }}
+ JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_PASSWORD }}
- - name: JReleaser release output timefold-solver
- if: always()
+ - name: JReleaser release output
uses: actions/upload-artifact@v3
+ if: always()
with:
name: jreleaser-release
path: |
- timefold-solver/target/jreleaser/trace.log
- timefold-solver/target/jreleaser/output.properties
+ target/jreleaser/trace.log
+ target/jreleaser/output.properties
- - name: Set snapshot version timefold-solver
- working-directory: ./timefold-solver
- run: mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
+ - name: Set micro snapshot version on the release branch
+ run: |
+ mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT
+ find . -name 'pom.xml' | xargs git add
+ git commit -m "chore: move to ${{ github.event.inputs.nextMicroVersion }}-SNAPSHOT"
- - name: Commit and push tag snapshot version timefold-solver
- uses: actions-js/push@v1.4
- with:
- directory: ./timefold-solver
- github_token: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- message: Set next SNAPSHOT version ${{ github.event.inputs.nextVersion }}-SNAPSHOT
- tags: true
+ - name: Switch back to source branch and set snapshot version
+ run: |
+ git checkout ${{ github.event.inputs.sourceBranch }}
+ git checkout -B ${{ github.event.inputs.releaseBranch }}-bump
+ mvn --no-transfer-progress --batch-mode -Dfull versions:set -DnewVersion=${{ github.event.inputs.nextVersion }}-SNAPSHOT
+ mvn --no-transfer-progress --batch-mode -Dfull verify -DskipTests=true
+
+ - name: Update source branch and commit
+ run: |
+ cp docs/target/antora-template.yml docs/src/antora.yml
+ git add docs/src/antora.yml
+ find . -name 'pom.xml' | xargs git add
+ git commit -m "chore: move to ${{ github.event.inputs.nextVersion }}-SNAPSHOT"
+
+ # JReleaser should push the tag on its own, but it does not due to a bug.
+ # https://github.com/jreleaser/jreleaser/issues/1425
+ - name: Push branches to git
+ run: |
+ git push origin ${{ github.event.inputs.releaseBranch }}
+ git push origin ${{ github.event.inputs.releaseBranch }}-bump | In the last stage of the release, this branch should be deleted. Apart from just having a stale branch in the git repository, if you want to do a micro release from already existing release branch, there will likely be a conflict with the existing release-bump branch. |
timefold-solver | github_2023 | others | 120 | TimefoldAI | triceo | @@ -18,8 +18,7 @@ A _realistic contest_ is _an official, independent contest_:
Realistic contests provide an objective comparison of Timefold with competitive software and academic research.
-The source code of all these examples is available in the distribution zip under [path]_examples/sources_
-and also in git under [path]_timefold/timefold-solver-examples_.
+The source code of all these examples is available in git under [path]_timefold/timefold-solver-examples_. | Maybe link to Github instead? |
timefold-solver | github_2023 | others | 108 | TimefoldAI | rsynek | @@ -25,63 +25,73 @@
</constructionHeuristic>
<localSearch>
<unionMoveSelector>
- <listChangeMoveSelector>
- <valueSelector id="1"/>
- <destinationSelector>
- <nearbySelection>
- <originValueSelector mimicSelectorRef="1"/>
- <nearbyDistanceMeterClass>ai.timefold.solver.examples.vehiclerouting.domain.solver.nearby.CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
- <nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelectionDistributionType>
- <parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
- </nearbySelection>
- </destinationSelector>
- </listChangeMoveSelector>
- <listSwapMoveSelector>
- <valueSelector id="2"/>
- <secondaryValueSelector>
- <nearbySelection>
- <originValueSelector mimicSelectorRef="2"/>
- <nearbyDistanceMeterClass>ai.timefold.solver.examples.vehiclerouting.domain.solver.nearby.CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
- <nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelectionDistributionType>
- <parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
- </nearbySelection>
- </secondaryValueSelector>
- </listSwapMoveSelector>
+ <listChangeMoveSelector />
+ <listSwapMoveSelector />
<subListChangeMoveSelector>
<selectReversingMoveToo>true</selectReversingMoveToo>
- <subListSelector id="3"/>
- <destinationSelector>
- <nearbySelection>
- <originSubListSelector mimicSelectorRef="3"/>
- <nearbyDistanceMeterClass>ai.timefold.solver.examples.vehiclerouting.domain.solver.nearby.CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
- <nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelectionDistributionType>
- <parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
- </nearbySelection>
- </destinationSelector>
</subListChangeMoveSelector>
<subListSwapMoveSelector>
<selectReversingMoveToo>true</selectReversingMoveToo>
- <subListSelector id="4"/>
- <secondarySubListSelector>
- <nearbySelection>
- <originSubListSelector mimicSelectorRef="4"/>
- <nearbyDistanceMeterClass>ai.timefold.solver.examples.vehiclerouting.domain.solver.nearby.CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
- <nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelectionDistributionType>
- <parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
- </nearbySelection>
- </secondarySubListSelector>
</subListSwapMoveSelector>
- <kOptListMoveSelector>
- <originSelector id="5"/>
- <valueSelector>
- <nearbySelection>
- <originValueSelector mimicSelectorRef="5"/>
- <nearbyDistanceMeterClass>ai.timefold.solver.examples.vehiclerouting.domain.solver.nearby.CustomerNearbyDistanceMeter</nearbyDistanceMeterClass>
- <nearbySelectionDistributionType>PARABOLIC_DISTRIBUTION</nearbySelectionDistributionType>
- <parabolicDistributionSizeMaximum>40</parabolicDistributionSizeMaximum>
- </nearbySelection>
- </valueSelector>
- </kOptListMoveSelector>
+ <kOptListMoveSelector />
+ <!-- With Timefold Solver Enterprise Edition, uncomment the following to enable Nearby Selection: --> | I see a lot of combinations got commented out as expected. However, this impacts:
a) performance tests in timefold-examples (if they run these configurations)
b) turtle tests (assuming there are some turtle tests) |
timefold-solver | github_2023 | java | 102 | TimefoldAI | rsynek | @@ -461,4 +468,27 @@ Constraint talkUndesiredRoomTags(ConstraintFactory factory) {
.asConstraint(TALK_UNDESIRED_ROOM_TAGS);
}
+ Constraint speakerMakespan(ConstraintFactory factory) {
+ return factory.forEach(Speaker.class)
+ .join(Talk.class,
+ filtering((speaker, talk) -> talk.hasSpeaker(speaker)))
+ .groupBy((speaker, talk) -> speaker,
+ compose(
+ min((Speaker speaker, Talk talk) -> talk, talk -> talk.getTimeslot().getStartDateTime()),
+ max((Speaker speaker, Talk talk) -> talk, talk -> talk.getTimeslot().getStartDateTime()),
+ (firstTalk, lastTalk) -> {
+ LocalDate firstDate = firstTalk.getTimeslot().getStartDateTime().toLocalDate();
+ LocalDate lastDate = lastTalk.getTimeslot().getStartDateTime().toLocalDate();
+ if (firstDate.equals(lastDate)) {
+ return 0;
+ } | The next line should cover this case too. Is the extra `if` worth it? |
timefold-solver | github_2023 | java | 99 | TimefoldAI | rsynek | @@ -718,19 +718,130 @@ private static <Result> Runnable innerSum(MutableReference<Result> resultContain
*/
public static <A, Mapped extends Comparable<? super Mapped>> UniConstraintCollector<A, ?, Mapped> min(
Function<A, Mapped> groupValueMapping) {
- return min(groupValueMapping, Comparator.naturalOrder());
+ return minOrMax(groupValueMapping, Comparator.naturalOrder(), true);
+ }
+
+ /**
+ * Returns a collector that finds a minimum value in a group of {@link Comparable} elements.
+ * The elements will be compared according to the value returned by the comparable function.
+ * <p>
+ * Important: The {@link Comparable}'s {@link Comparable#compareTo(Object)} must be <i>consistent with equals</i>,
+ * such that {@code e1.compareTo(e2) == 0} has the same boolean value as {@code e1.equals(e2)}.
+ * In other words, if two elements compare to zero, any of them can be returned by the collector.
+ * It can even differ between 2 score calculations on the exact same {@link PlanningSolution} state, due to
+ * incremental score calculation.
+ * <p>
+ * For example, {@code [Ann(age = 20), Beth(age = 25), Cathy(age = 30), David(age = 30), Eric(age = 20)]} with
+ * {@code .groupBy(max(Person::name, Person::age))} returns {@code Ann} or {@code Eric}, | ```suggestion
* {@code .groupBy(min(Person::name, Person::age))} returns {@code Ann} or {@code Eric},
``` |
timefold-solver | github_2023 | java | 90 | TimefoldAI | rsynek | @@ -35,11 +37,34 @@ public int countMutations(Solution_ a, Solution_ b) {
Object bEntity = bIt.next();
for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor
.getGenuineVariableDescriptorList()) {
- // TODO broken if the value is an entity, because then it's never the same
- // But we don't want to depend on value/entity equals() => use surrogate entity IDs to compare
- // https://issues.redhat.com/browse/PLANNER-170
- if (variableDescriptor.getValue(aEntity) != variableDescriptor.getValue(bEntity)) {
- mutationCount++;
+ if (variableDescriptor.isListVariable()) {
+ ListVariableDescriptor<Solution_> listVariableDescriptor =
+ (ListVariableDescriptor<Solution_>) variableDescriptor;
+ List<Object> aValues = listVariableDescriptor.getListVariable(aEntity);
+ List<Object> bValues = listVariableDescriptor.getListVariable(bEntity);
+ int aSize = aValues.size();
+ int bSize = bValues.size();
+ if (aSize != bSize) {
+ // First add mutations for the elements that are missing in one list.
+ mutationCount += Math.abs(aSize - bSize);
+ }
+ // Then iterate over the list and count every item that is different.
+ for (int i = 0; i < aSize; i++) { | Maybe slightly more readable:
```
int shorterListSize = Math.min(aSize, bSize);
for (int i = 0; i < shorterListSize; i++) {
``` |
timefold-solver | github_2023 | others | 69 | TimefoldAI | rsynek | @@ -0,0 +1,17 @@
+# https://github.com/Ezard/semantic-prs
+enabled: true
+titleAndCommits: true
+allowMergeCommits: false
+types:
+ - feat
+ - fix
+ - docs
+ - style
+ - refactor
+ - perf
+ - test
+ - build
+ - ci
+ - chore | What's the difference between style, refactor and chore? And what about build vs. ci? The fewer keywords we use, the bigger chance we use them right. |
timefold-solver | github_2023 | others | 69 | TimefoldAI | rsynek | @@ -0,0 +1,74 @@
+== Contributing to Timefold Solver
+
+This is an open source project, and you are more than welcome to contribute!
+
+* Found an issue? https://github.com/TimefoldAI/timefold-solver/issues[Submit an issue.]
+* Want to fix an issue or contribute an improvement? https://github.com/TimefoldAI/timefold-solver/discussions[Talk to us about your ideas] or just start coding:
+
+. https://github.com/TimefoldAI/timefold-solver[Fork it.] | ```suggestion
. https://github.com/TimefoldAI/timefold-solver/fork[Fork it.]
``` |
timefold-solver | github_2023 | others | 69 | TimefoldAI | rsynek | @@ -0,0 +1,74 @@
+== Contributing to Timefold Solver
+
+This is an open source project, and you are more than welcome to contribute!
+
+* Found an issue? https://github.com/TimefoldAI/timefold-solver/issues[Submit an issue.]
+* Want to fix an issue or contribute an improvement? https://github.com/TimefoldAI/timefold-solver/discussions[Talk to us about your ideas] or just start coding:
+
+. https://github.com/TimefoldAI/timefold-solver[Fork it.]
+. Create a feature branch: `git checkout -b feature`
+. Commit your changes with a comment: `git commit -m "feat: add shiny new feature"`
+(See xref:commit-messages[Commit messages] for details.)
+. Push to the branch to GitHub: `git push origin feature`
+. https://github.com/TimefoldAI/timefold-solver[Create a new Pull Request.] | ```suggestion
. https://github.com/TimefoldAI/timefold-solver/compare[Create a new Pull Request.]
``` |
timefold-solver | github_2023 | java | 68 | TimefoldAI | rsynek | @@ -103,6 +123,29 @@ public void update(InTuple_ tuple) {
}
}
+ private List<FlattenedItem_> iterableToList(Iterable<FlattenedItem_> iterable) {
+ if (iterable instanceof Collection<FlattenedItem_> collection) {
+ // Optimization for Collection, where we know the size.
+ int size = collection.size();
+ if (size == 0) {
+ return Collections.emptyList();
+ }
+ List<FlattenedItem_> result = new ArrayList<>(size); | In this case, it is safe to cast the `iterable` to a `Collection` and pass it here directly. It could bring an additional minor perf improvement, if we skip the `forEach` and the method reference (no proof). |
timefold-solver | github_2023 | java | 28 | TimefoldAI | ge0ffrey | @@ -131,8 +130,7 @@ public BenchmarkAggregatorFrame(BenchmarkAggregator benchmarkAggregator) {
this.benchmarkAggregator = benchmarkAggregator;
benchmarkResultIO = new BenchmarkResultIO();
plannerBenchmarkResultList = Collections.emptyList();
- Locale locale = benchmarkAggregator.getBenchmarkReportConfig().determineLocale();
- millisecondsSpentNumberFormat = new MillisecondsSpentNumberFormat(locale);
+ millisecondsSpentNumberFormat = new MillisecondsSpentNumberFormat(); | A) Either the benchmark report has a locale.
B) Or the locale is the eye of the beholder. Basically, the browser's locale determines if it's 1'000,05 (BE) or 1,000.05 (US).
If B) is possible, I prefer that. A big advantage over the JfreeChart approach is that the locale isn't hard coded in the report output.
Anyway:
- In A), the MillisecondsSpentNumberFormat should still use the locale. Even if it's just for tables in html.
- In B), the millisecondsSpentNumberFormat can be removed, as no number is formatted during report generation (only during report rendering).
|
timefold-solver | github_2023 | others | 28 | TimefoldAI | ge0ffrey | @@ -56,6 +56,10 @@
<version.surefire.plugin>3.0.0-M8</version.surefire.plugin>
<version.versions.plugin>2.15.0</version.versions.plugin>
+ <version.org.webjars.webjars-locator>0.46</version.org.webjars.webjars-locator>
+ <version.org.webjars.bootstrap>5.2.3</version.org.webjars.bootstrap>
+ <version.org.webjars.jquery>3.6.4</version.org.webjars.jquery> | Should be at line 35 in this file, with the other dependency version, not with the plugin versions. |
timefold-solver | github_2023 | others | 28 | TimefoldAI | ge0ffrey | @@ -148,6 +152,24 @@
<artifactId>jcl-over-slf4j</artifactId>
<version>${version.org.slf4j}</version>
</dependency>
+ <dependency>
+ <groupId>org.webjars</groupId>
+ <artifactId>webjars-locator</artifactId>
+ <version>${version.org.webjars.webjars-locator}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.webjars</groupId>
+ <artifactId>bootstrap</artifactId>
+ <version>${version.org.webjars.bootstrap}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.webjars</groupId>
+ <artifactId>jquery</artifactId>
+ <version>${version.org.webjars.jquery}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <!-- Webjars --> | comment should be above these artifacts? |
timefold-solver | github_2023 | java | 1,493 | TimefoldAI | zepfred | @@ -27,14 +27,17 @@
import ai.timefold.solver.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import ai.timefold.solver.core.config.phase.PhaseConfig;
+import ai.timefold.solver.core.config.solver.PreviewFeature;
import ai.timefold.solver.core.config.util.ConfigUtils;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveProviders;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
@XmlType(propOrder = {
"localSearchType",
"moveSelectorConfig",
+ "moveProvidersClass", | Should it be named `moveProviderClass`? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -155,12 +157,12 @@ protected void pickMove(ConstructionHeuristicStepScope<Solution_> stepScope) {
protected <Score_ extends Score<Score_>> void doMove(ConstructionHeuristicMoveScope<Solution_> moveScope) {
InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
- scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
- moveScope.setScore(score);
- forager.addMove(moveScope);
- });
+ var score = scoreDirector.executeTemporaryMove(moveScope.getMove(), assertMoveScoreFromScratch);
+ moveScope.setScore(score);
+ forager.addMove(moveScope);
if (assertExpectedUndoMoveScore) {
- scoreDirector.assertExpectedUndoMoveScore(moveScope.getMove(),
+ var undoMoveToString = "Undo(%s)".formatted(moveScope.getMove()); | This variable seems off to me. I think it should be within the scope of `scoreDirector.assertExpectedUndoMoveScore`. |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -24,17 +25,17 @@ public class DefaultConstructionHeuristicPhase<Solution_>
implements ConstructionHeuristicPhase<Solution_> {
protected final ConstructionHeuristicDecider<Solution_> decider;
- protected final EntityPlacer<Solution_> entityPlacer;
+ protected final PlacerBasedMoveRepository<Solution_> moveRepository;
private TerminationStatus terminationStatus = TerminationStatus.NOT_TERMINATED;
protected DefaultConstructionHeuristicPhase(DefaultConstructionHeuristicPhaseBuilder<Solution_> builder) {
super(builder);
this.decider = builder.decider;
- this.entityPlacer = builder.getEntityPlacer();
+ this.moveRepository = new PlacerBasedMoveRepository<>(builder.getEntityPlacer()); | Should we retrieve it from the builder? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -131,29 +126,32 @@ public void expandNode(ExhaustiveSearchStepScope<Solution_> stepScope) {
@SuppressWarnings("unchecked")
private <Score_ extends Score<Score_>> void doMove(ExhaustiveSearchStepScope<Solution_> stepScope,
ExhaustiveSearchNode moveNode) {
- InnerScoreDirector<Solution_, Score_> scoreDirector = stepScope.getScoreDirector();
- Move<Solution_> move = moveNode.getMove();
- try (var ephemeralMoveDirector = scoreDirector.getMoveDirector().ephemeral()) {
- move.execute(ephemeralMoveDirector);
- processMove(stepScope, moveNode);
- moveNode.setUndoMove(ephemeralMoveDirector.createUndoMove());
- }
- // TODO reuse scoreDirector.doAndProcessMove() unless it's an expandableNode
+ var scoreDirector = stepScope.<Score_> getScoreDirector();
+ var move = moveNode.getMove();
+ var undoMove = scoreDirector.getMoveDirector().executeTemporary(move, | Let's make the name consistent. We have used `executeTemporaryMove` in the CH decider. |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -131,29 +126,32 @@ public void expandNode(ExhaustiveSearchStepScope<Solution_> stepScope) {
@SuppressWarnings("unchecked")
private <Score_ extends Score<Score_>> void doMove(ExhaustiveSearchStepScope<Solution_> stepScope,
ExhaustiveSearchNode moveNode) {
- InnerScoreDirector<Solution_, Score_> scoreDirector = stepScope.getScoreDirector();
- Move<Solution_> move = moveNode.getMove();
- try (var ephemeralMoveDirector = scoreDirector.getMoveDirector().ephemeral()) {
- move.execute(ephemeralMoveDirector);
- processMove(stepScope, moveNode);
- moveNode.setUndoMove(ephemeralMoveDirector.createUndoMove());
- }
- // TODO reuse scoreDirector.doAndProcessMove() unless it's an expandableNode
+ var scoreDirector = stepScope.<Score_> getScoreDirector();
+ var move = moveNode.getMove();
+ var undoMove = scoreDirector.getMoveDirector().executeTemporary(move,
+ (moveDirector, score) -> {
+ processMove(stepScope, moveNode);
+ return moveDirector.createUndoMove();
+ });
+ moveNode.setUndoMove(undoMove);
var executionPoint = SolverLifecyclePoint.of(stepScope, moveNode.getTreeId());
if (assertExpectedUndoMoveScore) {
// In BRUTE_FORCE a stepScore can be null because it was not calculated
if (stepScope.getStartingStepScore() != null) {
- scoreDirector.assertExpectedUndoMoveScore(move, (Score_) stepScope.getStartingStepScore(), executionPoint);
+ var undoMoveToString = "Undo(%s)".formatted(move); | Same as before. The scope seems incorrect to me. |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -113,21 +111,20 @@ public void decideNextStep(LocalSearchStepScope<Solution_> stepScope) {
@SuppressWarnings("unchecked")
protected <Score_ extends Score<Score_>> void doMove(LocalSearchMoveScope<Solution_> moveScope) {
- InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
- MoveDirector<Solution_> moveDirector = moveScope.getStepScope().getMoveDirector();
- Move<Solution_> move = moveScope.getMove();
+ var scoreDirector = (InnerScoreDirector<Solution_, Score_>) moveScope.getScoreDirector();
+ var moveDirector = (MoveDirector<Solution_, Score_>) moveScope.getStepScope().getMoveDirector();
+ var move = moveScope.getMove();
if (!LegacyMoveAdapter.isDoable(moveDirector, move)) {
- throw new IllegalStateException("Impossible state: Local search move selector (" + moveSelector
+ throw new IllegalStateException("Impossible state: Local search move selector (" + moveRepository
+ ") provided a non-doable move (" + moveScope.getMove() + ").");
}
- scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
- moveScope.setScore(score);
- boolean accepted = acceptor.isAccepted(moveScope);
- moveScope.setAccepted(accepted);
- forager.addMove(moveScope);
- });
+ var score = scoreDirector.executeTemporaryMove(moveScope.getMove(), assertMoveScoreFromScratch);
+ moveScope.setScore(score);
+ moveScope.setAccepted(acceptor.isAccepted(moveScope));
+ forager.addMove(moveScope);
if (assertExpectedUndoMoveScore) {
- scoreDirector.assertExpectedUndoMoveScore(moveScope.getMove(),
+ var undoMoveToString = "Undo(%s)".formatted(move); | Same as before |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -113,21 +111,20 @@ public void decideNextStep(LocalSearchStepScope<Solution_> stepScope) {
@SuppressWarnings("unchecked")
protected <Score_ extends Score<Score_>> void doMove(LocalSearchMoveScope<Solution_> moveScope) {
- InnerScoreDirector<Solution_, Score_> scoreDirector = moveScope.getScoreDirector();
- MoveDirector<Solution_> moveDirector = moveScope.getStepScope().getMoveDirector();
- Move<Solution_> move = moveScope.getMove();
+ var scoreDirector = (InnerScoreDirector<Solution_, Score_>) moveScope.getScoreDirector();
+ var moveDirector = (MoveDirector<Solution_, Score_>) moveScope.getStepScope().getMoveDirector();
+ var move = moveScope.getMove();
if (!LegacyMoveAdapter.isDoable(moveDirector, move)) {
- throw new IllegalStateException("Impossible state: Local search move selector (" + moveSelector
+ throw new IllegalStateException("Impossible state: Local search move selector (" + moveRepository
+ ") provided a non-doable move (" + moveScope.getMove() + ").");
}
- scoreDirector.doAndProcessMove(moveScope.getMove(), assertMoveScoreFromScratch, score -> {
- moveScope.setScore(score);
- boolean accepted = acceptor.isAccepted(moveScope);
- moveScope.setAccepted(accepted);
- forager.addMove(moveScope);
- });
+ var score = scoreDirector.executeTemporaryMove(moveScope.getMove(), assertMoveScoreFromScratch); | Did you notice any improvements in performance after removing this lambda? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -57,12 +58,12 @@ phaseTermination, buildDecider(phaseConfigPolicy, phaseTermination))
private LocalSearchDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy,
PhaseTermination<Solution_> termination) {
- var moveSelector = buildMoveSelector(configPolicy);
+ var moveRepository = new MoveSelectorBasedMoveRepository<>(buildMoveSelector(configPolicy));
var acceptor = buildAcceptor(configPolicy);
var forager = buildForager(configPolicy);
- if (moveSelector.isNeverEnding() && !forager.supportsNeverEndingMoveSelector()) {
- throw new IllegalStateException("The moveSelector (" + moveSelector
- + ") has neverEnding (" + moveSelector.isNeverEnding()
+ if (moveRepository.isNeverEnding() && !forager.supportsNeverEndingMoveSelector()) { | Let's use `String::format` |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -2,64 +2,82 @@
import java.util.List;
import java.util.Objects;
+import java.util.function.BiFunction;
+import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningListVariableMetaModel;
import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.heuristic.move.LegacyMoveAdapter;
import ai.timefold.solver.core.impl.move.InnerMutableSolutionView;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
import ai.timefold.solver.core.preview.api.domain.metamodel.ElementLocation;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
+import ai.timefold.solver.core.preview.api.move.Move;
import ai.timefold.solver.core.preview.api.move.Rebaser;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
@NullMarked
-public sealed class MoveDirector<Solution_>
+public sealed class MoveDirector<Solution_, Score_ extends Score<Score_>>
implements InnerMutableSolutionView<Solution_>, Rebaser
permits EphemeralMoveDirector {
- protected final VariableDescriptorAwareScoreDirector<Solution_> scoreDirector;
-
- public MoveDirector(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector) {
- this.scoreDirector = Objects.requireNonNull(scoreDirector);
+ protected final VariableDescriptorAwareScoreDirector<Solution_> externalScoreDirector;
+ private final InnerScoreDirector<Solution_, Score_> backingScoreDirector;
+
+ public MoveDirector(InnerScoreDirector<Solution_, Score_> scoreDirector) {
+ this.backingScoreDirector = Objects.requireNonNull(scoreDirector);
+ if (getClass() == EphemeralMoveDirector.class) { | ```suggestion
if (EphemeralMoveDirector.class.isAssignableFrom(getClass())) {
``` |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -0,0 +1,116 @@
+package ai.timefold.solver.core.impl.move.generic;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.impl.util.CollectionUtils;
+import ai.timefold.solver.core.preview.api.move.Move;
+import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
+import ai.timefold.solver.core.preview.api.move.Rebaser;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * A CompositeMove is composed out of multiple other moves.
+ * <p>
+ * Warning: each of moves in the moveList must not rely on the effect of a previous move in the moveList
+ * to create its undoMove correctly.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @see Move
+ */
+@NullMarked
+public final class CompositeMove<Solution_> implements Move<Solution_> {
+
+ /**
+ * @param moves never null, sometimes empty. Do not modify this argument afterwards or the CompositeMove corrupts.
+ * @return never null
+ */
+ @SafeVarargs
+ public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(Move_... moves) {
+ return switch (moves.length) {
+ case 0 -> NoChangeMove.getInstance();
+ case 1 -> moves[0];
+ default -> new CompositeMove<>(moves);
+ };
+ }
+
+ /**
+ * @param moveList never null, sometimes empty
+ * @return never null
+ */
+ @SuppressWarnings("unchecked")
+ public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(List<Move_> moveList) {
+ return buildMove(moveList.toArray(new Move[0]));
+ }
+
+ private final Move<Solution_>[] moves;
+
+ private CompositeMove(Move<Solution_>[] moves) {
+ this.moves = moves;
+ }
+
+ @Override
+ public void execute(MutableSolutionView<Solution_> solutionView) {
+ for (Move<Solution_> move : moves) {
+ move.execute(solutionView);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Move<Solution_> rebase(Rebaser rebaser) {
+ Move<Solution_>[] rebasedMoves = new Move[moves.length];
+ for (int i = 0; i < moves.length; i++) {
+ rebasedMoves[i] = moves[i].rebase(rebaser);
+ }
+ return new CompositeMove<>(rebasedMoves);
+ }
+
+ @Override
+ public Collection<?> extractPlanningEntities() {
+ Set<Object> entities = CollectionUtils.newLinkedHashSet(moves.length * 2); | Should we use `LinkedIdentityHashSet`? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -0,0 +1,116 @@
+package ai.timefold.solver.core.impl.move.generic;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.impl.util.CollectionUtils;
+import ai.timefold.solver.core.preview.api.move.Move;
+import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
+import ai.timefold.solver.core.preview.api.move.Rebaser;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * A CompositeMove is composed out of multiple other moves.
+ * <p>
+ * Warning: each of moves in the moveList must not rely on the effect of a previous move in the moveList
+ * to create its undoMove correctly.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @see Move
+ */
+@NullMarked
+public final class CompositeMove<Solution_> implements Move<Solution_> {
+
+ /**
+ * @param moves never null, sometimes empty. Do not modify this argument afterwards or the CompositeMove corrupts.
+ * @return never null
+ */
+ @SafeVarargs
+ public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(Move_... moves) {
+ return switch (moves.length) {
+ case 0 -> NoChangeMove.getInstance();
+ case 1 -> moves[0];
+ default -> new CompositeMove<>(moves);
+ };
+ }
+
+ /**
+ * @param moveList never null, sometimes empty
+ * @return never null
+ */
+ @SuppressWarnings("unchecked")
+ public static <Solution_, Move_ extends Move<Solution_>> Move<Solution_> buildMove(List<Move_> moveList) {
+ return buildMove(moveList.toArray(new Move[0]));
+ }
+
+ private final Move<Solution_>[] moves;
+
+ private CompositeMove(Move<Solution_>[] moves) {
+ this.moves = moves;
+ }
+
+ @Override
+ public void execute(MutableSolutionView<Solution_> solutionView) {
+ for (Move<Solution_> move : moves) {
+ move.execute(solutionView);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Move<Solution_> rebase(Rebaser rebaser) {
+ Move<Solution_>[] rebasedMoves = new Move[moves.length];
+ for (int i = 0; i < moves.length; i++) {
+ rebasedMoves[i] = moves[i].rebase(rebaser);
+ }
+ return new CompositeMove<>(rebasedMoves);
+ }
+
+ @Override
+ public Collection<?> extractPlanningEntities() {
+ Set<Object> entities = CollectionUtils.newLinkedHashSet(moves.length * 2);
+ for (Move<Solution_> move : moves) {
+ entities.addAll(move.extractPlanningEntities());
+ }
+ return entities;
+ }
+
+ @Override
+ public Collection<?> extractPlanningValues() {
+ Set<Object> values = CollectionUtils.newLinkedHashSet(moves.length * 2); | Same as before |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -0,0 +1,12 @@
+package ai.timefold.solver.core.impl.move.streams;
+
+import java.util.Iterator;
+import java.util.Random;
+
+import ai.timefold.solver.core.preview.api.move.Move;
+
+public interface MoveIterable<Solution_> extends Iterable<Move<Solution_>> { | I'm not sure what the advantage is of creating this abstraction |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -0,0 +1,34 @@
+package ai.timefold.solver.core.impl.move;
+
+import ai.timefold.solver.core.impl.phase.event.PhaseLifecycleListener;
+import ai.timefold.solver.core.preview.api.move.Move;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * This is a shared abstraction for all three types of move iterators currently used in the solver:
+ *
+ * <ul>
+ * <li>{@link MoveSelectorBasedMoveRepository} for local search and exhaustive search.</li>
+ * <li>{@link PlacerBasedMoveRepository} for construction heuristics.</li>
+ * <li>{@link MoveStreamsBasedMoveRepository} for move streams.</li>
+ * </ul>
+ *
+ * As move streams become gradually more capable, | If we plan to use only this repository in the future, we need to consider that both CH and the Exact methods require a finite repository. |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -190,6 +182,7 @@ protected <Score_ extends Score<Score_>> void predictWorkingStepScore(AbstractSt
@Override
public void stepEnded(AbstractStepScope<Solution_> stepScope) {
if (!isNested()) {
+ var solver = stepScope.getPhaseScope().getSolverScope().getSolver(); | To ensure that these solver changes do not cause score corruption, we need to avoid sharing the score director in nested phases, while the solver itself can be shared. Given that the previous statement is correct, the changes will not cause any issues. Does that make sense? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -229,25 +226,42 @@ public void setWorkingSolution(Solution_ workingSolution) {
* possibly many thousands of objects.
* Providing the init score and genuine entity count requires another pass over the entities.
* The following code does all of those operations in a single pass.
+ * It will also run the optional entityAndFactVisitor from the calling code,
+ * as that would have also resulted in another pass over all entities and facts.
*/
- Consumer<Object> visitor = null;
if (lookUpEnabled) {
lookUpManager.reset();
- visitor = lookUpManager::addWorkingObject;
- // This visits all the problem facts, applying the visitor.
- solutionDescriptor.visitAllProblemFacts(workingSolution, visitor);
+ Consumer<Object> workingObjectLookupVisitor = lookUpManager::addWorkingObject;
+ entityAndFactVisitor = entityAndFactVisitor == null ? workingObjectLookupVisitor
+ : entityAndFactVisitor.andThen(workingObjectLookupVisitor);
+ }
+ // This visits all the facts, applying the visitor if non-null.
+ if (entityAndFactVisitor != null) {
+ solutionDescriptor.visitAllProblemFacts(workingSolution, entityAndFactVisitor);
}
- // This visits all the entities, applying the visitor if non-null.
Consumer<Object> entityValidator = entity -> scoreDirectorFactory.validateEntity(this, entity);
- visitor = visitor == null ? entityValidator : visitor.andThen(entityValidator);
- var initializationStatistics = solutionDescriptor.computeInitializationStatistics(workingSolution, visitor);
+ entityAndFactVisitor = entityAndFactVisitor == null ? entityValidator : entityAndFactVisitor.andThen(entityValidator);
+ // This visits all the entities.
+ var initializationStatistics =
+ solutionDescriptor.computeInitializationStatistics(workingSolution, entityAndFactVisitor);
setWorkingEntityListDirty();
workingInitScore =
-(initializationStatistics.unassignedValueCount() + initializationStatistics.uninitializedVariableCount());
assertInitScoreZeroOrLess();
workingGenuineEntityCount = initializationStatistics.genuineEntityCount();
variableListenerSupport.resetWorkingSolution();
+ if (moveRepository != null) {
+ moveRepository.initialize(workingSolution);
+ }
+ }
+
+ @Override
+ public void setMoveRepository(@Nullable MoveRepository<Solution_> moveRepository) {
+ this.moveRepository = moveRepository;
+ if (moveRepository != null) {
+ moveRepository.initialize(workingSolution); | I wonder if `moveRepository.initialize` will be called twice. |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -260,25 +274,30 @@ private void assertInitScoreZeroOrLess() {
}
@Override
- public Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFromScratch, Consumer<Score_> moveProcessor) {
- if (trackingWorkingSolution) {
+ public void executeMove(Move<Solution_> move) { | Is it safe to skip the assertions here? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -90,6 +92,19 @@ static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> getConstraintAn
*/
void setWorkingSolution(Solution_ workingSolution);
+ /** | This comment answers one of my questions |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -26,34 +23,10 @@ public interface InnerScoreDirectorFactory<Solution_, Score_ extends Score<Score
*/
ScoreDefinition<Score_> getScoreDefinition();
- @Override
- default InnerScoreDirector<Solution_, Score_> buildScoreDirector(boolean lookUpEnabled,
- ConstraintMatchPolicy constraintMatchPolicy) {
- return buildScoreDirector(lookUpEnabled, constraintMatchPolicy, true);
- }
-
- @Override
- InnerScoreDirector<Solution_, Score_> buildScoreDirector(boolean lookUpEnabled, ConstraintMatchPolicy constraintMatchPolicy,
- boolean expectShadowVariablesInCorrectState);
+ AbstractScoreDirector.AbstractScoreDirectorBuilder<Solution_, Score_, ?, ?> createScoreDirectorBuilder(); | Should this method be part of `ScoreDirectorFactory`? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -12,20 +10,4 @@
*/
public interface ScoreDirectorFactory<Solution_> { | Does it make sense to maintain this interface? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -80,21 +77,21 @@ void oldAndNewTrailing() {
var inverseVariableSupply = SelectorTestUtils.mockSingletonInverseVariableSupply(
new TestdataChainedEntity[] { a1, a2, a3, a4, a5, b1, b2, b3 });
- try (var ephemeralMoveDirector = new MoveDirector<>(innerScoreDirector).ephemeral()) {
- var scoreDirector = Mockito.spy(ephemeralMoveDirector.getScoreDirector());
- var move = new SubChainSwapMove<>(variableDescriptor, inverseVariableSupply,
- new SubChain(Arrays.asList(a2, a3, a4)),
- new SubChain(Arrays.asList(b1, b2)));
- move.doMoveOnly(scoreDirector);
-
- SelectorTestUtils.assertChain(a0, a1, b1, b2, a5);
- SelectorTestUtils.assertChain(b0, a2, a3, a4, b3);
-
- verify(scoreDirector).changeVariableFacade(variableDescriptor, a2, b0);
- verify(scoreDirector).changeVariableFacade(variableDescriptor, b3, a4);
- verify(scoreDirector).changeVariableFacade(variableDescriptor, b1, a1);
- verify(scoreDirector).changeVariableFacade(variableDescriptor, a5, b2);
- }
+ var moveDirector = new MoveDirector<>(innerScoreDirector); | I observed in several places that we are not invoking `executeTemporaryMove` when replacing the ephemeral director. Can this be a problem? |
timefold-solver | github_2023 | java | 1,476 | TimefoldAI | zepfred | @@ -133,48 +148,47 @@ void doMoveInSameChain() {
SelectorTestUtils.assertChain(a0, a1, a2, a3, a4, a5, a6, a7);
var moveDirector = new MoveDirector<>(innerScoreDirector);
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply,
- anchorVariableSupply, a4, a1);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a1, a4, a3, a2, a5, a6, a7);
- }
-
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, a3, a1);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a1, a3, a2, a4, a5, a6, a7);
- }
-
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, a7, a1);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a1, a7, a6, a5, a4, a3, a2);
- }
-
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, a1, a4);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a7, a6, a5, a2, a3, a4, a1);
- }
-
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, a3, a4);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a7, a6, a5, a4, a3, a2, a1);
- }
-
- try (var ephemeralMoveDirector = moveDirector.ephemeral()) {
- var scoreDirector = ephemeralMoveDirector.getScoreDirector();
- var move = new TailChainSwapMove<>(variableDescriptor, inverseVariableSupply, anchorVariableSupply, a2, a6);
- move.doMoveOnly(scoreDirector);
- SelectorTestUtils.assertChain(a0, a7, a3, a4, a5, a6, a2, a1);
- }
+ moveDirector.executeTemporary( | This one you're calling the temporary action |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -57,6 +60,7 @@ public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDi
.toList();
this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getListVariableDescriptor();
this.listVariableEventList = new ArrayList<>();
+ this.unassignedValueWithEmptyInverseEntitySet = new HashSet<>(); | Arguably this should be an identity hash set; no entities should be considered equal here. (The class doesn't exist in the JDK, but it can be created by converting `IdentityHashMap`.) |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,126 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Collection;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Set;
+
+public class IdentityHashSet<V> implements Set<V> { | Take a look at the Javadoc of `AbstractSet` - it explains how to write a minimal set implementation. All the other methods should only be implemented if you can make them faster in your implementation, and arguably in this case, we don't really need it. Less is more. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,126 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Collection;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Set;
+
+public class IdentityHashSet<V> implements Set<V> {
+
+ private ElementAwareList<V> delegate;
+ private IdentityHashMap<V, ElementAwareListEntry<V>> identityMap; | Let's make them final. Clearing is cheap, final is fast. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,126 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.Collection;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Set;
+
+public class IdentityHashSet<V> implements Set<V> {
+
+ private ElementAwareList<V> delegate;
+ private IdentityHashMap<V, ElementAwareListEntry<V>> identityMap;
+
+ public IdentityHashSet() { | Should be called `LinkedIdentityHashSet`. Also, it should be final. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -57,6 +60,7 @@ public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDi
.toList();
this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getListVariableDescriptor();
this.listVariableEventList = new ArrayList<>();
+ this.unassignedValueWithEmptyInverseEntitySet = new IdentityHashSet<>(); | We should add a comment here, explaining why we chose this particular type.
(It's not obvious.) |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -240,61 +261,83 @@ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variable
public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex) {
var notifiables = notifiableRegistry.get(variableDescriptor);
+ var notification = Notification.<Solution_> listVariableChanged(entity, fromIndex, toIndex);
if (!notifiables.isEmpty()) {
- ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex);
for (var notifiable : notifiables) {
notifiable.notifyAfter(notification);
}
notificationQueuesAreEmpty = false;
}
- listVariableEventList.add(new ListVariableEvent(entity, fromIndex, toIndex));
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade.
+ listVariableChangedNotificationList.add(notification);
+ }
}
public void triggerVariableListenersInNotificationQueues() {
for (var notifiable : notifiableRegistry.getAll()) {
notifiable.triggerAllNotifications();
}
- if (listVariableDescriptor != null && !cascadingUpdateShadowVarDescriptorList.isEmpty()) {
+ // If there is no cascade, skip the whole thing.
+ // If there are no events and no newly unassigned variables, skip the whole thing as well.
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty() &&
+ !(listVariableChangedNotificationList.isEmpty() && unassignedValueWithEmptyInverseEntitySet.isEmpty())) {
triggerCascadingUpdateShadowVariableUpdate();
}
notificationQueuesAreEmpty = true;
- listVariableEventList.clear();
}
- /**
- * Triggers all cascading update shadow variable user-logic.
- */
private void triggerCascadingUpdateShadowVariableUpdate() {
- if (listVariableEventList.isEmpty() || cascadingUpdateShadowVarDescriptorList.isEmpty()) {
- return;
- }
for (var cascadingUpdateShadowVariableDescriptor : cascadingUpdateShadowVarDescriptorList) {
- for (var event : listVariableEventList) {
- var values = listVariableDescriptor.getValue(event.entity());
- // Evaluate all elements inside the range
- evaluateFromIndex(values, event.fromIndex(), event.toIndex(), true, cascadingUpdateShadowVariableDescriptor);
- // Evaluate later elements, but stops when there is no change
- evaluateFromIndex(values, event.toIndex(), values.size(), false, cascadingUpdateShadowVariableDescriptor); | Both of these separate iterations have been merged together to just one iteration.
If you can iterate once, iterate once; useful for CPU caches. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -240,61 +261,83 @@ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variable
public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex) {
var notifiables = notifiableRegistry.get(variableDescriptor);
+ var notification = Notification.<Solution_> listVariableChanged(entity, fromIndex, toIndex);
if (!notifiables.isEmpty()) {
- ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex);
for (var notifiable : notifiables) {
notifiable.notifyAfter(notification);
}
notificationQueuesAreEmpty = false;
}
- listVariableEventList.add(new ListVariableEvent(entity, fromIndex, toIndex));
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade.
+ listVariableChangedNotificationList.add(notification);
+ }
}
public void triggerVariableListenersInNotificationQueues() {
for (var notifiable : notifiableRegistry.getAll()) {
notifiable.triggerAllNotifications();
}
- if (listVariableDescriptor != null && !cascadingUpdateShadowVarDescriptorList.isEmpty()) {
+ // If there is no cascade, skip the whole thing.
+ // If there are no events and no newly unassigned variables, skip the whole thing as well.
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty() &&
+ !(listVariableChangedNotificationList.isEmpty() && unassignedValueWithEmptyInverseEntitySet.isEmpty())) {
triggerCascadingUpdateShadowVariableUpdate();
}
notificationQueuesAreEmpty = true;
- listVariableEventList.clear();
}
- /**
- * Triggers all cascading update shadow variable user-logic.
- */
private void triggerCascadingUpdateShadowVariableUpdate() {
- if (listVariableEventList.isEmpty() || cascadingUpdateShadowVarDescriptorList.isEmpty()) {
- return;
- }
for (var cascadingUpdateShadowVariableDescriptor : cascadingUpdateShadowVarDescriptorList) {
- for (var event : listVariableEventList) {
- var values = listVariableDescriptor.getValue(event.entity());
- // Evaluate all elements inside the range
- evaluateFromIndex(values, event.fromIndex(), event.toIndex(), true, cascadingUpdateShadowVariableDescriptor);
- // Evaluate later elements, but stops when there is no change
- evaluateFromIndex(values, event.toIndex(), values.size(), false, cascadingUpdateShadowVariableDescriptor);
- }
+ cascadeListVariableChangedNotifications(cascadingUpdateShadowVariableDescriptor);
+ // When the unassigned element has no inverse entity,
+ // it indicates that it is not reverting to a previous entity.
+ // In this case, we need to invoke the cascading logic,
+ // or its related shadow variables will remain unchanged.
+ cascadeUnassignedValues(cascadingUpdateShadowVariableDescriptor);
+ }
+ listVariableChangedNotificationList.clear();
+ unassignedValueWithEmptyInverseEntitySet.clear();
+ }
+
+ private void cascadeListVariableChangedNotifications(
+ CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) {
+ for (var notification : listVariableChangedNotificationList) {
+ cascadeListVariableValueUpdates(
+ listVariableDescriptor.getValue(notification.getEntity()),
+ notification.getFromIndex(), notification.getToIndex(),
+ cascadingUpdateShadowVariableDescriptor);
}
}
- private void evaluateFromIndex(List<Object> values, int fromIndex, int toIndex, boolean forceUpdate,
+ private void cascadeListVariableValueUpdates(List<Object> values, int fromIndex, int toIndex,
CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) {
- var lastUpdated = fromIndex;
- while (lastUpdated < toIndex) {
- if (!cascadingUpdateShadowVariableDescriptor.update(scoreDirector, values.get(lastUpdated))
- && !forceUpdate) {
+ for (int currentIndex = fromIndex; currentIndex < values.size(); currentIndex++) {
+ var value = values.get(currentIndex);
+ // The value is present in the unassigned values,
+ // but the cascade logic is triggered by a list event.
+ // So, we can remove it from the unassigned list
+ // since the entity will be reverted to a previous entity.
+ unassignedValueWithEmptyInverseEntitySet.remove(value);
+ // Force updates within the range.
+ // Outside the range, only update while the values keep changing.
+ var forceUpdate = currentIndex < toIndex;
+ if (!cascadingUpdateShadowVariableDescriptor.update(scoreDirector, value) && !forceUpdate) {
break;
}
- lastUpdated++;
+ }
+ }
+
+ private void cascadeUnassignedValues( | I only split this into a separate method so that I can see its impact in the profiler individually. This is not actually a perf optimization, just helps with profiling. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,77 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.AbstractSet;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * This set does not support null keys.
+ *
+ * @param <V>
+ */
+@NullMarked
+public final class LinkedIdentityHashSet<V> extends AbstractSet<V> {
+
+ private final ElementAwareList<V> delegate;
+ private final IdentityHashMap<V, ElementAwareListEntry<V>> identityMap;
+ private int size = 0; // Avoid method calls to underlying collections.
+
+ public LinkedIdentityHashSet() {
+ this.delegate = new ElementAwareList<>();
+ this.identityMap = new IdentityHashMap<>();
+ }
+
+ @Override
+ public Iterator<V> iterator() {
+ return delegate.iterator();
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ if (size == 0) { // Micro-optimization; contains() on an empty map is not entirely free.
+ return false;
+ } | These zero checks are speculative; but if you take a look at what the map does even when it's empty, I bet this will prove itself if the methods are called often enough. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,77 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.AbstractSet;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * This set does not support null keys.
+ *
+ * @param <V>
+ */
+@NullMarked
+public final class LinkedIdentityHashSet<V> extends AbstractSet<V> {
+
+ private final ElementAwareList<V> delegate;
+ private final IdentityHashMap<V, ElementAwareListEntry<V>> identityMap;
+ private int size = 0; // Avoid method calls to underlying collections.
+
+ public LinkedIdentityHashSet() {
+ this.delegate = new ElementAwareList<>();
+ this.identityMap = new IdentityHashMap<>();
+ }
+
+ @Override
+ public Iterator<V> iterator() {
+ return delegate.iterator();
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ if (size == 0) { // Micro-optimization; contains() on an empty map is not entirely free.
+ return false;
+ }
+ return identityMap.containsKey(o);
+ }
+
+ @Override
+ public boolean add(V v) {
+ var entry = identityMap.get(v);
+ if (entry == null) {
+ identityMap.put(v, delegate.add(v));
+ size += 1;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ if (size == 0) { // Micro-optimization; remove() on an empty map is not entirely free.
+ return false;
+ }
+ var entry = identityMap.remove(o);
+ if (entry == null) {
+ return false;
+ } | contains+remove is worse than just remove, if you don't need to support null keys. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -0,0 +1,77 @@
+package ai.timefold.solver.core.impl.util;
+
+import java.util.AbstractSet;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+
+import org.jspecify.annotations.NullMarked;
+
+/**
+ * This set does not support null keys.
+ *
+ * @param <V>
+ */
+@NullMarked
+public final class LinkedIdentityHashSet<V> extends AbstractSet<V> {
+
+ private final ElementAwareList<V> delegate;
+ private final IdentityHashMap<V, ElementAwareListEntry<V>> identityMap;
+ private int size = 0; // Avoid method calls to underlying collections.
+
+ public LinkedIdentityHashSet() {
+ this.delegate = new ElementAwareList<>();
+ this.identityMap = new IdentityHashMap<>();
+ }
+
+ @Override
+ public Iterator<V> iterator() {
+ return delegate.iterator();
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ if (size == 0) { // Micro-optimization; contains() on an empty map is not entirely free.
+ return false;
+ }
+ return identityMap.containsKey(o);
+ }
+
+ @Override
+ public boolean add(V v) {
+ var entry = identityMap.get(v);
+ if (entry == null) {
+ identityMap.put(v, delegate.add(v));
+ size += 1;
+ return true;
+ } | computeIfAbsent does the same thing, but it also forces the JVM to create a lambda instance. This does not. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -155,9 +155,18 @@ public void forEach(Consumer<? super T> tupleConsumer) {
*/
@Override
public Iterator<T> iterator() {
+ if (size == 0) {
+ return Collections.emptyIterator(); | Reduces allocations in some pathological cases. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -25,38 +28,51 @@
import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.util.LinkedIdentityHashSet;
+
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
/**
* This class is not thread-safe.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
+@NullMarked
public final class VariableListenerSupport<Solution_> implements SupplyManager {
+ private static final int SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3;
+
public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDirector<Solution_, ?> scoreDirector) {
return new VariableListenerSupport<>(scoreDirector, new NotifiableRegistry<>(scoreDirector.getSolutionDescriptor()));
}
- private static final int SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3;
private final InnerScoreDirector<Solution_, ?> scoreDirector;
private final NotifiableRegistry<Solution_> notifiableRegistry;
private final Map<Demand<?>, SupplyWithDemandCount> supplyMap = new HashMap<>();
- private final List<ListVariableEvent> listVariableEventList;
- private final ListVariableDescriptor<Solution_> listVariableDescriptor;
+ private final @Nullable ListVariableDescriptor<Solution_> listVariableDescriptor;
+ private final List<ListVariableChangedNotification<Solution_>> listVariableChangedNotificationList;
+ private final Set<Object> unassignedValueWithEmptyInverseEntitySet;
private final List<CascadingUpdateShadowVariableDescriptor<Solution_>> cascadingUpdateShadowVarDescriptorList;
private boolean notificationQueuesAreEmpty = true;
private int nextGlobalOrder = 0;
VariableListenerSupport(InnerScoreDirector<Solution_, ?> scoreDirector, NotifiableRegistry<Solution_> notifiableRegistry) {
- this.scoreDirector = scoreDirector;
- this.notifiableRegistry = notifiableRegistry;
- this.cascadingUpdateShadowVarDescriptorList = scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream()
- .flatMap(e -> e.getDeclaredCascadingUpdateShadowVariableDescriptors().stream())
- .toList();
+ this.scoreDirector = Objects.requireNonNull(scoreDirector);
+ this.notifiableRegistry = Objects.requireNonNull(notifiableRegistry);
+
+ // Fields specific to list variable; will be ignored if not necessary.
this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getListVariableDescriptor();
- this.listVariableEventList = new ArrayList<>();
+ this.cascadingUpdateShadowVarDescriptorList =
+ listVariableDescriptor != null ? scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream()
+ .flatMap(e -> e.getDeclaredCascadingUpdateShadowVariableDescriptors().stream())
+ .toList() : Collections.emptyList();
+ var hasCascadingUpdates = !cascadingUpdateShadowVarDescriptorList.isEmpty();
+ this.listVariableChangedNotificationList = hasCascadingUpdates ? new ArrayList<>() : Collections.emptyList();
+ this.unassignedValueWithEmptyInverseEntitySet =
+ hasCascadingUpdates ? new LinkedIdentityHashSet<>() : Collections.emptySet(); | Don't create what doesn't need creating. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -215,14 +233,17 @@ public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescript
}
public void afterElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
- Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor);
+ var notifiables = notifiableRegistry.get(variableDescriptor);
if (!notifiables.isEmpty()) {
ListVariableNotification<Solution_> notification = Notification.elementUnassigned(element);
for (var notifiable : notifiables) {
notifiable.notifyAfter(notification);
}
notificationQueuesAreEmpty = false;
}
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade.
+ unassignedValueWithEmptyInverseEntitySet.add(element);
+ } | Don't use what doesn't need using. |
timefold-solver | github_2023 | java | 1,480 | TimefoldAI | triceo | @@ -240,61 +261,83 @@ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variable
public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
int toIndex) {
var notifiables = notifiableRegistry.get(variableDescriptor);
+ var notification = Notification.<Solution_> listVariableChanged(entity, fromIndex, toIndex);
if (!notifiables.isEmpty()) {
- ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex);
for (var notifiable : notifiables) {
notifiable.notifyAfter(notification);
}
notificationQueuesAreEmpty = false;
}
- listVariableEventList.add(new ListVariableEvent(entity, fromIndex, toIndex));
+ if (!cascadingUpdateShadowVarDescriptorList.isEmpty()) { // Only necessary if there is a cascade.
+ listVariableChangedNotificationList.add(notification);
+ } | No need to create the event if we already have the notification.
Help the GC do less work, help yourself. |
timefold-solver | github_2023 | java | 1,479 | TimefoldAI | triceo | @@ -15,7 +17,14 @@ FeatureBuildItem feature() {
}
@BuildStep
- void registerTimefoldJacksonModule(BuildProducer<AdditionalBeanBuildItem> additionalBeans) {
+ ClassPathJacksonModuleBuildItem registerTimefoldJacksonModule() {
+ // Make timefold-solver-jackson discoverable by quarkus-rest
+ // https://quarkus.io/guides/rest-migration#service-loading
+ return new ClassPathJacksonModuleBuildItem(TimefoldJacksonModule.class.getName());
+ }
+
+ @BuildStep
+ void registerTimefoldObjectMapperCustomizer(BuildProducer<AdditionalBeanBuildItem> additionalBeans) { | I'm good with removing this. |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,87 @@
+from timefold.solver.score import *
+from datetime import time
+from typing import Final | Unused import
```suggestion
``` |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,255 @@
+import json
+from itertools import count
+from random import Random
+from datetime import datetime, time, timedelta
+from typing import List, Callable, TypeVar
+
+from .domain import *
+
+random = Random(0)
+T = TypeVar('T')
+L = TypeVar('L')
+
+# Constants for employee skills
+ATTENDANT_SKILL = "Flight attendant"
+PILOT_SKILL = "Pilot"
+
+# First names and last names
+FIRST_NAMES = ["Amy", "Beth", "Carl", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay",
+ "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose",
+ "Dena", "Jana", "Dave", "Russ", "Josh", "Dana", "Katy"]
+
+LAST_NAMES = ["Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe",
+ "Lowe", "Wise", "Clay", "Carr", "Hood", "Long", "Horn", "Haas", "Meza"]
+
+
+def generate_demo_data() -> FlightCrewSchedule:
+ # Airports
+ airports = [
+ Airport(code="LHR",name="LHR", latitude=51.4775, longitude=-0.461389),
+ Airport(code="JFK", name="JFK", latitude=40.639722, longitude=-73.778889),
+ Airport(code="CNF", name="CNF", latitude=-19.624444, longitude=-43.971944),
+ Airport(code="BRU", name="BRU", latitude=50.901389, longitude=4.484444),
+ Airport(code="ATL", name="ATL", latitude=33.636667, longitude=-84.428056),
+ Airport(code="BNE", name="BNE", latitude=-27.383333, longitude=153.118333)
+ ]
+ distances = {
+ "LHR-JFK": 8, "LHR-CNF": 12, "LHR-BRU": 13, "LHR-ATL": 9, "LHR-BNE": 21,
+ "JFK-LHR": 8, "JFK-BRU": 14, "JFK-CNF": 10, "JFK-ATL": 6, "JFK-BNE": 20,
+ "CNF-LHR": 12, "CNF-JFK": 10, "CNF-BRU": 19, "CNF-ATL": 10, "CNF-BNE": 19,
+ "BRU-LHR": 13, "BRU-JFK": 14, "BRU-CNF": 19, "BRU-ATL": 9, "BRU-BNE": 21,
+ "ATL-LHR": 9, "ATL-JFK": 6, "ATL-CNF": 10, "ATL-BRU": 9, "ATL-BNE": 18,
+ "BNE-LHR": 21, "BNE-JFK": 20, "BNE-CNF": 19, "BNE-BRU": 21, "BNE-ATL": 18
+ }
+
+ # Flights
+ first_date = date.today()
+ count_days = 5
+ dates = [first_date + timedelta(days=i) for i in range(count_days)]
+ home_airports = random.sample(airports, 2)
+ times = [time(hour=i, minute=0) for i in range(24)]
+ count_flights = 14
+ flights = generate_flights(count_flights, datetime.now() + timedelta(minutes=1), airports, home_airports, dates,
+ times, distances)
+ # Flight assignments
+ flight_assignments = generate_flight_assignments(flights)
+ # Employees
+ employees = generate_employees(flights, dates)
+
+ # Flight Crew Schedule
+ schedule = FlightCrewSchedule(airports=airports, employees=employees, flights=flights,
+ flight_assignments=flight_assignments, score=None, solver_status=SolverStatus.NOT_SOLVING)
+
+ return schedule
+
+
+def generate_flights(size: int, start_datetime: datetime, airports: List[Airport],
+ home_airports: List[Airport], dates: List[datetime.date],
+ time_groups: List[datetime.time], distances: Dict[str, int]) -> List[Flight]:
+ if size % 2 != 0:
+ raise ValueError("The size of flights must be even")
+
+ # Departure and arrival airports
+ flights = []
+ remaining_airports = [airport for airport in airports if airport not in home_airports]
+ count_flights = 0
+
+ while count_flights < size:
+ route_size = pick_random_route_size(count_flights, size)
+ home_airport = random.choice(home_airports)
+ home_flight = Flight(flight_number=str(count_flights), departure_airport=home_airport, arrival_airport=random.choice(remaining_airports))
+ flights.append(home_flight)
+ count_flights += 1
+
+ next_flight = home_flight
+ for _ in range(route_size - 2):
+ next_flight = Flight(
+ flight_number=str(count_flights),
+ departure_airport=next_flight.arrival_airport,
+ arrival_airport=pick_random_airport(remaining_airports, next_flight.arrival_airport.code)
+ )
+ flights.append(next_flight)
+ count_flights += 1
+
+ flights.append(Flight(flight_number=str(count_flights), departure_airport=next_flight.arrival_airport, arrival_airport=home_flight.departure_airport))
+ count_flights += 1
+
+ # Assign flight numbers
+ for i, flight in enumerate(flights):
+ flight.flight_number = f"Flight {i + 1}"
+
+ # Assign flight durations
+ count_dates = size // len(dates)
+
+ def flight_consumer(f: Flight, d: date):
+ key = f"{f.departure_airport.code}-{f.arrival_airport.code}"
+ count_hours = distances[key]
+ start_time = random.choice(time_groups)
+ departure_datetime = datetime.combine(d, start_time)
+
+ if departure_datetime < start_datetime:
+ departure_datetime = start_datetime + timedelta(hours=random.randint(0, 4))
+
+ arrival_datetime = departure_datetime + timedelta(hours=count_hours)
+ f.departure_utc_date_time = departure_datetime
+ f.arrival_utc_date_time = arrival_datetime
+
+ apply_random_value_with_param(count_dates, flights, random.choice(dates),
+ lambda f: f.departure_utc_date_time is None, flight_consumer) | I personally find this hard to read/reason about. I recommend using a for loop instead:
```suggestion
for start_date in dates:
apply_random_value(count_dates, flights, lambda f: f.departure_utc_date_time is None, lambda f: flight_consumer(f, start_date))
``` |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,255 @@
+import json
+from itertools import count
+from random import Random
+from datetime import datetime, time, timedelta
+from typing import List, Callable, TypeVar
+
+from .domain import *
+
+random = Random(0)
+T = TypeVar('T')
+L = TypeVar('L')
+
+# Constants for employee skills
+ATTENDANT_SKILL = "Flight attendant"
+PILOT_SKILL = "Pilot"
+
+# First names and last names
+FIRST_NAMES = ["Amy", "Beth", "Carl", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay",
+ "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose",
+ "Dena", "Jana", "Dave", "Russ", "Josh", "Dana", "Katy"]
+
+LAST_NAMES = ["Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe",
+ "Lowe", "Wise", "Clay", "Carr", "Hood", "Long", "Horn", "Haas", "Meza"]
+
+
+def generate_demo_data() -> FlightCrewSchedule:
+ # Airports
+ airports = [
+ Airport(code="LHR",name="LHR", latitude=51.4775, longitude=-0.461389),
+ Airport(code="JFK", name="JFK", latitude=40.639722, longitude=-73.778889),
+ Airport(code="CNF", name="CNF", latitude=-19.624444, longitude=-43.971944),
+ Airport(code="BRU", name="BRU", latitude=50.901389, longitude=4.484444),
+ Airport(code="ATL", name="ATL", latitude=33.636667, longitude=-84.428056),
+ Airport(code="BNE", name="BNE", latitude=-27.383333, longitude=153.118333)
+ ]
+ distances = {
+ "LHR-JFK": 8, "LHR-CNF": 12, "LHR-BRU": 13, "LHR-ATL": 9, "LHR-BNE": 21,
+ "JFK-LHR": 8, "JFK-BRU": 14, "JFK-CNF": 10, "JFK-ATL": 6, "JFK-BNE": 20,
+ "CNF-LHR": 12, "CNF-JFK": 10, "CNF-BRU": 19, "CNF-ATL": 10, "CNF-BNE": 19,
+ "BRU-LHR": 13, "BRU-JFK": 14, "BRU-CNF": 19, "BRU-ATL": 9, "BRU-BNE": 21,
+ "ATL-LHR": 9, "ATL-JFK": 6, "ATL-CNF": 10, "ATL-BRU": 9, "ATL-BNE": 18,
+ "BNE-LHR": 21, "BNE-JFK": 20, "BNE-CNF": 19, "BNE-BRU": 21, "BNE-ATL": 18
+ }
+
+ # Flights
+ first_date = date.today()
+ count_days = 5
+ dates = [first_date + timedelta(days=i) for i in range(count_days)]
+ home_airports = random.sample(airports, 2)
+ times = [time(hour=i, minute=0) for i in range(24)]
+ count_flights = 14
+ flights = generate_flights(count_flights, datetime.now() + timedelta(minutes=1), airports, home_airports, dates,
+ times, distances)
+ # Flight assignments
+ flight_assignments = generate_flight_assignments(flights)
+ # Employees
+ employees = generate_employees(flights, dates)
+
+ # Flight Crew Schedule
+ schedule = FlightCrewSchedule(airports=airports, employees=employees, flights=flights,
+ flight_assignments=flight_assignments, score=None, solver_status=SolverStatus.NOT_SOLVING)
+
+ return schedule
+
+
+def generate_flights(size: int, start_datetime: datetime, airports: List[Airport],
+ home_airports: List[Airport], dates: List[datetime.date],
+ time_groups: List[datetime.time], distances: Dict[str, int]) -> List[Flight]:
+ if size % 2 != 0:
+ raise ValueError("The size of flights must be even")
+
+ # Departure and arrival airports
+ flights = []
+ remaining_airports = [airport for airport in airports if airport not in home_airports]
+ count_flights = 0
+
+ while count_flights < size:
+ route_size = pick_random_route_size(count_flights, size)
+ home_airport = random.choice(home_airports)
+ home_flight = Flight(flight_number=str(count_flights), departure_airport=home_airport, arrival_airport=random.choice(remaining_airports))
+ flights.append(home_flight)
+ count_flights += 1
+
+ next_flight = home_flight
+ for _ in range(route_size - 2):
+ next_flight = Flight(
+ flight_number=str(count_flights),
+ departure_airport=next_flight.arrival_airport,
+ arrival_airport=pick_random_airport(remaining_airports, next_flight.arrival_airport.code)
+ )
+ flights.append(next_flight)
+ count_flights += 1
+
+ flights.append(Flight(flight_number=str(count_flights), departure_airport=next_flight.arrival_airport, arrival_airport=home_flight.departure_airport))
+ count_flights += 1
+
+ # Assign flight numbers
+ for i, flight in enumerate(flights):
+ flight.flight_number = f"Flight {i + 1}"
+
+ # Assign flight durations
+ count_dates = size // len(dates)
+
+ def flight_consumer(f: Flight, d: date):
+ key = f"{f.departure_airport.code}-{f.arrival_airport.code}"
+ count_hours = distances[key]
+ start_time = random.choice(time_groups)
+ departure_datetime = datetime.combine(d, start_time)
+
+ if departure_datetime < start_datetime:
+ departure_datetime = start_datetime + timedelta(hours=random.randint(0, 4))
+
+ arrival_datetime = departure_datetime + timedelta(hours=count_hours)
+ f.departure_utc_date_time = departure_datetime
+ f.arrival_utc_date_time = arrival_datetime
+
+ apply_random_value_with_param(count_dates, flights, random.choice(dates),
+ lambda f: f.departure_utc_date_time is None, flight_consumer)
+
+ # Ensure no flights are left without assigned dates
+ for flight in flights:
+ if flight.departure_utc_date_time is None:
+ flight_consumer(flight, random.choice(dates))
+
+ return flights
+
+
+def generate_employees(flights: List[Flight], dates: List[date]) -> List[Employee]:
+ name_supplier = lambda: f"{random.choice(FIRST_NAMES)} {random.choice(LAST_NAMES)}"
+
+ # Get distinct departure airports from flights
+ flight_airports = list({flight.departure_airport for flight in flights})
+
+ # Two pilots and three attendants per airport
+ employees = []
+ counter = 0
+
+ for airport in flight_airports:
+ for _ in range(2): # Two teams per airport
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
+
+ if airport.code == "CNF":
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[])) | The walrus `x := y` operator can be confusing and not usually encountered. I recommend importing [itertools.count](https://docs.python.org/3/library/itertools.html#itertools.count) and using it as an id generator
```suggestion
ids = map(str, itertools.count())
for airport in flight_airports:
for _ in range(2): # Two teams per airport
employees.append(Employee(id=next(ids) name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
employees.append(Employee(id=next(ids), name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
employees.append(Employee(id=next(ids), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
employees.append(Employee(id=next(ids), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
if airport.code == "CNF":
employees.append(Employee(id=next(ids), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
``` |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,255 @@
+import json
+from itertools import count
+from random import Random
+from datetime import datetime, time, timedelta
+from typing import List, Callable, TypeVar
+
+from .domain import *
+
+random = Random(0)
+T = TypeVar('T')
+L = TypeVar('L')
+
+# Constants for employee skills
+ATTENDANT_SKILL = "Flight attendant"
+PILOT_SKILL = "Pilot"
+
+# First names and last names
+FIRST_NAMES = ["Amy", "Beth", "Carl", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay",
+ "Jeri", "Hope", "Avis", "Lino", "Lyle", "Nick", "Dino", "Otha", "Gwen", "Jose",
+ "Dena", "Jana", "Dave", "Russ", "Josh", "Dana", "Katy"]
+
+LAST_NAMES = ["Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt", "Howe",
+ "Lowe", "Wise", "Clay", "Carr", "Hood", "Long", "Horn", "Haas", "Meza"]
+
+
+def generate_demo_data() -> FlightCrewSchedule:
+ # Airports
+ airports = [
+ Airport(code="LHR",name="LHR", latitude=51.4775, longitude=-0.461389),
+ Airport(code="JFK", name="JFK", latitude=40.639722, longitude=-73.778889),
+ Airport(code="CNF", name="CNF", latitude=-19.624444, longitude=-43.971944),
+ Airport(code="BRU", name="BRU", latitude=50.901389, longitude=4.484444),
+ Airport(code="ATL", name="ATL", latitude=33.636667, longitude=-84.428056),
+ Airport(code="BNE", name="BNE", latitude=-27.383333, longitude=153.118333)
+ ]
+ distances = {
+ "LHR-JFK": 8, "LHR-CNF": 12, "LHR-BRU": 13, "LHR-ATL": 9, "LHR-BNE": 21,
+ "JFK-LHR": 8, "JFK-BRU": 14, "JFK-CNF": 10, "JFK-ATL": 6, "JFK-BNE": 20,
+ "CNF-LHR": 12, "CNF-JFK": 10, "CNF-BRU": 19, "CNF-ATL": 10, "CNF-BNE": 19,
+ "BRU-LHR": 13, "BRU-JFK": 14, "BRU-CNF": 19, "BRU-ATL": 9, "BRU-BNE": 21,
+ "ATL-LHR": 9, "ATL-JFK": 6, "ATL-CNF": 10, "ATL-BRU": 9, "ATL-BNE": 18,
+ "BNE-LHR": 21, "BNE-JFK": 20, "BNE-CNF": 19, "BNE-BRU": 21, "BNE-ATL": 18
+ }
+
+ # Flights
+ first_date = date.today()
+ count_days = 5
+ dates = [first_date + timedelta(days=i) for i in range(count_days)]
+ home_airports = random.sample(airports, 2)
+ times = [time(hour=i, minute=0) for i in range(24)]
+ count_flights = 14
+ flights = generate_flights(count_flights, datetime.now() + timedelta(minutes=1), airports, home_airports, dates,
+ times, distances)
+ # Flight assignments
+ flight_assignments = generate_flight_assignments(flights)
+ # Employees
+ employees = generate_employees(flights, dates)
+
+ # Flight Crew Schedule
+ schedule = FlightCrewSchedule(airports=airports, employees=employees, flights=flights,
+ flight_assignments=flight_assignments, score=None, solver_status=SolverStatus.NOT_SOLVING)
+
+ return schedule
+
+
+def generate_flights(size: int, start_datetime: datetime, airports: List[Airport],
+ home_airports: List[Airport], dates: List[datetime.date],
+ time_groups: List[datetime.time], distances: Dict[str, int]) -> List[Flight]:
+ if size % 2 != 0:
+ raise ValueError("The size of flights must be even")
+
+ # Departure and arrival airports
+ flights = []
+ remaining_airports = [airport for airport in airports if airport not in home_airports]
+ count_flights = 0
+
+ while count_flights < size:
+ route_size = pick_random_route_size(count_flights, size)
+ home_airport = random.choice(home_airports)
+ home_flight = Flight(flight_number=str(count_flights), departure_airport=home_airport, arrival_airport=random.choice(remaining_airports))
+ flights.append(home_flight)
+ count_flights += 1
+
+ next_flight = home_flight
+ for _ in range(route_size - 2):
+ next_flight = Flight(
+ flight_number=str(count_flights),
+ departure_airport=next_flight.arrival_airport,
+ arrival_airport=pick_random_airport(remaining_airports, next_flight.arrival_airport.code)
+ )
+ flights.append(next_flight)
+ count_flights += 1
+
+ flights.append(Flight(flight_number=str(count_flights), departure_airport=next_flight.arrival_airport, arrival_airport=home_flight.departure_airport))
+ count_flights += 1
+
+ # Assign flight numbers
+ for i, flight in enumerate(flights):
+ flight.flight_number = f"Flight {i + 1}"
+
+ # Assign flight durations
+ count_dates = size // len(dates)
+
+ def flight_consumer(f: Flight, d: date):
+ key = f"{f.departure_airport.code}-{f.arrival_airport.code}"
+ count_hours = distances[key]
+ start_time = random.choice(time_groups)
+ departure_datetime = datetime.combine(d, start_time)
+
+ if departure_datetime < start_datetime:
+ departure_datetime = start_datetime + timedelta(hours=random.randint(0, 4))
+
+ arrival_datetime = departure_datetime + timedelta(hours=count_hours)
+ f.departure_utc_date_time = departure_datetime
+ f.arrival_utc_date_time = arrival_datetime
+
+ apply_random_value_with_param(count_dates, flights, random.choice(dates),
+ lambda f: f.departure_utc_date_time is None, flight_consumer)
+
+ # Ensure no flights are left without assigned dates
+ for flight in flights:
+ if flight.departure_utc_date_time is None:
+ flight_consumer(flight, random.choice(dates))
+
+ return flights
+
+
+def generate_employees(flights: List[Flight], dates: List[date]) -> List[Employee]:
+ name_supplier = lambda: f"{random.choice(FIRST_NAMES)} {random.choice(LAST_NAMES)}"
+
+ # Get distinct departure airports from flights
+ flight_airports = list({flight.departure_airport for flight in flights})
+
+ # Two pilots and three attendants per airport
+ employees = []
+ counter = 0
+
+ for airport in flight_airports:
+ for _ in range(2): # Two teams per airport
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[PILOT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
+
+ if airport.code == "CNF":
+ employees.append(Employee(id=str(counter := counter + 1), name=name_supplier(), home_airport=airport, skills=[ATTENDANT_SKILL], unavailable_days=[]))
+
+ # Assign unavailable dates: 28% for one date, 4% for two dates
+ apply_random_value(
+ int(0.28 * len(employees)),
+ employees,
+ lambda e: not e.unavailable_days,
+ lambda e: setattr(e, 'unavailable_days', [random.choice(dates)])
+ )
+
+ apply_random_value(
+ int(0.04 * len(employees)),
+ employees,
+ lambda e: not e.unavailable_days,
+ lambda e: setattr(e, 'unavailable_days', random.sample(dates, 2))
+ )
+
+ return employees
+
+
+def pick_random_airport(airports: List[Airport], exclude_code: str) -> Airport:
+ airport = None
+ while airport is None or airport.code == exclude_code:
+ airport = random.choice(airports)
+ return airport
+
+def pick_random_route_size(count_flights: int, max_count_flights: int) -> int:
+ allowed_sizes = [2, 4, 6]
+ limit = max_count_flights - count_flights
+ route_size = 0
+ while route_size == 0 or route_size > limit:
+ route_size = random.choice(allowed_sizes)
+ return route_size
+
+
+def generate_flight_assignments(flights: List[Flight]) -> List[FlightAssignment]:
+ # 2 pilots and 2 or 3 attendants
+ flight_assignments = []
+ id_counter = count(1)
+
+ for flight in flights:
+ index_skill = count(1)
+
+ flight_assignments.append(FlightAssignment(
+ id=str(next(id_counter)),
+ flight=flight,
+ index_in_flight=next(index_skill),
+ required_skill=PILOT_SKILL
+ ))
+
+ flight_assignments.append(FlightAssignment(
+ id=str(next(id_counter)),
+ flight=flight,
+ index_in_flight=next(index_skill),
+ required_skill=PILOT_SKILL
+ ))
+
+ flight_assignments.append(FlightAssignment(
+ id=str(next(id_counter)),
+ flight=flight,
+ index_in_flight=next(index_skill),
+ required_skill=ATTENDANT_SKILL
+ ))
+
+ flight_assignments.append(FlightAssignment(
+ id=str(next(id_counter)),
+ flight=flight,
+ index_in_flight=next(index_skill),
+ required_skill=ATTENDANT_SKILL
+ ))
+
+ if flight.departure_airport.code == "CNF" or flight.arrival_airport.code == "CNF":
+ flight_assignments.append(FlightAssignment(
+ id=str(next(id_counter)),
+ flight=flight,
+ index_in_flight=next(index_skill),
+ required_skill=ATTENDANT_SKILL
+ ))
+
+ return flight_assignments
+
+
+def apply_random_value(counter: int, values: List[T], filter_func: Callable[[T], bool],
+ consumer: Callable[[T], None]) -> None:
+ filtered_values = [v for v in values if filter_func(v)]
+ size = len(filtered_values)
+
+ for _ in range(counter):
+ if size <= 0:
+ break
+ selected_item = random.choice(filtered_values) if size > 0 else None
+ if selected_item:
+ consumer(selected_item)
+ filtered_values.remove(selected_item)
+ size -= 1
+
+
+def apply_random_value_with_param(count: int, values: List[T], second_param: L, filter_func: Callable[[T], bool],
+ consumer: Callable[[T, L], None]) -> None:
+ filtered_values = [v for v in values if filter_func(v)]
+ size = len(filtered_values)
+
+ for _ in range(count):
+ if size <= 0:
+ break
+ selected_item = random.choice(filtered_values) if size > 0 else None
+ if selected_item:
+ consumer(selected_item, second_param)
+ filtered_values.remove(selected_item)
+ size -= 1 | Can be removed if my suggestion above is applied.
```suggestion
``` |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,177 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+from .json_serialization import *
+from datetime import date, timedelta, datetime
+
+
+class Airport(JsonDomainBase):
+ code: Annotated[str, PlanningId]
+ name: str
+ latitude: Annotated[float, Field(default=0.0)]
+ longitude: Annotated[float, Field(default=0.0)]
+ taxi_time_in_minutes: Annotated[Dict[str, int] | None,
+ TaxiTimeValidator,
+ Field(default_factory=dict)]
+
+
+ def __str__(self) -> str:
+ return self.name
+
+ def __repr__(self) -> str:
+ return (f"Airport(code={self.code}, name={self.name}, latitude={self.latitude}, longitude={self.longitude},"
+ f" taxi_time_in_minutes={self.taxi_time_in_minutes})")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Airport):
+ return False
+ return self.code == other.code
+
+ def __hash__(self) -> int:
+ return hash(self.code)
+
+ def __lt__(self, other: "Airport") -> bool:
+ return self.code < other.code
+
+ def __gt__(self, other: "Airport") -> bool:
+ return self.code > other.code | Not needed; if `__gt__` is not defined, `__lt__` will be used.
```suggestion
``` |
timefold-quickstarts | github_2023 | python | 703 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,177 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+from .json_serialization import *
+from datetime import date, timedelta, datetime
+
+
+class Airport(JsonDomainBase):
+ code: Annotated[str, PlanningId]
+ name: str
+ latitude: Annotated[float, Field(default=0.0)]
+ longitude: Annotated[float, Field(default=0.0)]
+ taxi_time_in_minutes: Annotated[Dict[str, int] | None,
+ TaxiTimeValidator,
+ Field(default_factory=dict)]
+
+
+ def __str__(self) -> str:
+ return self.name
+
+ def __repr__(self) -> str:
+ return (f"Airport(code={self.code}, name={self.name}, latitude={self.latitude}, longitude={self.longitude},"
+ f" taxi_time_in_minutes={self.taxi_time_in_minutes})")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Airport):
+ return False
+ return self.code == other.code
+
+ def __hash__(self) -> int:
+ return hash(self.code)
+
+ def __lt__(self, other: "Airport") -> bool:
+ return self.code < other.code
+
+ def __gt__(self, other: "Airport") -> bool:
+ return self.code > other.code
+
+
+class Employee(JsonDomainBase):
+ id: Annotated[str, PlanningId]
+ name: str
+ home_airport: Annotated[Airport | None, IdSerializer, AirportDeserializer, Field(default=None)]
+ skills: Annotated[List[str], Field(default_factory=list)]
+ unavailable_days: Annotated[List[date], Field(default_factory=list)]
+
+
+ def has_skill(self, skill: str) -> bool:
+ """Checks if the employee has a specific skill."""
+ return skill in self.skills
+
+ def is_available(self, from_date_inclusive: date, to_date_inclusive: date) -> bool:
+ """Checks if the employee is available between two dates."""
+ if len(self.unavailable_days) == 0:
+ return True
+ current_date = from_date_inclusive
+ while current_date <= to_date_inclusive:
+ if current_date in self.unavailable_days:
+ return False
+ current_date += timedelta(days=1)
+ return True
+
+ def __str__(self) -> str:
+ return self.name
+
+ def __repr__(self) -> str:
+ return (f"Employee(id={self.id}, name={self.name}, home_airport={self.home_airport}, skills={self.skills},"
+ f" unavailable_days={self.unavailable_days})")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Employee):
+ return False
+ return self.id == other.id
+
+ def __hash__(self) -> int:
+ return hash(self.id)
+
+
+class Flight(JsonDomainBase):
+ flight_number: Annotated[str, PlanningId]
+ departure_airport: Annotated[Airport | None, IdSerializer, AirportDeserializer, Field(default=None)]
+ departure_utc_date_time: Annotated[datetime | None, Field(default=None, alias="departureUTCDateTime")]
+ arrival_airport: Annotated[Airport | None, IdSerializer, AirportDeserializer, Field(default=None)]
+ arrival_utc_date_time: Annotated[datetime | None, Field(default=None, alias="arrivalUTCDateTime")]
+
+
+ def get_departure_utc_date(self) -> date:
+ """Retrieve flight's departure date."""
+ return self.departure_utc_date_time.date()
+
+ def __str__(self) -> str:
+ return f"{self.flight_number}@{self.get_departure_utc_date()}"
+
+ def __repr__(self) -> str:
+ return (f"Flight(flight_number={self.flight_number}, departure_airport={self.departure_airport}, departure_utc_date_time={self.departure_utc_date_time},"
+ f" arrival_airport={self.arrival_airport}, arrival_utc_date_time{self.arrival_utc_date_time})")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Flight):
+ return False
+ return self.flight_number == other.flight_number
+
+ def __hash__(self) -> int:
+ return hash(self.flight_number)
+
+ def __lt__(self, other: "Flight") -> bool:
+ if self.departure_utc_date_time != other.departure_utc_date_time:
+ return self.departure_utc_date_time < other.departure_utc_date_time
+ if self.departure_airport != other.departure_airport:
+ return self.departure_airport < other.departure_airport
+ if self.arrival_utc_date_time != other.arrival_utc_date_time:
+ return self.arrival_utc_date_time < other.arrival_utc_date_time
+ if self.arrival_airport != other.arrival_airport:
+ return self.arrival_airport < other.arrival_airport
+ return self.flight_number < other.flight_number | Tuple comparison logic can simplify this:
```suggestion
def _comparison_key(self):
return (departure_utc_date_time, departure_airport, arrival_utc_date_time, arrival_airport, flight_number)
def __lt__(self, other: "Flight") -> bool:
return self._comparison_key() < other._comparison_key()
``` |
timefold-quickstarts | github_2023 | python | 694 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,61 @@
+from timefold.solver.score import *
+from datetime import time
+from typing import Final
+
+from .domain import *
+from .score_analysis import LoadBalanceJustification
+
+
+@constraint_provider
+def define_constraints(constraint_factory: ConstraintFactory):
+ return [
+ one_assignment_per_date_per_team(constraint_factory),
+ unavailability_penalty(constraint_factory),
+ fair_assignment_count_per_team(constraint_factory),
+ evenly_confrontation_count(constraint_factory)
+ | Extra line
```suggestion
``` |
timefold-quickstarts | github_2023 | python | 694 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,97 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore, PlanningPin)
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Day(JsonDomainBase):
+ date_index: int
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Day):
+ return False
+ return self.date_index == other.date_index
+
+ def __hash__(self):
+ return 31 * self.date_index
+
+
+class Team(JsonDomainBase):
+ id: Annotated[int, PlanningId]
+ name: Annotated[str, Field(default=None)]
+
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Team):
+ return False
+ return self.id == other.id
+
+ def __hash__(self):
+ return 31 * hash(self.id)
+
+ def __str__(self):
+ return self.name if self.name is not None else super().__str__()
+
+ def __repr__(self):
+ return f'Team({self.id}, {self.name})'
+
+
+class UnavailabilityPenalty(JsonDomainBase):
+ team: Annotated[Team | None,
+ IdSerializer,
+ TeamDeserializer,
+ Field(default=None)]
+ day: Annotated[Day | None,
+ IdSerializer,
+ DayDeserializer,
+ Field(default=None)]
+
+
+@planning_entity
+class TeamAssignment(JsonDomainBase):
+ id: Annotated[int, PlanningId]
+ day: Annotated[Day | None,
+ IdSerializer,
+ DayDeserializer,
+ Field(default=None)]
+ index_in_day: int
+ pinned: Annotated[bool, PlanningPin] | I would make this default to `False` (in Java, all `boolean` values are initialized to `false` even if they don't appear in a constructor and don't have a field initializer.
```suggestion
pinned: Annotated[bool, PlanningPin, Field(default=False)]
``` |
timefold-quickstarts | github_2023 | python | 694 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,68 @@
+from timefold.solver.test import ConstraintVerifier
+from tournament_scheduling.domain import *
+from tournament_scheduling.constraints import *
+
+constraint_verifier = ConstraintVerifier.build(define_constraints, TournamentSchedule, TeamAssignment)
+# Sample teams and days (equivalent to static variables in Java)
+DAY0 = Day(date_index=0)
+DAY1 = Day(date_index=1)
+DAY2 = Day(date_index=2)
+TEAM0 = Team(id=0, name="A")
+TEAM1 = Team(id=1, name="B")
+TEAM2 = Team(id=2, name="C")
+
+def test_one_assignment_per_day_per_team():
+ assignment1 = TeamAssignment(id=0, day=DAY0, index_in_day=0, pinned=False, team=TEAM0) | If you make `pinned` default to `False`, you won't need to specify it on all these objects (applies to the whole file). |
timefold-quickstarts | github_2023 | python | 694 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,68 @@
+from timefold.solver.test import ConstraintVerifier
+from tournament_scheduling.domain import *
+from tournament_scheduling.constraints import *
+
+constraint_verifier = ConstraintVerifier.build(define_constraints, TournamentSchedule, TeamAssignment)
+# Sample teams and days (equivalent to static variables in Java) | I don't think the latter part of the comment is helpful. It would only confuse a Python developer looking at it.
I would remove this comment, since it is obvious this is sample data (and there no such comment in Java).
```suggestion
``` |
timefold-quickstarts | github_2023 | others | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,159 @@
+<!DOCTYPE>
+<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>Sports League Scheduling - Timefold Solver on Python</title> | ```suggestion
<title>Sports League Scheduling - Timefold Solver for Python</title>
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,155 @@
+from timefold.solver.score import *
+from datetime import time
+from typing import Final
+
+from .domain import *
+
+
+MAX_CONSECUTIVE_MATCHES: Final[int] = 4
+
+
+@constraint_provider
+def define_constraints(constraint_factory: ConstraintFactory):
+ return [
+ matches_on_same_day(constraint_factory),
+ multiple_consecutive_home_matches(constraint_factory),
+ multiple_consecutive_away_matches(constraint_factory),
+ repeat_match_on_the_next_day(constraint_factory),
+ start_to_away_hop(constraint_factory),
+ home_to_away_hop(constraint_factory),
+ away_to_away_hop(constraint_factory),
+ away_to_home_hop(constraint_factory),
+ away_to_end_hop(constraint_factory),
+ classic_matches(constraint_factory)
+ ]
+
+
+def matches_on_same_day(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each_unique_pair(Match,
+ Joiners.equal(lambda match: match.round.index),
+ Joiners.filtering(are_teams_overlapping))
+ .penalize(HardSoftScore.ONE_HARD)
+ .as_constraint("Matches on the same day"))
+
+def are_teams_overlapping(match1 : Match, match2:Match) -> bool:
+ return (match1.home_team == match2.home_team or match1.home_team == match2.away_team
+ or match1.away_team == match2.home_team or match1.away_team == match2.away_team)
+
+
+def multiple_consecutive_home_matches(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Team,
+ Joiners.equal(lambda match: match.home_team, lambda team: team))
+ .group_by(lambda match, team: team,
+ ConstraintCollectors.to_consecutive_sequences(lambda match, team: match.round,
+ lambda match_round: match_round.index))
+ .flatten_last(lambda sequences: sequences.getConsecutiveSequences())
+ .filter(lambda team, matches: matches.getCount() >= MAX_CONSECUTIVE_MATCHES)
+ .penalize(HardSoftScore.ONE_HARD, lambda team, matches: matches.getCount())
+ .as_constraint("4 or more consecutive home matches"))
+
+
+def multiple_consecutive_away_matches(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Team,
+ Joiners.equal(lambda match: match.away_team, lambda team: team))
+ .group_by(lambda match, team: team,
+ ConstraintCollectors.to_consecutive_sequences(lambda match, team: match.round,
+ lambda match_round: match_round.index))
+ .flatten_last(lambda sequences: sequences.getConsecutiveSequences())
+ .filter(lambda team, matches: matches.getCount() >= MAX_CONSECUTIVE_MATCHES)
+ .penalize(HardSoftScore.ONE_HARD, lambda team, matches: matches.getCount())
+ .as_constraint("4 or more consecutive away matches"))
+
+
+def repeat_match_on_the_next_day(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .if_exists(Match,
+ Joiners.equal(lambda match: match.home_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_HARD)
+ .as_constraint("Repeat match on the next day"))
+
+
+def start_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .if_not_exists(Round, Joiners.equal(lambda match: match.round.index - 1,
+ lambda match_round: match_round.index))
+ .penalize(HardSoftScore.ONE_SOFT, away_home_match_distance_lambda)
+ .as_constraint("Start to away hop"))
+
+
+def home_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.home_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .as_constraint("Home to away hop"))
+
+
+def away_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.away_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .as_constraint("Away to away hop"))
+
+
+def away_to_home_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_away_matches_distance_lambda)
+ .as_constraint("Away to home hop"))
+
+home_away_match_distance_lambda = lambda match: ( | The `if isinstance(match.home_team, Team) and isinstance(match.away_team, Team) else 0` should be unnecessary; all matches home and away teams should be set.
It might be best to add a method to Team `get_distance(self, team: Team)` to perform the lookup logic. |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,155 @@
+from timefold.solver.score import *
+from datetime import time
+from typing import Final
+
+from .domain import *
+
+
+MAX_CONSECUTIVE_MATCHES: Final[int] = 4
+
+
+@constraint_provider
+def define_constraints(constraint_factory: ConstraintFactory):
+ return [
+ matches_on_same_day(constraint_factory),
+ multiple_consecutive_home_matches(constraint_factory),
+ multiple_consecutive_away_matches(constraint_factory),
+ repeat_match_on_the_next_day(constraint_factory),
+ start_to_away_hop(constraint_factory),
+ home_to_away_hop(constraint_factory),
+ away_to_away_hop(constraint_factory),
+ away_to_home_hop(constraint_factory),
+ away_to_end_hop(constraint_factory),
+ classic_matches(constraint_factory)
+ ]
+
+
+def matches_on_same_day(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each_unique_pair(Match,
+ Joiners.equal(lambda match: match.round.index),
+ Joiners.filtering(are_teams_overlapping))
+ .penalize(HardSoftScore.ONE_HARD)
+ .as_constraint("Matches on the same day"))
+
+def are_teams_overlapping(match1 : Match, match2:Match) -> bool:
+ return (match1.home_team == match2.home_team or match1.home_team == match2.away_team
+ or match1.away_team == match2.home_team or match1.away_team == match2.away_team)
+
+
+def multiple_consecutive_home_matches(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Team,
+ Joiners.equal(lambda match: match.home_team, lambda team: team))
+ .group_by(lambda match, team: team,
+ ConstraintCollectors.to_consecutive_sequences(lambda match, team: match.round,
+ lambda match_round: match_round.index))
+ .flatten_last(lambda sequences: sequences.getConsecutiveSequences())
+ .filter(lambda team, matches: matches.getCount() >= MAX_CONSECUTIVE_MATCHES)
+ .penalize(HardSoftScore.ONE_HARD, lambda team, matches: matches.getCount())
+ .as_constraint("4 or more consecutive home matches"))
+
+
+def multiple_consecutive_away_matches(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Team,
+ Joiners.equal(lambda match: match.away_team, lambda team: team))
+ .group_by(lambda match, team: team,
+ ConstraintCollectors.to_consecutive_sequences(lambda match, team: match.round,
+ lambda match_round: match_round.index))
+ .flatten_last(lambda sequences: sequences.getConsecutiveSequences())
+ .filter(lambda team, matches: matches.getCount() >= MAX_CONSECUTIVE_MATCHES)
+ .penalize(HardSoftScore.ONE_HARD, lambda team, matches: matches.getCount())
+ .as_constraint("4 or more consecutive away matches"))
+
+
+def repeat_match_on_the_next_day(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .if_exists(Match,
+ Joiners.equal(lambda match: match.home_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_HARD)
+ .as_constraint("Repeat match on the next day"))
+
+
+def start_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .if_not_exists(Round, Joiners.equal(lambda match: match.round.index - 1,
+ lambda match_round: match_round.index))
+ .penalize(HardSoftScore.ONE_SOFT, away_home_match_distance_lambda)
+ .as_constraint("Start to away hop"))
+
+
+def home_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.home_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .as_constraint("Home to away hop"))
+
+
+def away_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.away_team, lambda match: match.away_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .as_constraint("Away to away hop"))
+
+
+def away_to_home_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .join(Match,
+ Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
+ Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_away_matches_distance_lambda)
+ .as_constraint("Away to home hop"))
+
+home_away_match_distance_lambda = lambda match: (
+ match.home_team.distance_to_team.get(match.away_team.id, 0)
+ if isinstance(match.home_team, Team) and isinstance(match.away_team, Team) else 0
+)
+
+
+away_home_match_distance_lambda = lambda match: (
+ match.away_team.distance_to_team.get(match.home_team.id, 0)
+ if isinstance(match.away_team, Team) and isinstance(match.home_team, Team) else 0
+)
+
+home_away_matches_distance_lambda = lambda match, other_match: (
+ match.home_team.distance_to_team.get(match.away_team.id, 0)
+ if isinstance(match.home_team, Team) and isinstance(match.away_team, Team) else 0
+)
+
+home_matches_distance_lambda = lambda match, other_match: (
+ match.home_team.distance_to_team.get(other_match.home_team.id, 0)
+ if isinstance(match.home_team, Team) and isinstance(other_match.home_team, Team) else 0
+)
+
+def away_to_end_hop(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .if_not_exists(Round, Joiners.equal(lambda match: match.round.index + 1,
+ lambda match_round: match_round.index))
+ .penalize(HardSoftScore.ONE_SOFT, home_away_match_distance_lambda)
+ .as_constraint("Away to end hop"))
+
+
+def classic_matches(constraint_factory: ConstraintFactory) -> Constraint:
+ return (constraint_factory
+ .for_each(Match)
+ .filter(is_invalid_classic_match) | I would inline `is_invalid_classic_match` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,126 @@
+import json
+import random | To prevent accidentally using a shared random, only import the `Random` class from the package.
```suggestion
from random import Random
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,126 @@
+import json
+import random
+from datetime import datetime, time, timedelta
+from typing import List, Callable
+
+from .domain import *
+
+ | You should create a seeded random so the generated demo data is consistent.
```suggestion
random = Random(0)
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,126 @@
+import json
+import random
+from datetime import datetime, time, timedelta
+from typing import List, Callable
+
+from .domain import *
+
+
+DISTANCE_IN_KM = [
+ [0, 2163, 2163, 2160, 2156, 2156, 2163, 340, 1342, 512, 3038, 1526, 2054, 2054],
+ [2163, 0, 11, 50, 813, 813, 11, 1967, 842, 1661, 1139, 1037, 202, 202],
+ [2163, 11, 0, 50, 813, 813, 11, 1967, 842, 1661, 1139, 1037, 202, 202],
+ [2160, 50, 50, 0, 862, 862, 50, 1957, 831, 1655, 1180, 1068, 161, 161],
+ [2160, 813, 813, 862, 0, 1, 813, 2083, 1160, 1741, 910, 644, 600, 600],
+ [2160, 813, 813, 862, 1, 0, 813, 2083, 1160, 1741, 910, 644, 600, 600],
+ [2163, 11, 11, 50, 813, 813, 0, 1967, 842, 1661, 1139, 1037, 202, 202],
+ [340, 1967, 1967, 1957, 2083, 2083, 1967, 0, 1126, 341, 2926, 1490, 1836, 1836],
+ [1342, 842, 842, 831, 1160, 1160, 842, 1126, 0, 831, 1874, 820, 714, 714],
+ [512, 1661, 1661, 1655, 1741, 1741, 1661, 341, 831, 0, 2589, 1151, 1545, 1545],
+ [3038, 1139, 1139, 1180, 910, 910, 1139, 2926, 1874, 2589, 0, 1552, 1340, 1340],
+ [1526, 1037, 1037, 1068, 644, 644, 1037, 1490, 820, 1151, 1552, 0, 1077, 1077],
+ [2054, 202, 202, 161, 600, 600, 202, 1836, 714, 1545, 1340, 1077, 0, 14],
+ [2054, 202, 202, 161, 600, 600, 202, 1836, 714, 1545, 1340, 1077, 14, 0],
+]
+
+
+def id_generator():
+ current = 0
+ while True:
+ yield str(current)
+ current += 1
+
+
+def generate_rounds(count_rounds : int) -> List[Round]:
+ today = datetime.now()
+ rounds = [Round(index=i, weekend_or_holiday=False) for i in range(count_rounds)]
+
+ # Mark weekend rounds as important
+ for round_obj in rounds:
+ future_date = today + timedelta(days=round_obj.index)
+ if future_date.weekday() in (5, 6): # Saturday or Sunday
+ round_obj.weekend_or_holiday = True
+
+ return rounds
+
+
+def generate_teams() -> List[Team]:
+ team_names = [
+ "Cruzeiro", "Argentinos Jr.", "Boca Juniors", "Estudiantes", "Independente",
+ "Racing", "River Plate", "Flamengo", "Gremio", "Santos",
+ "Colo-Colo", "Olimpia", "Nacional", "Penharol"
+ ]
+
+ teams = [Team(id=str(i + 1), name=name, distance_to_team={}) for i, name in enumerate(team_names)]
+
+ # Assign distances
+ for i, team in enumerate(teams):
+ team.distance_to_team = {
+ teams[j].id: DISTANCE_IN_KM[i][j]
+ for j in range(len(teams))
+ if i != j
+ }
+
+ return teams
+
+def generate_matches(teams: List[Team]) -> List[Match]:
+ reciprocal_match = None
+ matches = [
+ Match(id=f'{team1.id}-{team2.id}', home_team=team1, away_team=team2, classic_match=False, round=None)
+ for team1 in teams
+ for team2 in teams
+ if team1 != team2
+ ]
+
+ # 5% classic matches
+ apply_random_value(
+ count=int(len(matches) * 0.05),
+ values = matches,
+ filter_func = lambda match_league: not match_league.classic_match,
+ consumer_func = lambda match_league: setattr(match_league, 'classic_match', True)
+ )
+
+ # Ensure reciprocity for classic matches
+ for match in matches:
+ if match.classic_match:
+ reciprocal_match = next((m for m in matches if m.home_team == match.away_team and m.away_team == match.home_team), None)
+ if reciprocal_match:
+ reciprocal_match.classic_match = True
+
+ return matches
+
+
+def apply_random_value(count: int, values: List, filter_func: Callable, consumer_func: Callable) -> None:
+ filtered_values = [value for value in values if filter_func(value)]
+ size = len(filtered_values)
+
+ for _ in range(count):
+ if size > 0:
+ selected_value = random.choice(filtered_values)
+ consumer_func(selected_value)
+ filtered_values.remove(selected_value)
+ size -= 1
+ else:
+ break
+
+
+def generate_demo_data_test() -> LeagueSchedule: | I would rename this to just `generate_demo_data`
```suggestion
def generate_demo_data() -> LeagueSchedule:
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,113 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Team(JsonDomainBase):
+ id: str
+ name: str
+ distance_to_team: Annotated[Dict[str, int],
+ DistanceToTeamValidator,
+ Field(default_factory=dict)]
+
+
+ def __eq__(self, other):
+ if self is other: # Check if both references are the same
+ return True
+ if not isinstance(other, Team): # Ensure the other object is a Team instance
+ return False
+ return self.id == other.id # Compare IDs for equality
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __str__(self):
+ return self.id
+
+ def __repr__(self):
+ return f'Team({self.id}, {self.name}, {self.distance_to_team})'
+
+
+class Round(JsonDomainBase):
+ index: Annotated[int, PlanningId]
+ # Rounds scheduled on weekends and holidays. It's common for classic matches to be scheduled on weekends or holidays.
+ weekend_or_holiday: bool
+
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Round):
+ return False
+ return self.index == other.index
+
+ def __hash__(self):
+ return 31 * self.index
+
+ def __str__(self):
+ return f'Round-{self.index}'
+
+ def __repr__(self):
+ return f'Round({self.index}, {self.weekendOrHoliday})'
+
+
+@planning_entity
+class Match(JsonDomainBase):
+ id: Annotated[str, PlanningId]
+ home_team: Annotated[Team | None, | The home and away teams should always be set. Also remove the `Field(default=None)`.
```suggestion
home_team: Annotated[Team,
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,113 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Team(JsonDomainBase):
+ id: str
+ name: str
+ distance_to_team: Annotated[Dict[str, int],
+ DistanceToTeamValidator,
+ Field(default_factory=dict)]
+
+
+ def __eq__(self, other):
+ if self is other: # Check if both references are the same
+ return True
+ if not isinstance(other, Team): # Ensure the other object is a Team instance
+ return False
+ return self.id == other.id # Compare IDs for equality
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __str__(self):
+ return self.id
+
+ def __repr__(self):
+ return f'Team({self.id}, {self.name}, {self.distance_to_team})'
+
+
+class Round(JsonDomainBase):
+ index: Annotated[int, PlanningId]
+ # Rounds scheduled on weekends and holidays. It's common for classic matches to be scheduled on weekends or holidays.
+ weekend_or_holiday: bool
+
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Round):
+ return False
+ return self.index == other.index
+
+ def __hash__(self):
+ return 31 * self.index
+
+ def __str__(self):
+ return f'Round-{self.index}'
+
+ def __repr__(self):
+ return f'Round({self.index}, {self.weekendOrHoliday})'
+
+
+@planning_entity
+class Match(JsonDomainBase):
+ id: Annotated[str, PlanningId]
+ home_team: Annotated[Team | None,
+ IdStrSerializer,
+ TeamDeserializer,
+ Field(default=None)]
+ away_team: Annotated[Team | None, | ```suggestion
away_team: Annotated[Team,
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,113 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Team(JsonDomainBase):
+ id: str
+ name: str
+ distance_to_team: Annotated[Dict[str, int],
+ DistanceToTeamValidator,
+ Field(default_factory=dict)]
+ | I would add a `get_distance(self, team: Team)` method here. |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,113 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Team(JsonDomainBase):
+ id: str
+ name: str
+ distance_to_team: Annotated[Dict[str, int],
+ DistanceToTeamValidator,
+ Field(default_factory=dict)]
+
+
+ def __eq__(self, other):
+ if self is other: # Check if both references are the same
+ return True
+ if not isinstance(other, Team): # Ensure the other object is a Team instance
+ return False
+ return self.id == other.id # Compare IDs for equality
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __str__(self):
+ return self.id
+
+ def __repr__(self):
+ return f'Team({self.id}, {self.name}, {self.distance_to_team})'
+
+
+class Round(JsonDomainBase):
+ index: Annotated[int, PlanningId]
+ # Rounds scheduled on weekends and holidays. It's common for classic matches to be scheduled on weekends or holidays.
+ weekend_or_holiday: bool
+
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Round):
+ return False
+ return self.index == other.index
+
+ def __hash__(self):
+ return 31 * self.index
+
+ def __str__(self):
+ return f'Round-{self.index}'
+
+ def __repr__(self):
+ return f'Round({self.index}, {self.weekendOrHoliday})'
+
+
+@planning_entity
+class Match(JsonDomainBase):
+ id: Annotated[str, PlanningId]
+ home_team: Annotated[Team | None,
+ IdStrSerializer,
+ TeamDeserializer,
+ Field(default=None)]
+ away_team: Annotated[Team | None,
+ IdStrSerializer,
+ TeamDeserializer,
+ Field(default=None)]
+ # A classic/important match can impact aspects like revenue (e.g., derby)
+ classic_match: Annotated[bool, Field(default=False)]
+ round: Annotated[Round | None,
+ PlanningVariable,
+ IdIntSerializer,
+ RoundDeserializer,
+ Field(default=None)]
+
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ if not isinstance(other, Match):
+ return False
+ return self.id == other.id
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __str__(self):
+ return f'{self.home_team} + {self.away_team}'
+
+ def __repr__(self):
+ return f'Match({self.id}, {self.home_team}, {self.away_team}, {self.classic_match})'
+
+
+@planning_solution
+class LeagueSchedule(JsonDomainBase):
+ id: str
+ rounds: Annotated[list[Round],
+ ProblemFactCollectionProperty,
+ ValueRangeProvider]
+ teams: Annotated[list[Team],
+ ProblemFactCollectionProperty,
+ ValueRangeProvider]
+ matches: Annotated[list[Match],
+ PlanningEntityCollectionProperty] | Slightly unaligned.
```suggestion
PlanningEntityCollectionProperty]
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,113 @@
+from timefold.solver import SolverStatus
+from timefold.solver.domain import (planning_entity, planning_solution, PlanningId, PlanningVariable,
+ PlanningEntityCollectionProperty,
+ ProblemFactCollectionProperty, ValueRangeProvider,
+ PlanningScore)
+from timefold.solver.score import HardSoftScore
+from typing import Dict, List, Any, Annotated
+
+from .json_serialization import *
+
+
+class Team(JsonDomainBase):
+ id: str
+ name: str
+ distance_to_team: Annotated[Dict[str, int],
+ DistanceToTeamValidator,
+ Field(default_factory=dict)]
+
+
+ def __eq__(self, other):
+ if self is other: # Check if both references are the same
+ return True
+ if not isinstance(other, Team): # Ensure the other object is a Team instance
+ return False
+ return self.id == other.id # Compare IDs for equality
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __str__(self):
+ return self.id
+
+ def __repr__(self):
+ return f'Team({self.id}, {self.name}, {self.distance_to_team})'
+
+
+class Round(JsonDomainBase):
+ index: Annotated[int, PlanningId]
+ # Rounds scheduled on weekends and holidays. It's common for classic matches to be scheduled on weekends or holidays.
+ weekend_or_holiday: bool | I would annotate this attribute with `Field(default=False)` so you wouldn't need to specify it every time in the test.
```suggestion
weekend_or_holiday: Annotated[bool, Field(default=False)]
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,165 @@
+from timefold.solver.test import ConstraintVerifier
+
+from sports_league_scheduling.domain import *
+from sports_league_scheduling.constraints import *
+
+constraint_verifier = ConstraintVerifier.build(define_constraints, LeagueSchedule, Match)
+
+
+def test_matches_same_day():
+ # Two matches for the home team
+ home_team = Team(id="1", name="TeamA", distance_to_team={})
+ rival_team = Team(id="2", name="TeamB", distance_to_team={})
+ match1 = Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+ match2 = Match(id="2", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+ match3 = Match(id="3", home_team=home_team, away_team=rival_team, round=None, classic_match=False) | `round=None` and `classic_match=False` are the defaults for `Match` and do not need to be specified
(applies to the whole file wherever `classic_match=False` or `round=None`).
```suggestion
match3 = Match(id="3", home_team=home_team, away_team=rival_team)
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,165 @@
+from timefold.solver.test import ConstraintVerifier
+
+from sports_league_scheduling.domain import *
+from sports_league_scheduling.constraints import *
+
+constraint_verifier = ConstraintVerifier.build(define_constraints, LeagueSchedule, Match)
+
+
+def test_matches_same_day():
+ # Two matches for the home team
+ home_team = Team(id="1", name="TeamA", distance_to_team={})
+ rival_team = Team(id="2", name="TeamB", distance_to_team={})
+ match1 = Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+ match2 = Match(id="2", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+ match3 = Match(id="3", home_team=home_team, away_team=rival_team, round=None, classic_match=False)
+
+ constraint_verifier.verify_that(matches_on_same_day).given(match1, match2, match3).penalizes_by(1)
+
+ # Two matches, one for home and another for away match
+ other_team = Team(id="3", name="TeamC", distance_to_team={})
+ match1 = Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+ match2 = Match(id="2", home_team=rival_team, away_team=other_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False)
+
+ constraint_verifier.verify_that(matches_on_same_day).given(match1, match2, match3).penalizes_by(1)
+
+
+def test_multiple_consecutive_home_matches():
+ home_team = Team(id="1", name="TeamA", distance_to_team={})
+ rival_team = Team(id="2", name="TeamB", distance_to_team={})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=home_team, away_team=rival_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="3", home_team=home_team, away_team=rival_team, round=Round(index=2, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="4", home_team=home_team, away_team=rival_team, round=Round(index=3, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="5", home_team=Team(id="3", name="TeamC", distance_to_team={}), away_team=home_team, round=None,
+ classic_match=False)
+ ]
+ # four consecutive home matches for homeTeam
+ constraint_verifier.verify_that(multiple_consecutive_home_matches).given(*matches, home_team, rival_team).penalizes_by(4)
+
+
+def test_multiple_consecutive_away_matches():
+ home_team = Team(id="1", name="TeamA", distance_to_team={})
+ rival_team = Team(id="2", name="TeamB", distance_to_team={})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=home_team, away_team=rival_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="3", home_team=home_team, away_team=rival_team, round=Round(index=2, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="4", home_team=home_team, away_team=rival_team, round=Round(index=3, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="5", home_team=Team(id="3", name="TeamC", distance_to_team={}), away_team=home_team, round=None,
+ classic_match=False)
+ ]
+ # four consecutive away matches for homeTeam
+ constraint_verifier.verify_that(multiple_consecutive_away_matches).given(*matches, home_team, rival_team).penalizes_by(4)
+
+
+def test_repeat_match_on_next_day():
+ home_team = Team(id="1", name="TeamA", distance_to_team={})
+ rival_team = Team(id="2", name="TeamB", distance_to_team={})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=rival_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=rival_team, away_team=home_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="3", home_team=home_team, away_team=rival_team, round=Round(index=4, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="4", home_team=rival_team, away_team=home_team, round=Round(index=6, weekend_or_holiday=False),
+ classic_match=False)
+ ]
+ # one match repeating on the next day
+ constraint_verifier.verify_that(repeat_match_on_the_next_day).given(*matches).penalizes_by(1)
+
+
+def test_start_to_away_hop():
+ home_team = Team(id="1", name="TeamA", distance_to_team={"2": 5})
+ second_team = Team(id="2", name="TeamB", distance_to_team={"1": 5})
+ third_team = Team(id="3", name="TeamC", distance_to_team={})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=second_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=home_team, away_team=third_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False),
+ ]
+ # match with the second team
+ constraint_verifier.verify_that(start_to_away_hop).given(*matches).penalizes_by(5)
+
+
+def test_home_to_away_hop():
+ home_team = Team(id="1", name="TeamA", distance_to_team={"3": 7})
+ second_team = Team(id="2", name="TeamB", distance_to_team={})
+ third_team = Team(id="3", name="TeamC", distance_to_team={"1": 7})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=second_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=third_team, away_team=home_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False)
+ ]
+ # match with the home team
+ constraint_verifier.verify_that(home_to_away_hop).given(*matches).penalizes_by(7)
+
+
+def test_away_to_away_hop():
+ second_team = Team(id="2", name="TeamB", distance_to_team={"3": 2})
+ third_team = Team(id="3", name="TeamC", distance_to_team={"2": 2})
+ matches = [
+ Match(id="1", home_team=second_team, away_team=Team(id="1", name="TeamA", distance_to_team={}),
+ round=Round(index=0, weekend_or_holiday=False),classic_match=False),
+ Match(id="2", home_team=third_team, away_team=Team(id="1", name="TeamA", distance_to_team={}),
+ round=Round(index=1, weekend_or_holiday=False),classic_match=False)
+ ]
+ # match with the home team
+ constraint_verifier.verify_that(away_to_away_hop).given(*matches).penalizes_by(2)
+
+
+def test_away_to_home_hop():
+ home_team = Team(id="1",name="TeamA", distance_to_team={"2": 20})
+ second_team = Team(id="2", name="TeamB", distance_to_team={"1": 20})
+ matches = [
+ Match(id="1", home_team=second_team, away_team=home_team, round=Round(index=0, weekend_or_holiday=False),
+ classic_match=False),
+ Match(id="2", home_team=home_team, away_team=Team(id="3", name="TeamC", distance_to_team={}),
+ round=Round(index=1, weekend_or_holiday=False),classic_match=False)
+ ]
+ # match with the home team
+ constraint_verifier.verify_that(away_to_home_hop).given(*matches).penalizes_by(20)
+
+
+def test_away_to_end_hop():
+ home_team = Team(id="1", name="TeamA", distance_to_team={"3": 15})
+ third_team = Team(id="3", name="TeamC", distance_to_team={"1": 15})
+ matches = [
+ Match(id="1", home_team=home_team, away_team=Team(id="2", name="TeamB", distance_to_team={}),
+ round=Round(index=0, weekend_or_holiday=False),classic_match=False),
+ Match(id="2", home_team=third_team, away_team=home_team, round=Round(index=1, weekend_or_holiday=False),
+ classic_match=False)
+ ]
+ # match with the home team
+ constraint_verifier.verify_that(away_to_end_hop).given(*matches).penalizes_by(15)
+
+
+def test_classic_matches():
+ home_team = Team(id="1", name="TeamA", distance_to_team={}) | Don't need to specify `distance_to_team` if you are not populating it (it will create an empty dict using the default factory)
(applies to the whole file wherever `distance_to_team={}` is used).
```suggestion
home_team = Team(id="1", name="TeamA")
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -81,7 +81,7 @@ def start_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
.for_each(Match)
.if_not_exists(Round, Joiners.equal(lambda match: match.round.index - 1,
lambda match_round: match_round.index))
- .penalize(HardSoftScore.ONE_SOFT, away_home_match_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match: (match.away_team.get_distance(match.home_team))) | Parenthesis uneccessary
```suggestion
.penalize(HardSoftScore.ONE_SOFT, lambda match: match.away_team.get_distance(match.home_team))
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -91,7 +91,7 @@ def home_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
.join(Match,
Joiners.equal(lambda match: match.home_team, lambda match: match.away_team),
Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
- .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: (match.home_team.get_distance(other_match.home_team))) | ```suggestion
.penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: match.home_team.get_distance(other_match.home_team))
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -101,7 +101,7 @@ def away_to_away_hop(constraint_factory: ConstraintFactory) -> Constraint:
.join(Match,
Joiners.equal(lambda match: match.away_team, lambda match: match.away_team),
Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
- .penalize(HardSoftScore.ONE_SOFT, home_matches_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: (match.home_team.get_distance(other_match.home_team))) | ```suggestion
.penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: match.home_team.get_distance(other_match.home_team))
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -111,45 +111,22 @@ def away_to_home_hop(constraint_factory: ConstraintFactory) -> Constraint:
.join(Match,
Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
- .penalize(HardSoftScore.ONE_SOFT, home_away_matches_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: (match.home_team.get_distance(match.away_team))) | ```suggestion
.penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: match.home_team.get_distance(match.away_team))
``` |
timefold-quickstarts | github_2023 | python | 685 | TimefoldAI | Christopher-Chianelli | @@ -111,45 +111,22 @@ def away_to_home_hop(constraint_factory: ConstraintFactory) -> Constraint:
.join(Match,
Joiners.equal(lambda match: match.away_team, lambda match: match.home_team),
Joiners.equal(lambda match: match.round.index + 1, lambda match: match.round.index))
- .penalize(HardSoftScore.ONE_SOFT, home_away_matches_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match, other_match: (match.home_team.get_distance(match.away_team)))
.as_constraint("Away to home hop"))
-home_away_match_distance_lambda = lambda match: (
- match.home_team.distance_to_team.get(match.away_team.id, 0)
- if isinstance(match.home_team, Team) and isinstance(match.away_team, Team) else 0
-)
-
-
-away_home_match_distance_lambda = lambda match: (
- match.away_team.distance_to_team.get(match.home_team.id, 0)
- if isinstance(match.away_team, Team) and isinstance(match.home_team, Team) else 0
-)
-
-home_away_matches_distance_lambda = lambda match, other_match: (
- match.home_team.distance_to_team.get(match.away_team.id, 0)
- if isinstance(match.home_team, Team) and isinstance(match.away_team, Team) else 0
-)
-
-home_matches_distance_lambda = lambda match, other_match: (
- match.home_team.distance_to_team.get(other_match.home_team.id, 0)
- if isinstance(match.home_team, Team) and isinstance(other_match.home_team, Team) else 0
-)
def away_to_end_hop(constraint_factory: ConstraintFactory) -> Constraint:
return (constraint_factory
.for_each(Match)
.if_not_exists(Round, Joiners.equal(lambda match: match.round.index + 1,
lambda match_round: match_round.index))
- .penalize(HardSoftScore.ONE_SOFT, home_away_match_distance_lambda)
+ .penalize(HardSoftScore.ONE_SOFT, lambda match: (match.home_team.get_distance(match.away_team))) | ```suggestion
.penalize(HardSoftScore.ONE_SOFT, lambda match: match.home_team.get_distance(match.away_team))
``` |
timefold-quickstarts | github_2023 | others | 601 | TimefoldAI | triceo | @@ -121,4 +120,28 @@ jobs:
export NEW_PYTHON_VERSION="999-dev0"
.github/scripts/change_versions.sh
git commit -am "build: move back to version $NEW_VERSION"
- git push origin $RELEASE_BRANCH_NAME
\ No newline at end of file
+ git push origin $RELEASE_BRANCH_NAME
+
+ - name: Update release branch
+ working-directory: ./timefold-quickstarts
+ shell: bash
+ run: |
+ java_version=${{ github.event.inputs.javaVersion }}
+ version="${java_version%.*}.x"
+ echo $version
+ exists="$(git branch -a | grep -w $version || true)"
+ echo "branch $exists"
+ if [ -n "$exists" ]; then | Why are we doing this if none of workflows in the other repos had this?
Can't we delete the branch if it exists, like we do everywhere else? For consistency. |
timefold-quickstarts | github_2023 | others | 601 | TimefoldAI | triceo | @@ -1,4 +1,4 @@
-name: Release
+'name: Release | ? |
timefold-quickstarts | github_2023 | others | 553 | TimefoldAI | triceo | @@ -1,11 +1,9 @@
At this point, the release of _Timefold Quickstarts_ is ready to be published.
-- [x] Release branch has been created.
-- [x] Git tag has been published.
-- [ ] Delete the branch `dry_run`.
-- [ ] Create the version branch (e.g., `1.13.x`) from the `stable` one.
+- Release branch has been created.
+- Git tag has been published. | Arguably, this can be removed entirely. It doesn't provide any extra information. |
timefold-quickstarts | github_2023 | others | 536 | TimefoldAI | triceo | @@ -28,6 +28,13 @@ jobs:
java-version: [ 17 ] # Only the first supported LTS; already too many jobs here.
timeout-minutes: 120
steps:
+ # Clone timefold-quickstarts
+ # No need to check for stale repo, as Github merges the main repo into the fork automatically. | Please remove this line (and others like it), we no longer check for stale repo anywhere. |
timefold-quickstarts | github_2023 | java | 536 | TimefoldAI | triceo | @@ -45,7 +45,7 @@ public class Job {
/**
* Start is after cleanup.
*/
- @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableNames = {"line", "previousJob"})
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime")
private LocalDateTime startCleaningDateTime;
@PiggybackShadowVariable(shadowVariableName = "startCleaningDateTime") | Didn't we discuss that _nothing_ is allowed to depend on cascading shadows?
How do piggybacks work, if the shadows are not part of the var listener chain anymore, but instead are processed independently in their own loop? |
timefold-quickstarts | github_2023 | java | 527 | TimefoldAI | triceo | @@ -40,15 +41,19 @@ public class Job {
@NextElementShadowVariable(sourceVariableName = "jobs")
private Job nextJob;
- /** Start is after cleanup. */
- @ShadowVariable(variableListenerClass = StartDateTimeUpdatingVariableListener.class, sourceVariableName = "line")
- @ShadowVariable(variableListenerClass = StartDateTimeUpdatingVariableListener.class, sourceVariableName = "previousJob")
+ /**
+ * Start is after cleanup.
+ */
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "line")
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "previousJob")
private LocalDateTime startCleaningDateTime;
- @PiggybackShadowVariable(shadowVariableName = "startCleaningDateTime")
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "line")
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "previousJob")
private LocalDateTime startProductionDateTime;
- @PiggybackShadowVariable(shadowVariableName = "startCleaningDateTime")
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "line")
+ @CascadingUpdateShadowVariable(targetMethodName = "updateStartCleaningDateTime", sourceVariableName = "previousJob") | Observation: that's a lot of boilerplate. The annotation - 6 times. The name of the method - 6 times. The name of each variable - three times. |
timefold-quickstarts | github_2023 | java | 527 | TimefoldAI | triceo | @@ -1,102 +0,0 @@
-package org.acme.foodpackaging.domain.solver;
-
-import java.time.LocalDateTime;
-import java.util.Objects;
-
-import org.acme.foodpackaging.domain.Job;
-import org.acme.foodpackaging.domain.Line;
-import org.acme.foodpackaging.domain.PackagingSchedule;
-import ai.timefold.solver.core.api.domain.variable.VariableListener;
-import ai.timefold.solver.core.api.score.director.ScoreDirector;
-
-public class StartDateTimeUpdatingVariableListener implements VariableListener<PackagingSchedule, Job> { | Beautiful! |
timefold-quickstarts | github_2023 | python | 528 | TimefoldAI | triceo | @@ -41,3 +42,14 @@ def __post_init__(self):
self.description = (f"Vehicle '{self.vehicle_name}' total travel time is "
f"{self.total_driving_time_seconds // (60 * 60)} hours "
f"{round(self.total_driving_time_seconds / 60)} minutes.")
+
+
+@dataclass
+class ServiceFinishedAfterMaxEndTimeJustification(ConstraintJustification): | We've agreed a while back that we won't be adding justifications to the quickstarts.
Please remove; if the Java quickstart still has them, that's an accident and please remove those too. |
timefold-quickstarts | github_2023 | javascript | 528 | TimefoldAI | triceo | @@ -20,6 +21,37 @@ const visitGroup = L.layerGroup().addTo(map);
const homeLocationGroup = L.layerGroup().addTo(map);
const routeGroup = L.layerGroup().addTo(map);
+/************************************ Time line constants and variable definitions ************************************/
+
+const byVehiclePanel = document.getElementById("byVehiclePanel"); | Please make sure this file is identical to the Java frontend.
(I haven't checked whether it is or not.) |
timefold-quickstarts | github_2023 | javascript | 496 | TimefoldAI | zepfred | @@ -335,8 +335,8 @@ function analyze() {
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);
+ $.each([...score.matchAll(/(-?\d*(\.\d+)?)(hard|medium|soft)/g)], (i, parts) => {
+ components[parts[3]] = parseFloat(parts[1], 10); | Agreed. Let's create a papercut story to ensure consistency between the quickstart modules. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.