An AI constraint solver that optimizes planning and scheduling problems
Project description
Planning optimization made easy.
timefold.ai
Timefold Solver is an AI constraint solver you can use to optimize the Vehicle Routing Problem, Employee Rostering, Maintenance Scheduling, Task Assignment, School Timetabling, Cloud Optimization, Conference Scheduling, Job Shop Scheduling and many more planning problems.
Using Timefold Solver in Python is significantly slower than using Timefold Solver for Java or Kotlin.
Get started with Timefold Solver in Python
Requirements
- Install Python 3.10 or later.
 - Install JDK 17 or later with the environment variable 
JAVA_HOMEconfigured to the JDK installation directory. For example, with Sdkman:$ sdk install java
 
Build from source
- Build the main branch of Timefold Solver from source
 - Install the repo
$ pip install git+https://github.com/TimefoldAI/timefold-solver.git
 
Source code overview
Domain
In Timefold Solver, the domain has three parts:
- Problem Facts, which do not change.
 - Planning Entities, which have one or more planning variables.
 - Planning Solution, which define the facts and entities of the problem.
 
Problem Facts
Problem facts can be any Python class, which are used to describe unchanging facts in your problem:
from dataclasses import dataclass
from datetime import time
@dataclass
class Timeslot:
    id: int
    day_of_week: str
    start_time: time
    end_time: time
Planning Entities
To declare Planning Entities, use the @planning_entity decorator along with annotations:
from dataclasses import dataclass, field
from typing import Annotated
from timefold.solver.domain import planning_entity, PlanningId, PlanningVariable
@planning_entity
@dataclass
class Lesson:
    id: Annotated[int, PlanningId]
    subject: str
    teacher: str
    student_group: str
    timeslot: Annotated[Timeslot, PlanningVariable] = field(default=None)
    room: Annotated[Room, PlanningVariable] = field(default=None)
- 
The
PlanningVariableannotation is used to mark what fields the solver is allowed to change. - 
The
PlanningIdannotation is used to uniquely identify an entity object of a particular class. The same Planning Id can be used on entities of different classes, but the ids of all entities in the same class must be different. 
Planning Solution
To declare the Planning Solution, use the @planning_solution decorator:
from dataclasses import dataclass, field
from typing import Annotated
from timefold.solver.domain import (planning_solution, ProblemFactCollectionProperty, ValueRangeProvider,
                                    PlanningEntityCollectionProperty, PlanningScore)
from timefold.solver.score import HardSoftScore
@planning_solution
@dataclass
class TimeTable:
    timeslots: Annotated[list[Timeslot], ProblemFactCollectionProperty, ValueRangeProvider]
    rooms: Annotated[list[Room], ProblemFactCollectionProperty, ValueRangeProvider]
    lessons: Annotated[list[Lesson], PlanningEntityCollectionProperty]
    score: Annotated[HardSoftScore, PlanningScore] = field(default=None)
- 
The
ValueRangeProviderannotation is used to denote a field that contains possible planning values for aPlanningVariable. - 
The
ProblemFactCollectionannotation is used to denote a field that contains problem facts. This allows these facts to be queried in your constraints. - 
The
PlanningEntityCollectionannotation is used to denote a field that contains planning entities. The planning variables of these entities will be modified during solving. - 
The
PlanningScoreannotation is used to denote the field that holds the score of the current solution. The solver will set this field during solving. 
Constraints
You define your constraints by using the ConstraintFactory:
from domain import Lesson
from timefold.solver.score import (Joiners, HardSoftScore, ConstraintFactory,
                                   Constraint, constraint_provider)
@constraint_provider
def define_constraints(constraint_factory: ConstraintFactory) -> list[Constraint]:
    return [
        # Hard constraints
        room_conflict(constraint_factory),
        # Other constraints here...
    ]
def room_conflict(constraint_factory: ConstraintFactory) -> Constraint:
    # A room can accommodate at most one lesson at the same time.
    return (
        constraint_factory.for_each_unique_pair(Lesson,
                # ... in the same timeslot ...
                Joiners.equal(lambda lesson: lesson.timeslot),
                # ... in the same room ...
                Joiners.equal(lambda lesson: lesson.room))
            .penalize(HardSoftScore.ONE_HARD)
            .as_constraint("Room conflict")
    )
Also see Timefold Solver Documentation on Constraint Streams.
Solve
from timefold.solver import SolverFactory
from timefold.solver.config import SolverConfig, TerminationConfig, ScoreDirectorFactoryConfig, Duration
from constraints import define_constraints
from domain import TimeTable, Lesson, generate_problem
solver_config = SolverConfig(
    solution_class=TimeTable,
    entity_class_list=[Lesson],
    score_director_factory_config=ScoreDirectorFactoryConfig(
        constraint_provider_function=define_constraints
    ),
    termination_config=TerminationConfig(
        spent_limit=Duration(seconds=30)
    )
)
solver = SolverFactory.create(solver_config).build_solver()
solution = solver.solve(generate_problem())
solution will be a TimeTable instance with planning
variables set to the final best solution found.
For a full API spec, visit the Timefold Documentation.
Legal notice
Timefold Solver is a derivative work of OptaPlanner and OptaPy, which includes copyrights of the original creator, Red Hat Inc., affiliates, and contributors, that were all entirely licensed under the Apache-2.0 license. Every source file has been modified.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
    Details for the file timefold-1.24.0b0.tar.gz.
  
File metadata
- Download URL: timefold-1.24.0b0.tar.gz
 - Upload date:
 - Size: 1.8 MB
 - Tags: Source
 - Uploaded using Trusted Publishing? Yes
 - Uploaded via: twine/6.1.0 CPython/3.12.9
 
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 | 
          0d5fb4bb3a2a0b73abe04eaa49779801f0ac844fffed1a89fecfff26e048d1c7
         | 
        |
| MD5 | 
          7d49ce9785b09b3d7634a5d45ffd0c68
         | 
        |
| BLAKE2b-256 | 
          177972b480c8360a4d1fe4bd19877ed69489390f56f908ffefcc09959e161ece
         | 
        
Provenance
    The following attestation bundles were made for timefold-1.24.0b0.tar.gz:
  
      Publisher: 
      
      release.yml on TimefoldAI/timefold-solver
    
  
- 
              Statement:
              
- 
                  Statement type: 
https://in-toto.io/Statement/v1 - 
                  Predicate type: 
https://docs.pypi.org/attestations/publish/v1 - 
                  Subject name: 
timefold-1.24.0b0.tar.gz - 
                  Subject digest: 
0d5fb4bb3a2a0b73abe04eaa49779801f0ac844fffed1a89fecfff26e048d1c7 - Sigstore transparency entry: 267453822
 - Sigstore integration time:
 
- 
                    Permalink: 
                    
TimefoldAI/timefold-solver@7bce5c216bac44f0d08938b6679083d10bcda408 - 
                  Branch / Tag: 
                  
refs/heads/main - Owner: https://github.com/TimefoldAI
 - 
                Access: 
public 
- 
              Token Issuer: 
https://token.actions.githubusercontent.com - 
                Runner Environment: 
self-hosted - 
                Publication workflow:
                
                  
release.yml@7bce5c216bac44f0d08938b6679083d10bcda408 - 
                Trigger Event: 
workflow_dispatch 
 - 
                  Statement type: 
 
File details
    Details for the file timefold-1.24.0b0-py3-none-any.whl.
  
File metadata
- Download URL: timefold-1.24.0b0-py3-none-any.whl
 - Upload date:
 - Size: 21.9 MB
 - Tags: Python 3
 - Uploaded using Trusted Publishing? Yes
 - Uploaded via: twine/6.1.0 CPython/3.12.9
 
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 | 
          e2dde8630e62f5b3718efda2c0b1e88bd2a7e015b82bfcfdd7a4ae72ad87f1e7
         | 
        |
| MD5 | 
          81c9cf0253ebb0d2851b20395b4fc964
         | 
        |
| BLAKE2b-256 | 
          b72eb90d2d525395166db8b1d6ad3ffe0ff84105663c275cc46eee5d59cfc615
         | 
        
Provenance
    The following attestation bundles were made for timefold-1.24.0b0-py3-none-any.whl:
  
      Publisher: 
      
      release.yml on TimefoldAI/timefold-solver
    
  
- 
              Statement:
              
- 
                  Statement type: 
https://in-toto.io/Statement/v1 - 
                  Predicate type: 
https://docs.pypi.org/attestations/publish/v1 - 
                  Subject name: 
timefold-1.24.0b0-py3-none-any.whl - 
                  Subject digest: 
e2dde8630e62f5b3718efda2c0b1e88bd2a7e015b82bfcfdd7a4ae72ad87f1e7 - Sigstore transparency entry: 267453831
 - Sigstore integration time:
 
- 
                    Permalink: 
                    
TimefoldAI/timefold-solver@7bce5c216bac44f0d08938b6679083d10bcda408 - 
                  Branch / Tag: 
                  
refs/heads/main - Owner: https://github.com/TimefoldAI
 - 
                Access: 
public 
- 
              Token Issuer: 
https://token.actions.githubusercontent.com - 
                Runner Environment: 
self-hosted - 
                Publication workflow:
                
                  
release.yml@7bce5c216bac44f0d08938b6679083d10bcda408 - 
                Trigger Event: 
workflow_dispatch 
 - 
                  Statement type: