discrete_optimization.generic_tasks_tools package
Subpackages
- discrete_optimization.generic_tasks_tools.objectives package
- Submodules
- discrete_optimization.generic_tasks_tools.objectives.allocated_tasks module
- discrete_optimization.generic_tasks_tools.objectives.allocation_changes module
AllocationSwitchObjectiveComputerAllocationSwitchObjectiveComputer.base_allocation_solutionAllocationSwitchObjectiveComputer.compute_objective()AllocationSwitchObjectiveComputer.get_objective_name()AllocationSwitchObjectiveComputer.get_switch_off_cost()AllocationSwitchObjectiveComputer.get_switch_on_cost()AllocationSwitchObjectiveComputer.has_switch_off_cost()AllocationSwitchObjectiveComputer.has_switch_on_cost()AllocationSwitchObjectiveComputer.has_switches_cost()AllocationSwitchObjectiveComputer.problemAllocationSwitchObjectiveComputer.set_base_allocation_solution()
- discrete_optimization.generic_tasks_tools.objectives.allocation_cost module
AllocationCostComputerAllocationCostComputerMultimodeAllocationCostComputerMultimode.compute_objective()AllocationCostComputerMultimode.cost_allocation_resource_to_task_mode()AllocationCostComputerMultimode.get_objective_name()AllocationCostComputerMultimode.get_tasks_having_cost()AllocationCostComputerMultimode.has_any_cost_allocation()AllocationCostComputerMultimode.problem
MultimodeAllocationProblem
- discrete_optimization.generic_tasks_tools.objectives.alternative_subproblems module
- discrete_optimization.generic_tasks_tools.objectives.calendar_preempted module
- discrete_optimization.generic_tasks_tools.objectives.cumul_cost module
- discrete_optimization.generic_tasks_tools.objectives.custom module
- discrete_optimization.generic_tasks_tools.objectives.earliness_tardiness module
EarlinessTardinessComputerEarlinessTardinessComputer.compute_aggregated_cost()EarlinessTardinessComputer.compute_earliness_cost()EarlinessTardinessComputer.compute_earliness_end()EarlinessTardinessComputer.compute_earliness_start()EarlinessTardinessComputer.compute_objective()EarlinessTardinessComputer.compute_tardiness_cost()EarlinessTardinessComputer.compute_tardiness_end()EarlinessTardinessComputer.compute_tardiness_start()EarlinessTardinessComputer.detailed_objectives()EarlinessTardinessComputer.get_max_end_for_tardiness()EarlinessTardinessComputer.get_max_start_for_tardiness()EarlinessTardinessComputer.get_min_end_for_earliness()EarlinessTardinessComputer.get_min_start_for_earliness()EarlinessTardinessComputer.get_objective_name()EarlinessTardinessComputer.get_tasks_having_max_end_for_tardiness()EarlinessTardinessComputer.get_tasks_having_max_start_for_tardiness()EarlinessTardinessComputer.get_tasks_having_min_end_for_earliness()EarlinessTardinessComputer.get_tasks_having_min_start_for_earliness()EarlinessTardinessComputer.get_weight_end_for_earliness()EarlinessTardinessComputer.get_weight_end_for_tardiness()EarlinessTardinessComputer.get_weight_start_for_earliness()EarlinessTardinessComputer.get_weight_start_for_tardiness()EarlinessTardinessComputer.problem
OnlyEarlinessComputerOnlyTardinessComputer
- discrete_optimization.generic_tasks_tools.objectives.makespan module
- discrete_optimization.generic_tasks_tools.objectives.mode_cost module
- discrete_optimization.generic_tasks_tools.objectives.objective_computer module
- discrete_optimization.generic_tasks_tools.objectives.resource_levels module
CalendarRenewableResourceLevelObjectiveComputerCalendarRenewableResourceLevelObjectiveComputer.compute_objective()CalendarRenewableResourceLevelObjectiveComputer.get_objective_name()CalendarRenewableResourceLevelObjectiveComputer.get_weight_resource()CalendarRenewableResourceLevelObjectiveComputer.has_any_weight()CalendarRenewableResourceLevelObjectiveComputer.problem
NonRenewableResourceLevelObjectiveComputerNonRenewableResourceLevelObjectiveComputer.compute_objective()NonRenewableResourceLevelObjectiveComputer.get_objective_name()NonRenewableResourceLevelObjectiveComputer.get_weight_resource()NonRenewableResourceLevelObjectiveComputer.has_any_weight()NonRenewableResourceLevelObjectiveComputer.problem
- discrete_optimization.generic_tasks_tools.objectives.routing_costs module
- discrete_optimization.generic_tasks_tools.objectives.schedule_changes module
ScheduleChangesComputerScheduleChangesComputer.base_scheduling_solutionScheduleChangesComputer.compute_any_shift_cost()ScheduleChangesComputer.compute_objective()ScheduleChangesComputer.compute_unit_deviation_cost()ScheduleChangesComputer.cost_any_shift()ScheduleChangesComputer.cost_unit_deviation()ScheduleChangesComputer.get_objective_name()ScheduleChangesComputer.has_any_shift_cost()ScheduleChangesComputer.has_any_unit_deviation_cost()ScheduleChangesComputer.problemScheduleChangesComputer.tasks_with_any_shift_cost()ScheduleChangesComputer.tasks_with_unit_deviation_cost()
- discrete_optimization.generic_tasks_tools.objectives.scheduled_tasks module
- discrete_optimization.generic_tasks_tools.objectives.soft_time_penalty module
- discrete_optimization.generic_tasks_tools.objectives.unary_resource_used module
- discrete_optimization.generic_tasks_tools.objectives.utils module
- discrete_optimization.generic_tasks_tools.objectives.weighted_number_late_tasks module
- discrete_optimization.generic_tasks_tools.objectives.weighted_sum_start_or_end module
- Module contents
- discrete_optimization.generic_tasks_tools.solvers package
- Subpackages
- discrete_optimization.generic_tasks_tools.solvers.base package
- Submodules
- discrete_optimization.generic_tasks_tools.solvers.base.allocation module
- discrete_optimization.generic_tasks_tools.solvers.base.base module
- discrete_optimization.generic_tasks_tools.solvers.base.multimode module
- discrete_optimization.generic_tasks_tools.solvers.base.scheduling module
- Module contents
- discrete_optimization.generic_tasks_tools.solvers.cp package
- discrete_optimization.generic_tasks_tools.solvers.lns package
- discrete_optimization.generic_tasks_tools.solvers.base package
- Submodules
- discrete_optimization.generic_tasks_tools.solvers.cpm module
- Module contents
- Subpackages
- discrete_optimization.generic_tasks_tools.transformations package
- Submodules
- discrete_optimization.generic_tasks_tools.transformations.generic_scheduling_impl module
FromGenericSchedulingImplToGenericSchedulingImplToGenericSchedulingImpl.back_transform_solution()ToGenericSchedulingImpl.forward_transform_solution()ToGenericSchedulingImpl.get_list_objective_computer()ToGenericSchedulingImpl.is_bidirectional()ToGenericSchedulingImpl.transform_problem()ToGenericSchedulingImpl.transform_solution_from_raw_generic_to_specific()
convert_solution_from_specific_to_generic()
- Module contents
Submodules
discrete_optimization.generic_tasks_tools.allocation module
- class discrete_optimization.generic_tasks_tools.allocation.AllocationProblem[source]
Bases:
TasksProblem[Task],Generic[Task,UnaryResource]Base class for allocation problems.
An allocation problems consist in allocating resources to tasks.
- get_same_unary_allocation() list[set[Task]][source]
a element (t1, t2, t3..) of this means corresponds to task for which we want the same resource to be allocated. WARNING: To be overriden if meaningful in the problem :return:
- is_compatible_task_unary_resource(task: Task, unary_resource: UnaryResource) bool[source]
Should return False if the unary_resource can never be allocated to task.
This is only a hint used to reduce the number of variables or constraints generated.
Default to True, to be overriden in subclasses.
- abstract property unary_resources_list: list[UnaryResource]
Available unary resources.
It can correspond to employees (rcpsp-multiskill), teams (workforce-scheduling), or a mix of several types.
- class discrete_optimization.generic_tasks_tools.allocation.AllocationSolution(problem: Problem)[source]
Bases:
TasksSolution[Task],Generic[Task,UnaryResource]Class inherited by a solution for allocation problems.
- check_same_allocation_as_ref(ref: AllocationSolution[Task, UnaryResource], tasks: Iterable[Task] | None = None, unary_resources: Iterable[UnaryResource] | None = None) bool[source]
- compute_nb_allocation_changes(ref: AllocationSolution[Task, UnaryResource], tasks: Iterable[Task] | None = None, unary_resources: Iterable[UnaryResource] | None = None) int[source]
- compute_nb_tasks_allocated() int[source]
Compute number of tasks with at least a resource allocated.
- compute_nb_unary_resources_used() int[source]
Compute number of unary resources allocated to at least one task.
- get_default_tasks_n_unary_resources(tasks: Iterable[Task] | None = None, unary_resources: Iterable[UnaryResource] | None = None) tuple[Iterable[Task], Iterable[UnaryResource]][source]
- abstractmethod is_allocated(task: Task, unary_resource: UnaryResource) bool[source]
Return the usage of the unary resource for the given task.
- Parameters:
task
unary_resource
Returns:
- is_present(task: Task) bool[source]
Tell whether the task is present in the solution.
For allocation problem, default to “at least one unary resource has been allocated to the task”. To be overriden in child classes for problem having tasks present without allocation.
- problem: AllocationProblem[Task, UnaryResource]
- class discrete_optimization.generic_tasks_tools.allocation.MultiModeAllocationSolution(problem: Problem)[source]
Bases:
AllocationSolution[Task,UnaryResource],MultimodeSolution[Task],Generic[Task,UnaryResource]- problem: MultimodeAllocationProblem[Task, UnaryResource]
- class discrete_optimization.generic_tasks_tools.allocation.MultimodeAllocationProblem[source]
Bases:
AllocationProblem[Task,UnaryResource],MultimodeProblem[Task],Generic[Task,UnaryResource]
- class discrete_optimization.generic_tasks_tools.allocation.MultimodeAllocationSolution(problem: Problem)[source]
Bases:
AllocationSolution[Task,UnaryResource],MultimodeSolution[Task]- problem: MultimodeAllocationProblem[Task, UnaryResource]
- class discrete_optimization.generic_tasks_tools.allocation.WithoutAllocationProblem[source]
Bases:
AllocationProblem[Task,None],Generic[Task]Mixin to simplify deriving from GenericSchedulingProblem when no allocation is needed.
- property unary_resources_list: list[None]
Available unary resources.
It can correspond to employees (rcpsp-multiskill), teams (workforce-scheduling), or a mix of several types.
- class discrete_optimization.generic_tasks_tools.allocation.WithoutAllocationSolution(problem: Problem)[source]
Bases:
AllocationSolution[Task,None],Generic[Task]Mixin to simplify deriving from GenericSchedulingSolution when no allocation is needed.
- discrete_optimization.generic_tasks_tools.allocation.get_default_tasks_n_unary_resources(problem: AllocationProblem, tasks: Iterable[Task] | None = None, unary_resources: Iterable[UnaryResource] | None = None) tuple[Iterable[Task], Iterable[UnaryResource]][source]
discrete_optimization.generic_tasks_tools.alternative_subproblems module
- class discrete_optimization.generic_tasks_tools.alternative_subproblems.AlternativeSchedulingProblem[source]
Bases:
MultimodeSchedulingProblem[Task],Generic[Task]- get_alternative_scheduling_subproblem() list[AlternativeSchedulingSubProblem][source]
- class discrete_optimization.generic_tasks_tools.alternative_subproblems.AlternativeSchedulingSolution(problem: Problem)[source]
Bases:
MultimodeSchedulingSolution[Task]- problem: AlternativeSchedulingProblem[Task]
- class discrete_optimization.generic_tasks_tools.alternative_subproblems.AlternativeSchedulingSubProblem(source_task: Hashable = None, sink_task: Hashable = None, graph: networkx.classes.digraph.DiGraph | None = None, is_graph_successors: bool = True, list_paths: list[list[Hashable]] | None = None, is_path_successors: bool = True, nb_path_to_do: int = 1)[source]
Bases:
object- graph: DiGraph | None = None
- has_a_sink: bool
- has_a_source: bool
- is_graph_successors: bool = True
- is_path_successors: bool = True
- list_paths: list[list[Hashable]] | None = None
- nb_path_to_do: int = 1
- sink_task: Hashable = None
- source_task: Hashable = None
discrete_optimization.generic_tasks_tools.base module
- class discrete_optimization.generic_tasks_tools.base.TasksProblem[source]
Bases:
Problem,Generic[Task]Base class for scheduling/allocation problems.
- is_optional(task: Task) bool[source]
Whether a task is optional or not.
It means that the task can be ignored in the solution. If absent of the solution, it can also be removed from the constraints.
Default to no optional task.
- linear_constraints_presence_tasks() list[tuple[list[tuple[Task, int]], int | None, int | None]][source]
- property optional_tasks_list: list[Task]
- abstract property tasks_list: list[Task]
List of all tasks to schedule or allocate to.
- class discrete_optimization.generic_tasks_tools.base.TasksSolution(problem: Problem)[source]
Bases:
Solution,Generic[Task]Base class for scheduling/allocation solutions.
- is_present(task: Task) bool[source]
Tell whether the task is present in the solution.
It can mean several thing: - scheduling problem: start and end of the task are defined - allocation problem: a ressource has been allocated to the task - multimode: a mode has been chosen for the task - or a mix of it
Sometimes a scheduling allocation problem will allow no resource allocation for present task, it has to be defined problem by problem.
For convenience, a default implementation is provided which assumes that all tasks are present. To be overriden in subclasses.
If and only if this method returns False, the mode, start, and end of the task can have the value AbsentValue.ABSENT.
If the method returns False, the task is removed from all constraints during checks.
- problem: TasksProblem[Task]
discrete_optimization.generic_tasks_tools.batching module
Module for batching problems.
Provides mixins for problems where tasks are grouped into batches: - Fixed batching: Batch membership is predetermined (Batch dataclass) - Variable batching: Batch membership is determined by the solution (VariableBatchEntity + BatchingSolution)
Variable batching is useful for: - Single batch processing: Assign jobs to batches on a machine - Multi-machine batching: Assign jobs to batches on multiple machines - Oven scheduling: Group items into batches with compatibility constraints
- class discrete_optimization.generic_tasks_tools.batching.Batch(batch_id: Hashable, tasks: frozenset[Task], max_size: int | None = None, min_size: int | None = None)[source]
Bases:
Generic[Task]Fixed batch with predetermined task membership.
Used for problems where batching decisions are made upfront.
- batch_id: Hashable
- max_size: int | None = None
- min_size: int | None = None
- tasks: frozenset[Task]
- class discrete_optimization.generic_tasks_tools.batching.BatchingProblem[source]
Bases:
TasksProblem[Task],Generic[Task]Mixin for problems with variable batch assignment.
This mixin supports problems where: - Tasks can be assigned to different batches - Batch membership is a decision variable - Constraints apply to batches (size, time windows, resources)
Architecture: Batch entities are the PRIMARY abstraction. Create VariableBatchEntity instances first, then pass them to the problem.
Example
>>> from discrete_optimization.generic_tasks_tools.entities import VariableBatchEntity >>> >>> # 1. Create batch entities FIRST (before problem) >>> batch_entities = [ ... VariableBatchEntity(batch_id=0, candidate_tasks=frozenset(tasks)), ... VariableBatchEntity(batch_id=1, candidate_tasks=frozenset(tasks)), ... VariableBatchEntity(batch_id=2, candidate_tasks=frozenset(tasks)), ... ] >>> >>> # 2. Define problem using entities >>> class MyProblem(BatchingProblem, EntityConstraintsProblem): ... def __init__(self, tasks, batch_entities): ... self._tasks = tasks ... self.batch_entities = batch_entities # Store entities ... ... def get_batch_entities(self): ... return self.batch_entities # Return stored entities ... ... def get_entity_precedence_constraints(self): ... # Use entities directly in constraints ... return { ... self.batch_entities[0]: [self.batch_entities[1]] ... } >>> >>> # 3. Create problem with entities >>> problem = MyProblem(tasks, batch_entities)
- can_batch_together(task1: Task, task2: Task) bool[source]
Check if two tasks are compatible for batching together.
Tasks are incompatible if they cannot be in the same batch due to: - Different attributes (e.g., different product types) - Conflicting resource requirements - Incompatible processing characteristics
- Parameters:
task1 – First task
task2 – Second task
- Returns:
True if tasks can be batched together, False otherwise
Default: All tasks are compatible (can batch together).
Example
>>> # Oven scheduling: only same-attribute tasks can batch >>> def can_batch_together(self, task1, task2): ... return self.get_task_attribute(task1) == self.get_task_attribute(task2) >>> >>> # Size-based compatibility >>> def can_batch_together(self, task1, task2): ... return self.task_sizes[task1] + self.task_sizes[task2] <= self.max_batch_size
- can_be_batched(task: Task) bool[source]
Check if a task CAN be assigned to a batch.
- Parameters:
task – Task to query
- Returns:
True if task can be in a batch, False if it must run individually
Default: All tasks can be batched.
Example
>>> # Large items cannot be batched >>> def can_be_batched(self, task): ... return self.get_task_size(task) <= self.single_task_threshold
- get_batch_attribute(batch_id: Hashable, tasks: frozenset[Task]) Hashable | None[source]
Determine batch attribute based on tasks assigned to it.
Batch attribute is derived from tasks in the batch and affects: - Setup time when switching between batches - Processing time of the batch - Resource consumption
- Parameters:
batch_id – Batch identifier
tasks – Tasks assigned to this batch
- Returns:
Batch attribute, or None if no attribute concept
Default: If all tasks have same attribute, return it; else None.
Example
>>> # Oven: batch inherits common attribute >>> def get_batch_attribute(self, batch_id, tasks): ... if not tasks: ... return None ... attrs = {self.get_task_attribute(t) for t in tasks} ... return attrs.pop() if len(attrs) == 1 else None # All must match
- get_batch_capacity(batch_id: Hashable) int | float | tuple[int | float, ...][source]
Get capacity of a batch for bin packing.
Batch capacity constrains total size of tasks in batch: sum(get_task_size(task) for task in batch) <= get_batch_capacity(batch)
For multi-dimensional sizes (tuples), capacity is also a tuple and constraint applies element-wise.
- Parameters:
batch_id – Batch identifier
- Returns:
Batch capacity (int, float, or tuple for multi-dimensional)
Default: Infinite capacity (no constraint).
Example
>>> # Oven scheduling: machine has capacity >>> def get_batch_capacity(self, batch_id): ... machine_id = self._get_machine_from_batch(batch_id) ... return self.machines_data[machine_id].capacity >>> >>> # Multi-dimensional: (max_weight, max_volume) >>> def get_batch_capacity(self, batch_id): ... return (self.max_weight, self.max_volume)
- get_batch_duration_bounds(batch_id: Hashable, tasks: frozenset[Task]) tuple[int | None, int | None][source]
Get minimum and maximum duration for a batch based on its tasks.
Batch duration depends on tasks assigned to it and batch attribute. This is separate from size bounds (number of tasks).
- Parameters:
batch_id – Batch identifier
tasks – Tasks assigned to this batch
- Returns:
Tuple of (min_duration, max_duration). None means no constraint.
Default: No duration constraints.
Example
>>> # Oven: duration based on task min/max durations >>> def get_batch_duration_bounds(self, batch_id, tasks): ... if not tasks: ... return None, None ... min_dur = max(self.tasks_data[t].min_duration for t in tasks) ... max_dur = min(self.tasks_data[t].max_duration for t in tasks) ... return min_dur, max_dur
- get_batch_entities() list[VariableBatchEntity[Task]][source]
Get all batch entities in the problem.
This is the PRIMARY method - batch entities are created first, before the problem, and stored. This method returns them.
- Returns:
List of VariableBatchEntity instances
Example
>>> def __init__(self, tasks, batch_entities): ... self._tasks = tasks ... self.batch_entities = batch_entities ... >>> def get_batch_entities(self): ... return self.batch_entities
- get_batch_entity(batch_id: Hashable) VariableBatchEntity[Task][source]
Get batch entity for a specific batch_id.
- Parameters:
batch_id – Batch identifier
- Returns:
VariableBatchEntity with matching batch_id
- Raises:
ValueError – If batch_id not found
- get_batch_ids() list[Hashable][source]
Get list of batch IDs (derived from entities).
This is DERIVED from get_batch_entities(). You don’t override this - it extracts batch_id from each entity.
- Returns:
List of batch IDs (batch_id attribute from each entity)
- get_batch_presence_chains() list[list[Hashable]][source]
Get batch presence ordering chains for symmetry breaking.
Returns chains of batches where if batch[i+1] is used, batch[i] must be used. This helps avoid symmetric solutions by enforcing a canonical ordering.
- Returns:
List of batch chains. Each chain is a list of batch IDs in order. Empty list means no presence constraints (all batches independent).
- Example - Single machine (one chain):
>>> def get_batch_presence_chains(self): ... return [self.get_batch_ids()] # All batches in one chain
- Example - Multi-machine (multiple chains):
>>> def get_batch_presence_chains(self): ... # Batches 0-4 for machine 1, batches 5-9 for machine 2 ... return [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
- Example - No presence constraints:
>>> def get_batch_presence_chains(self): ... return [] # Batches can be used in any order
- get_batch_size_bounds(batch_id: Hashable) tuple[int | None, int | None][source]
Get minimum and maximum NUMBER OF TASKS in a batch.
This is about cardinality (count), not weight/capacity. For capacity constraints, use get_task_size() and get_batch_capacity().
- Parameters:
batch_id – Batch identifier
- Returns:
Tuple of (min_size, max_size). None means no constraint.
Default: No size constraints.
- get_batching_task_categories() dict[str, list[Task]][source]
Categorize tasks based on batching requirements.
- Returns:
‘mandatory’: Tasks that MUST be batched (must_be_batched() = True)
’optional’: Tasks that CAN be batched but don’t have to (can_be_batched() = True, must_be_batched() = False)
’forbidden’: Tasks that CANNOT be batched (can_be_batched() = False)
- Return type:
Dictionary with three keys
Note: Tasks with must_be_batched() = True and can_be_batched() = False are invalid and will raise a ValueError.
Example
>>> categories = problem.get_batching_task_categories() >>> print(f"Must batch: {categories['mandatory']}") >>> print(f"Can batch: {categories['optional']}") >>> print(f"Cannot batch: {categories['forbidden']}")
- get_candidate_tasks_for_batch(batch_id: Hashable) frozenset[Task][source]
Get tasks that could potentially be assigned to this batch.
- Parameters:
batch_id – Batch identifier
- Returns:
Set of tasks that are candidates for this batch
Default: Extract from batch entity’s candidate_tasks.
- get_fixed_batches() list[Batch][source]
Get batches with predetermined task membership.
- Returns:
List of Batch objects with fixed task assignment.
Default: No fixed batches.
- get_task_attribute(task: Task) Hashable | None[source]
Get attribute of a task.
Task attribute determines batching compatibility and batch characteristics. Common examples: - Product type/color/recipe in manufacturing - Priority class in scheduling - Resource requirements
- Parameters:
task – Task to query
- Returns:
Task attribute (any hashable type), or None if no attribute concept
Default: No task attributes.
Example
>>> # Oven scheduling: tasks have product types >>> def get_task_attribute(self, task): ... return self.tasks_data[task].attribute # 0, 1, 2, ...
- get_task_size(task: Task) int | float | tuple[int | float, ...][source]
Get size/weight of a task for bin packing.
Task size is used in batch capacity constraints: sum(task_sizes in batch) <= batch_capacity
Size can be: - Scalar: single dimension (weight, volume, processing time) - Tuple: multiple dimensions (weight AND volume)
- Parameters:
task – Task to query
- Returns:
Task size (int, float, or tuple for multi-dimensional)
Default: Size 1 for all tasks.
Example
>>> # Oven scheduling: tasks have physical size >>> def get_task_size(self, task): ... return self.tasks_data[task].size >>> >>> # Multi-dimensional: (weight, volume) >>> def get_task_size(self, task): ... return (self.task_weight[task], self.task_volume[task])
- is_batch_optional(batch_id: Hashable) bool[source]
Check if batch can be empty (no tasks assigned).
- Parameters:
batch_id – Batch identifier
- Returns:
True if batch can be empty, False if it must have at least one task
Default: All batches are optional.
- must_be_batched(task: Task) bool[source]
Check if a task MUST be assigned to a batch.
- Parameters:
task – Task to query
- Returns:
True if task must be in a batch, False if batching is optional
Default: Batching is optional for all tasks.
Example
>>> # Some products must be batched, others can run individually >>> def must_be_batched(self, task): ... return self.tasks_data[task].requires_batching
- class discrete_optimization.generic_tasks_tools.batching.BatchingSolution(problem: Problem)[source]
Bases:
TasksSolution[Task],Generic[Task]Mixin for solutions to batching problems.
Provides abstract methods for querying batch assignments. Concrete solutions must implement at least one of: - get_batch_membership(batch_id) -> set[Task] - get_task_batch_assignment(task) -> BatchId
These methods are used by VariableBatchEntity to determine batch spans.
- check_batch_attributes() bool[source]
Check that each batch has a valid attribute.
For batches with task attribute concept, ensures batch can be assigned a valid attribute based on its tasks.
- Returns:
True if all batches have valid attributes, False otherwise
- check_batch_capacity() bool[source]
Check that all batches respect capacity constraints.
Validates: sum(task_sizes) <= batch_capacity for each batch. Supports scalar and multi-dimensional sizes/capacities.
- Returns:
True if all batches within capacity, False otherwise
- check_batch_compatibility() bool[source]
Check that all tasks in each batch are compatible.
- Returns:
True if all batches contain only compatible tasks, False otherwise
- check_batch_size_constraints() bool[source]
Check that all batches satisfy size constraints.
- Returns:
True if all batch sizes are within bounds, False otherwise
- check_task_batch_uniqueness() bool[source]
Check that each task is assigned to at most one batch.
- Returns:
True if no task appears in multiple batches, False otherwise
- get_batch_membership(batch_id: Hashable) set[Task][source]
Get all tasks assigned to a batch.
Default implementation queries each task. Can be overridden for efficiency.
- Parameters:
batch_id – Batch to query
- Returns:
Set of tasks in this batch
- get_batch_size(batch_id: Hashable) int[source]
Get number of tasks in a batch.
- Parameters:
batch_id – Batch to query
- Returns:
Number of tasks assigned to this batch
- get_task_batch_assignment(task: Task) Hashable | None[source]
Get which batch a task is assigned to.
- Parameters:
task – Task to query
- Returns:
Batch ID that task is assigned to, or None if unassigned
- problem: BatchingProblem[Task]
discrete_optimization.generic_tasks_tools.calendar_preemptive module
Module containing utils for problem having calendar based preemption: This means the tasks can overlap over a period where the resource are not met for this task: the duration of tasks can be pre-computed based on the start time. The hypothesis is that the task will be executed whenever there is enough cumulative resource available at a given time.
- class discrete_optimization.generic_tasks_tools.calendar_preemptive.CalendarPreemptionData(durations: dict[tuple[Task, int], tuple[ndarray, dict[int, list[list[int]]]]], resource_calendar_dict: dict[tuple[Hashable, int] | tuple[tuple[Hashable, int], ...], ndarray], task_mode_to_calendar: dict[tuple[Task, int], tuple[Hashable, int] | tuple[tuple[Hashable, int], ...]])[source]
Bases:
Generic[Task]Data structure containing calendar-aware preemption information for scheduling problems.
This class encapsulates the precomputed information needed to handle task preemption when resources have varying availability over time (e.g., workers unavailable on weekends).
For each (task, mode) combination, it provides: - How the actual task duration varies based on start time - Which time intervals are valid for each possible duration - Binary calendars indicating when resources are available
- durations
Maps (task, mode) to preemption duration information. For each (task, mode): - duration_array[t]: actual time units needed if task starts at time t - interval_dict[d]: list of [start, end) intervals where starting the task
results in duration d
- Type:
dict[tuple[discrete_optimization.generic_tasks_tools.base.Task, int], tuple[numpy.ndarray, dict[int, list[list[int]]]]]
- resource_calendar_dict
Maps resource consumption patterns to binary availability calendars. Each binary calendar is a numpy array where 1 = resources available, 0 = unavailable. The key is a CalendarKey identifying a unique resource consumption pattern.
- Type:
dict[tuple[collections.abc.Hashable, int] | tuple[tuple[collections.abc.Hashable, int], …], numpy.ndarray]
- task_mode_to_calendar
Maps each (task, mode) to its resource consumption pattern key. Used to look up the corresponding binary calendar in resource_calendar_dict.
- Type:
dict[tuple[discrete_optimization.generic_tasks_tools.base.Task, int], tuple[collections.abc.Hashable, int] | tuple[tuple[collections.abc.Hashable, int], …]]
- durations: dict[tuple[Task, int], tuple[ndarray, dict[int, list[list[int]]]]]
- get_binary_calendar(task: Task, mode: int) ndarray[source]
Get the binary availability calendar for a task/mode.
- Parameters:
task – The task
mode – The mode
- Returns:
Binary numpy array where 1 = resources available, 0 = unavailable
- get_duration_for_start_time(task: Task, mode: int, start_time: int) int[source]
Get the actual duration if the task starts at the given time.
- Parameters:
task – The task
mode – The mode
start_time – The proposed start time
- Returns:
Actual duration in time units (may be larger than nominal duration due to preemption)
- resource_calendar_dict: dict[tuple[Hashable, int] | tuple[tuple[Hashable, int], ...], ndarray]
- task_mode_to_calendar: dict[tuple[Task, int], tuple[Hashable, int] | tuple[tuple[Hashable, int], ...]]
- to_index_based(problem: CalendarPreemptiveProblem) tuple[dict[tuple[int, int], tuple[ndarray, dict[int, list[list[int]]]]], dict[tuple[int, int], ndarray], dict[tuple[int, int], tuple[Hashable, int] | tuple[tuple[Hashable, int], ...]]][source]
Convert task-based keys to index-based keys for solver compatibility.
Some solvers (e.g., FlexProblem solvers) expect integer task indices rather than task objects. This method remaps all data to use indices.
- Parameters:
problem – The scheduling problem providing the task-to-index mapping
- Returns:
durations_by_index: dict[(task_index, mode)] -> (duration_array, interval_dict)
res_arrays: dict[(task_index, mode)] -> binary calendar array
task_mode_to_calendar_by_index: dict[(task_index, mode)] -> CalendarKey
- Return type:
tuple of
- class discrete_optimization.generic_tasks_tools.calendar_preemptive.CalendarPreemptiveProblem[source]
Bases:
CumulativeResourceProblem[Task,CumulativeResource,OtherCalendarResource],Generic[Task,CumulativeResource,OtherCalendarResource]- calendar_preemption_data: CalendarPreemptionData[Task] = None
- compute_task_durations_with_calendar_preemption(horizon: int | None = None) CalendarPreemptionData[source]
Compute preemptive durations for all tasks/modes considering resource calendars.
For each (task, mode) combination, computes how the actual duration varies based on start time due to resource availability constraints from cumulative resources.
This method automatically extracts the necessary data from the problem structure and caches the result for efficiency.
- Parameters:
horizon – problem horizon (max time), defaults to get_makespan_upper_bound()
- Stores:
CalendarPreemptionData containing: - durations: mapping from (task, mode) to (duration_array, interval_dict) - resource_calendar_dict: binary calendars for each resource consumption pattern - task_mode_to_calendar: mapping from (task, mode) to calendar key
- get_calendar_preemption_data() CalendarPreemptionData[source]
- initialized_calendar_preemption_data = False
- class discrete_optimization.generic_tasks_tools.calendar_preemptive.CalendarPreemptiveSolution(problem: Problem)[source]
Bases:
CumulativeResourceSolution[Task,CumulativeResource,OtherCalendarResource]- problem: CalendarPreemptiveProblem[Task, CumulativeResource, OtherCalendarResource]
- discrete_optimization.generic_tasks_tools.calendar_preemptive.compute_binary_calendar_for_resource_consumption(resource_availabilities: dict[Any, ndarray], resource_consumption: dict[Any, int]) ndarray[source]
Compute binary calendar showing when resources are available for given consumption.
Given resource availability calendars and a consumption requirement, this computes a binary array indicating at each time step whether all required resources are available in sufficient quantity.
- Parameters:
resource_availabilities – dict mapping resource ID to availability array (values = capacity at each time)
resource_consumption – dict mapping resource ID to required consumption amount
- Returns:
Binary numpy array where 1 = all resources available with sufficient capacity, 0 = not available
Example
If resource_availabilities = {‘R1’: [2, 2, 0, 2], ‘R2’: [1, 1, 1, 1]} and resource_consumption = {‘R1’: 1, ‘R2’: 1} returns [1, 1, 0, 1] (unavailable at t=2 because R1 has 0 capacity)
- discrete_optimization.generic_tasks_tools.calendar_preemptive.compute_duration_with_calendar_preemption(orig_duration: int, resource_calendar: ndarray, cumulative_resource_calendar: ndarray) tuple[ndarray, dict[int, list[list[int]]]][source]
Compute how task duration varies based on start time given resource calendar.
This is the core algorithm for calendar-aware preemption. For each possible start time, it computes the actual duration (in time units) needed to complete orig_duration units of work, considering resource availability.
When a resource has varying availability (e.g., unavailable on weekends), a task requiring N work units may take more than N time units to complete. This function computes the mapping between start time and actual completion time.
- Parameters:
orig_duration – Original work duration (in work units, not time units)
resource_calendar – Binary array indicating resource availability at each time (1=available, 0=unavailable)
cumulative_resource_calendar – Cumulative sum of resource_calendar
- Returns:
duration array: duration[i] = actual time units needed if starting at time i (-1 if cannot complete)
- interval dict: maps each possible duration to list of [start, end] intervals
where that duration applies
- Return type:
tuple of
Example
If resource_calendar = [1, 1, 0, 1, 1] and orig_duration = 3: - Starting at t=0: work at t=0,1,3 → duration = 4 (takes 4 time units to complete 3 work units) - Starting at t=1: work at t=1,3,4 → duration = 4 - Starting at t=3: only 2 work units available (t=3,4) → duration = -1 (cannot complete) - Starting at t=4: only 1 work unit available → duration = -1 (cannot complete)
discrete_optimization.generic_tasks_tools.calendar_resource module
- class discrete_optimization.generic_tasks_tools.calendar_resource.CalendarResourceProblem[source]
Bases:
SchedulingProblem[Task],Generic[Task,Resource]Base class for scheduling problems dealing with renewable resources whose availability depend on a calendar.
- abstract property calendar_resources_list: list[Resource]
Renewable resources with an availability calendar used by the tasks.
Notes
renewable = the resource replenishes as soon as a task using it ends;
it can be a mix of unary resources (e.g. employees) and cumulative resources (e.g. tool types).
calendar can be constant
- get_fake_tasks(resource: Resource) list[tuple[int, int, int]][source]
Get fake tasks explaining the delta between resource current capacity and its max capacity
- Parameters:
resource
- Returns:
list of intervals of the form (start, end, value), for task starting at start and ending at end, using value resource.
- abstractmethod get_resource_availabilities(resource: Resource) list[tuple[int, int, int]][source]
Get availabilities intervals for a given resource
List of availability intervals of a resource. If the resource is not available, potentially no interval returned.
It is assumed that the intervals are disjunct though.
- Parameters:
resource
- Returns:
list of intervals of the form (start, end, value), which means from time start to time end, there are value of the resource available. NB: the start is included, the end is excluded (start <= t < end)
- get_resource_calendar(resource: Resource, horizon: int | None = None) list[int][source]
Compute resource calendar.
- Parameters:
resource
horizon – max value of time considered. Default to self.get_makespan_upper_bound().
- Returns:
list of resource value by time step from 0 to horizon-1.
- get_resource_consolidated_availabilities(resource: Resource, horizon: int | None = None) list[tuple[int, int, int]][source]
Get availabilities intervals for a given resource, consolidated as a partition of [0, horizon)
Default implementation use the get_calendar_resource_availabilities, by assuming the intervals are disjunct but potentially lacking 0-valued intervals.
- Parameters:
resource
horizon – max value of time considered. Default to self.get_makespan_upper_bound().
- Returns:
sorted list of intervals of the form (start, end, value), which means from time start to time end, there are value of the resource available NB: the start is included, the end is excluded (start <= t < end)
- class discrete_optimization.generic_tasks_tools.calendar_resource.CalendarResourceSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task],Generic[Task,Resource]- check_all_calendar_resource_capacity_constraints() bool[source]
Check capacity constraint on all calendar resources.
- check_calendar_resource_capacity_constraint(resource: Resource) bool[source]
Check capacity constraint on given resource.
- check_calendar_resource_capacity_constraints(resources: Iterable[Resource]) bool[source]
Check capacity constraint respected on given resources.
Do it simultaneously on all resources to optimize computation time.
- compute_aggregated_calendar_resources_levels(weights: dict[Resource, int] | None = None) int[source]
Compute aggregated level (i.e. min capacity needed) of each calendar resource.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
- compute_calendar_resources_levels() dict[Resource, int][source]
Compute the level (i.e. min capacity needed) for each calendar resource.
- compute_nb_calendar_resources_used(weights: dict[Resource, int] | None = None) int[source]
Compute number of calendar resources used by at least one task.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
Returns:
- abstractmethod get_calendar_resource_consumption(resource: Resource, task: Task) int[source]
Get resource consumption by given task.
- Parameters:
resource
task
Returns:
- problem: CalendarResourceProblem[Task, Resource]
- class discrete_optimization.generic_tasks_tools.calendar_resource.WithoutCalendarResourceProblem[source]
Bases:
CalendarResourceProblem[Task,None],Generic[Task]- property calendar_resources_list: list[Resource]
Renewable resources with an availability calendar used by the tasks.
Notes
renewable = the resource replenishes as soon as a task using it ends;
it can be a mix of unary resources (e.g. employees) and cumulative resources (e.g. tool types).
calendar can be constant
- get_resource_availabilities(resource: Resource) list[tuple[int, int, int]][source]
Get availabilities intervals for a given resource
List of availability intervals of a resource. If the resource is not available, potentially no interval returned.
It is assumed that the intervals are disjunct though.
- Parameters:
resource
- Returns:
list of intervals of the form (start, end, value), which means from time start to time end, there are value of the resource available. NB: the start is included, the end is excluded (start <= t < end)
- class discrete_optimization.generic_tasks_tools.calendar_resource.WithoutCalendarResourceSolution(problem: Problem)[source]
Bases:
CalendarResourceSolution[Task,None],Generic[Task]- check_all_calendar_resource_capacity_constraints() bool[source]
Check capacity constraint on all calendar resources.
- check_calendar_resource_capacity_constraint(resource: Resource) bool[source]
Check capacity constraint on given resource.
- check_calendar_resource_capacity_constraints(resources: Iterable[Resource]) bool[source]
Check capacity constraint respected on given resources.
Do it simultaneously on all resources to optimize computation time.
- compute_aggregated_calendar_resources_levels(weights: dict[Resource, int] | None = None)[source]
Compute aggregated level (i.e. min capacity needed) of each calendar resource.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
- compute_calendar_resources_levels() dict[Resource, int][source]
Compute the level (i.e. min capacity needed) for each calendar resource.
- discrete_optimization.generic_tasks_tools.calendar_resource.consolidate_availability_intervals(intervals: list[tuple[int, int, int]], horizon: int)[source]
Ensure that the intervals are a partition of [0, horizon).
- Parameters:
intervals – intervals (start, end, value). Supposed to be disjunct.
horizon – max value of time considered
- Returns:
sorted list of intervals constituting a partition of [0, horizon)
- discrete_optimization.generic_tasks_tools.calendar_resource.consolidate_calendar(calendar: list[int], horizon: int)[source]
Consoidate the calendar to correspond to the given horizon
If too long, retursn calendar[:horizon]. If too short, fill with 0’s.
- Parameters:
calendar
horizon
- Returns:
a calendar of size horizon
- discrete_optimization.generic_tasks_tools.calendar_resource.convert_availability_intervals_to_calendar(intervals: list[tuple[int, int, int]], horizon: int) list[int][source]
Convert availability intervals into a calendar.
- Parameters:
intervals – availability intervals, assumed to be disjunct
horizon – maximum time step considered
- Returns:
list of available resource values for each time step
- discrete_optimization.generic_tasks_tools.calendar_resource.convert_calendar_to_availability_intervals(calendar: int | list[int] | NDArray[int], horizon: int) list[tuple[int, int, int]][source]
Convert a calendar into availability intervals.
- Parameters:
calendar – if integer means a constant value, else list of values for each time step. If len(calendar)<horizon, last values are assumed to be 0. If len(calendar)>horizon, it is truncated to calendar[:horizon]
horizon – maximum time step considered
- Returns:
list of (start,end, value), a sorted partition of [0, horizon)
- discrete_optimization.generic_tasks_tools.calendar_resource.merge_resources_availability_intervals(intervals_per_resource: list[list[tuple[int, int, int]]], horizon: int) list[tuple[int, int, int]][source]
Merge several resources availability intervals, considering all resources as one meta-resource
- Parameters:
intervals_per_resource – availability for each resource
horizon – maximum time step considered
- Returns:
availability intervals for the meta-resource
- discrete_optimization.generic_tasks_tools.calendar_resource.merge_resources_calendars(calendars: list[list[int]], horizon: int) list[int][source]
Merge several resources calendars, considering all resources as one meta-resource
- Parameters:
calendars – calendars for each resource to merge
horizon – maximum time step considered
- Returns:
calendar for the meta-resource
discrete_optimization.generic_tasks_tools.cumulative_resource module
- class discrete_optimization.generic_tasks_tools.cumulative_resource.CumulativeResourceProblem[source]
Bases:
CalendarResourceProblem[Task,CumulativeResource|OtherCalendarResource],MultimodeSchedulingProblem[Task],Generic[Task,CumulativeResource,OtherCalendarResource]Scheduling problem with cumulative resources consumed by tasks.
Supports two consumption modes:
Standard: Task consumption is fixed by task mode. Example: Task A in mode 1 always consumes 5 units.
Resource-dependent: Task consumption depends on other tasks’ modes. Modeled via a consumption mapping. If the task/mode dont depend on any other task, returns empty condition with the static resource need.
Resource-Dependent Example:
Task A’s electricity varies based on whether task B’s heater is on:
>>> mapping = { ... frozenset([("task_B", 0)]): 10, # B heater off: A uses 10 kW ... frozenset([("task_B", 1)]): 8, # B heater on: A uses 8 kW ... }
Implementation pattern:
>>> class MyProblem(CumulativeResourceProblem): ... def is_cumulative_resource_task_mode_consumption_dependent( ... self, resource, task, mode ... ): ... return resource in self.mode_details[task][mode] ... ... def get_cumulative_resource_consumption_mapping( ... self, resource, task, mode ... ): ... if self.is_cumulative_resource_task_mode_consumption_dependent( ... resource, task, mode ... ): ... return self.mode_details[task][mode][resource] ... return None ... ...
See src/discrete_optimization/rcpsp_resource_dependent/problem.py for a complete implementation.
- abstract property cumulative_resources_list: list[CumulativeResource]
- abstractmethod get_cumulative_resource_consumption(resource: CumulativeResource, task: Task, mode: int) int[source]
Get cumulative resource consumption of the task in the given mode
- Parameters:
resource – cumulative resource
task
mode – not used for single mode problems
- Returns:
the consumption for cumulative resources.
- get_cumulative_resource_consumption_mapping(resource: CumulativeResource, task: Task, mode: int) dict[frozenset[tuple[Task, int]], int] | None[source]
Get resource consumption mapping for resource-dependent tasks.
- Parameters:
resource – The cumulative resource
task – The task
mode – The task mode
- Returns:
Mapping from task/mode configurations to consumption values. Keys are frozensets of (task, mode) tuples. Returns None if task has standard (non-dependent) consumption.
Example
>>> mapping = problem.get_cumulative_resource_consumption_mapping( ... "electricity", task_A, 0 ... ) {frozenset([("task_B", 0)]): 100, frozenset([("task_B", 1)]): 80}
- get_possible_cumulative_resource_consumption(resource: CumulativeResource, task: Task, mode: int) set[int][source]
- get_possible_cumulative_resource_consumption_all_modes(resource: CumulativeResource, task: Task) set[int][source]
- is_cumulative_resource(resource: CumulativeResource | OtherCalendarResource) bool[source]
Check if given resource is a cumulative resource whose consumption depends only on task mode.
- Parameters:
resource
Returns:
- is_cumulative_resource_task_consumption_dependent(resource: CumulativeResource, task: Task)[source]
- class discrete_optimization.generic_tasks_tools.cumulative_resource.CumulativeResourceSolution(problem: Problem)[source]
Bases:
CalendarResourceSolution[Task,CumulativeResource|OtherCalendarResource],MultimodeSchedulingSolution[Task],Generic[Task,CumulativeResource,OtherCalendarResource]Solution type associated to CumulativeResourceProblem.
- get_calendar_resource_consumption(resource: CumulativeResource | OtherCalendarResource, task: Task) int[source]
Get resource consumption by given task.
Dispatches to either: - get_cumulative_resource_consumption() for standard (fixed) consumption - get_calendar_resource_consumption_from_mapping() for resource-dependent consumption
- Parameters:
resource – The calendar resource (must be cumulative)
task – The task
- Returns:
Resource consumption amount
- Raises:
NotImplementedError – If resource is not cumulative
- get_calendar_resource_consumption_from_mapping(resource: CumulativeResource, task: Task) int[source]
Retrieve resource consumption from mapping based on current solution’s mode assignments.
- Parameters:
resource – The cumulative resource
task – The task
- Returns:
Resource consumption value, or None if no matching configuration found.
Example
Given mapping {frozenset([(task_B, 1)]): 8, frozenset([(task_B, 0)]): 10} and solution with task_B in mode 1, returns 8.
- problem: CumulativeResourceProblem[Task, CumulativeResource, OtherCalendarResource]
- class discrete_optimization.generic_tasks_tools.cumulative_resource.WithoutCumulativeResourceProblem[source]
Bases:
CumulativeResourceProblem[Task,None,OtherCalendarResource],Generic[Task,OtherCalendarResource]Mixin for problem without cumulative resources.
To be used has an additional mixin with generic GenericSchedulingProblem.
- property cumulative_resources_list: list[CumulativeResource]
- get_cumulative_resource_consumption(resource: CumulativeResource, task: Task, mode: int) int[source]
Get cumulative resource consumption of the task in the given mode
- Parameters:
resource – cumulative resource
task
mode – not used for single mode problems
- Returns:
the consumption for cumulative resources.
- class discrete_optimization.generic_tasks_tools.cumulative_resource.WithoutCumulativeResourceSolution(problem: Problem)[source]
Bases:
CumulativeResourceSolution[Task,None,OtherCalendarResource],Generic[Task,OtherCalendarResource]Mixin for solution without cumulative resources.
To be used has an additional mixin with generic GenericSchedulingSolution.
discrete_optimization.generic_tasks_tools.cumulative_resource_generic module
- class discrete_optimization.generic_tasks_tools.cumulative_resource_generic.CumulativeResourceGenericProblem[source]
Bases:
CalendarPreemptiveProblem[Task,CumulativeResource,UnaryResource],CumulativeResourceUsageByUnaryResourceProblem[Task,CumulativeResource,UnaryResource],Generic[Task,CumulativeResource,UnaryResource]
- class discrete_optimization.generic_tasks_tools.cumulative_resource_generic.CumulativeResourceGenericSolution(problem: Problem)[source]
Bases:
CalendarPreemptiveSolution[Task,CumulativeResource,UnaryResource],CumulativeResourceUsageByUnarySolution[Task,CumulativeResource,UnaryResource],Generic[Task,CumulativeResource,UnaryResource]- problem: CumulativeResourceGenericProblem[Task, CumulativeResource, UnaryResource]
discrete_optimization.generic_tasks_tools.entities module
Entity abstraction for scheduling constraints.
This module provides a unified abstraction for scheduling entities that can participate in various types of constraints (precedence, time lags, resource blocking, etc.).
An entity represents any schedulable object with start and end times: - Individual tasks (TaskEntity) - Groups of tasks (GroupEntity) - Tasks in specific modes (TaskModeEntity) - Hierarchical compositions of entities (CompositeEntity)
The abstraction is recursive: CompositeEntity can contain any other entities (including other CompositeEntity instances), enabling arbitrary hierarchical structures for constraint modeling (e.g., projects → phases → tasks).
Entities are immutable (frozen dataclasses) so they can be used as dict keys.
- class discrete_optimization.generic_tasks_tools.entities.CompositeEntity(entities: frozenset[SchedulingEntity], composite_id: Hashable | None = None)[source]
Bases:
SchedulingEntity[Task]Entity representing a hierarchical composition of other entities.
This enables recursive entity structures for hierarchical constraint modeling: - Groups of groups (e.g., projects containing sub-projects) - Mixed collections of tasks, groups, and mode-specific entities - Arbitrarily nested entity hierarchies (e.g., departments → teams → tasks)
The composite’s start time is the minimum start of its active children. The composite’s end time is the maximum end of its active children.
Examples
# Hierarchy: Project → Phases → Tasks phase1 = CompositeEntity(
entities=frozenset({TaskEntity(t1), TaskEntity(t2)}), composite_id=”phase1”
) phase2 = CompositeEntity(
entities=frozenset({TaskEntity(t3), TaskEntity(t4)}), composite_id=”phase2”
) project = CompositeEntity(
entities=frozenset({phase1, phase2}), composite_id=”project_alpha”
)
# Mixed: combining different entity types mixed = CompositeEntity(
- entities=frozenset({
TaskEntity(t1), GroupEntity(tasks=frozenset({t2, t3})), TaskModeEntity(task=t4, mode=2)
})
)
- entities
Set of child entities (must be non-empty)
- Type:
frozenset[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity]
- composite_id
Optional identifier for display/debugging
- Type:
collections.abc.Hashable | None
- Raises:
ValueError – If entities set is empty, or if all children are inactive when querying start/end times
- composite_id: Hashable | None = None
- entities: frozenset[SchedulingEntity]
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- class discrete_optimization.generic_tasks_tools.entities.ConstantDurationEntity(other_entity: SchedulingEntity[Task], constant_duration: int, offset: int = 0, start_or_end: StartOrEnd = StartOrEnd.START, constant_duration_id: Hashable | None = None)[source]
Bases:
SchedulingEntity[Task]Entity representing a constant duration block starting at start or end of a given entity
- constant_duration: int
- constant_duration_id: Hashable | None = None
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- offset: int = 0
- other_entity: SchedulingEntity[Task]
- start_or_end: StartOrEnd = 'start'
- class discrete_optimization.generic_tasks_tools.entities.DummyEntity(start: 'int', end: 'int', attribute: 'int', id_entity: 'Hashable')[source]
Bases:
SchedulingEntity[Task]- attribute: int
- end: int
- entity_id() Hashable[source]
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- id_entity: Hashable
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- start: int
- class discrete_optimization.generic_tasks_tools.entities.GroupEntity(tasks: frozenset[Task], group_id: Hashable | None = None)[source]
Bases:
SchedulingEntity[Task]Entity representing a group/batch of tasks.
The group’s start time is the minimum start of its tasks. The group’s end time is the maximum end of its tasks.
This is useful for: - Representing projects with multiple tasks - Modeling batches that must stay together - Defining spans that consume resources
- tasks
Set of tasks in the group (must be non-empty)
- Type:
frozenset[discrete_optimization.generic_tasks_tools.base.Task]
- group_id
Optional identifier for the group (for display/debugging)
- Type:
collections.abc.Hashable | None
Examples
>>> entity = GroupEntity( ... tasks=frozenset({"prep", "main", "cleanup"}), ... group_id="maintenance_job_1" ... ) >>> entity.get_start_time(solution) # min(start of prep, main, cleanup) >>> entity.get_end_time(solution) # max(end of prep, main, cleanup) >>> entity.get_tasks() frozenset({'prep', 'main', 'cleanup'})
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- group_id: Hashable | None = None
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- tasks: frozenset[Task]
- class discrete_optimization.generic_tasks_tools.entities.ModuloTaskEntity(task: 'Task', modulo_value: 'int')[source]
Bases:
SchedulingEntity[Task]- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- modulo_value: int
- task: Task
- class discrete_optimization.generic_tasks_tools.entities.ModuloTwoEntity(entity: 'SchedulingEntity[Task]', modulo_entity: 'SchedulingEntity[Task]', modulo_value_start_or_end: 'StartOrEnd' = <StartOrEnd.START: 'start'>)[source]
Bases:
SchedulingEntity[Task]- entity: SchedulingEntity[Task]
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_modulo_value(solution: SchedulingSolution) int | AbsentValue[source]
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- modulo_entity: SchedulingEntity[Task]
- modulo_value_start_or_end: StartOrEnd = 'start'
- class discrete_optimization.generic_tasks_tools.entities.MultiplyTaskEntity(task: 'Task', multiply_factor: 'int', start_or_end: 'StartOrEnd' = <StartOrEnd.START: 'start'>)[source]
Bases:
SchedulingEntity[Task]- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- multiply_factor: int
- start_or_end: StartOrEnd = 'start'
- task: Task
- class discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[source]
Bases:
Generic[Task]Abstract representation of a scheduling entity that has start and end times.
An entity represents any schedulable object that can participate in constraints: - Individual tasks (TaskEntity) - Groups of tasks (GroupEntity) - Tasks in specific execution modes (TaskModeEntity) - Hierarchical compositions of entities (CompositeEntity) - Other aggregations (resources, shifts, projects, etc.)
Entities are immutable (frozen dataclass) so they can be used as dict keys.
The entity abstraction is recursive: CompositeEntity can contain other entities, enabling hierarchical constraint modeling (e.g., projects → phases → tasks).
The entity abstraction allows expressing complex constraints naturally: - “Group of tasks must finish before another task starts” (precedence) - “Resource blocked from end of group to start of task” (resource blocking) - “If task is in mode 2, then block resource X” (conditional blocking) - “All phases of a project must respect a resource limit” (hierarchical constraints)
Example
>>> from discrete_optimization.generic_tasks_tools.entities import TaskEntity, GroupEntity >>> # Individual task >>> task_ent = TaskEntity("paint") >>> # Group of tasks >>> group_ent = GroupEntity(frozenset({"prep", "paint", "dry"}), "painting_job") >>> # Query in solution >>> start = task_ent.get_start_time(solution) >>> group_start = group_ent.get_start_time(solution) # min of task starts
- abstract property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- abstractmethod get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- abstractmethod get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- abstractmethod get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- abstractmethod is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- class discrete_optimization.generic_tasks_tools.entities.TaskEntity(task: Task)[source]
Bases:
SchedulingEntity[Task]Entity representing a single task.
This is the most common entity type, wrapping a Task reference.
- task
The task this entity represents
- Type:
discrete_optimization.generic_tasks_tools.base.Task
Examples
>>> entity = TaskEntity(task="assembly") >>> entity.get_start_time(solution) >>> entity.get_end_time(solution) >>> entity.get_tasks() frozenset({'assembly'}) >>> entity.is_active(solution)
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if this entity is active/present in the solution.
For tasks: always True (task is always scheduled) For groups: True if any task in group is scheduled For conditional entities: True if the condition is satisfied
(e.g., TaskModeEntity is active only if task is in specified mode)
- Parameters:
solution – The scheduling solution to query
- Returns:
True if entity is active, False otherwise
- task: Task
- class discrete_optimization.generic_tasks_tools.entities.TaskModeEntity(task: Task, mode: int)[source]
Bases:
SchedulingEntity[Task]Entity representing a task in a specific execution mode.
This entity is only “active” if the task is executed in the specified mode. Useful for mode-dependent constraints: - “If task A is in mode 1, then block resource X” - “Task B can only start after task A in mode 2 completes”
- task
The task
- Type:
discrete_optimization.generic_tasks_tools.base.Task
- mode
The specific mode (integer)
- Type:
int
Examples
>>> entity = TaskModeEntity(task="painting", mode=2) >>> entity.is_active(solution) # True only if painting is in mode 2 False # (if painting is in mode 1) >>> # If active: >>> entity.get_start_time(solution) 10 >>> entity.get_tasks() frozenset({'painting'})
- Raises:
ValueError – When calling get_start_time() or get_end_time() on an inactive entity
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue.ABSENT[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue.ABSENT[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Get all tasks that compose this entity.
For single tasks: {task} For groups: all tasks in the group For conditional entities: {task}
- Returns:
Frozen set of tasks
- is_active(solution: SchedulingSolution) bool[source]
Check if the task is executed in the specified mode.
- mode: int
- task: Task
- class discrete_optimization.generic_tasks_tools.entities.VariableBatchEntity(batch_id: Hashable, candidate_tasks: frozenset[Task] = frozenset({}))[source]
Bases:
SchedulingEntity[Task]Entity representing a batch with variable task membership.
Unlike GroupEntity where tasks are fixed, VariableBatchEntity’s membership is determined by the solution. This is essential for batching problems where: - The problem defines candidate tasks and batch IDs - The solution assigns tasks to batches - Constraints apply to batches (size limits, time windows, resource blocking)
The entity queries the solution (which must be a BatchingSolution) to determine which tasks belong to this batch.
- batch_id
Unique identifier for this batch
- Type:
collections.abc.Hashable
- candidate_tasks
Set of tasks that COULD be in this batch (used for get_tasks())
- Type:
frozenset[discrete_optimization.generic_tasks_tools.base.Task]
Examples
>>> from discrete_optimization.generic_tasks_tools.batching import ( ... BatchingProblem, BatchingSolution ... ) >>> # Define batch entities in problem >>> batch1 = VariableBatchEntity("batch_1", frozenset({0, 1, 2, 3, 4})) >>> batch2 = VariableBatchEntity("batch_2", frozenset({0, 1, 2, 3, 4})) >>> >>> # Solution must inherit from BatchingSolution and implement: >>> class MySolution(SchedulingSolution, BatchingSolution): ... def get_task_batch_assignment(self, task): ... return self.job_to_batch[task] # Return batch ID for task >>> >>> # Query batch1 span >>> batch1.get_start_time(solution) # min(start of jobs 0, 1, 4) >>> batch1.get_end_time(solution) # max(end of jobs 0, 1, 4) >>> batch1.is_active(solution) # True (has assigned tasks)
- Requires:
Solution must inherit from BatchingSolution mixin (batching.py) which provides get_batch_membership() and get_task_batch_assignment()
- batch_id: Hashable
- candidate_tasks: frozenset[Task] = frozenset({})
- property entity_id: Hashable
Unique identifier for this entity.
Used for hashing, equality, and display.
- Returns:
Hashable identifier (str, int, tuple, etc.)
- get_end_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the end time of this entity in the given solution.
For tasks: the task’s end time For groups: maximum end time of tasks in group For conditional entities: end time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
End time (integer)
- Raises:
ValueError – If entity is not active/present in solution
- get_start_time(solution: SchedulingSolution) int | AbsentValue[source]
Get the start time of this entity in the given solution.
For tasks: the task’s start time For groups: minimum start time of tasks in group For conditional entities: start time if active, else raises error
- Parameters:
solution – The scheduling solution to query
- Returns:
Start time (integer)
- Raises:
ValueError – If entity is not active/present in solution (e.g., TaskModeEntity when task is not in the specified mode)
- get_tasks() frozenset[Task][source]
Return candidate tasks (actual assignment depends on solution).
- is_active(solution: SchedulingSolution) bool[source]
Batch is active if it has at least one assigned task.
discrete_optimization.generic_tasks_tools.entity_constraints module
Entity-based constraints for flexible scheduling.
This module extends constraint capabilities beyond tasks to any SchedulingEntity. Entities can be: individual tasks, groups, mode-dependent tasks, hierarchical compositions, or variable-membership batches.
This allows expressing constraints like: - “Project (group of tasks) must finish before another task starts” (precedence) - “Setup period (fixed duration entity) must start after batch ends” (time lag) - “Batch (variable membership) must start within time window” (time window)
- class discrete_optimization.generic_tasks_tools.entity_constraints.EntityConstraintsProblem[source]
Bases:
SchedulingProblem[Task]Mixin for problems with entity-based constraints.
This mixin allows defining precedence, time lags, and time windows for any SchedulingEntity, not just tasks. This enables more expressive constraints:
Precedence between groups: “Phase 1 (group) → Task A”
Time lags with mode-dependent entities: “If task in mode 2, wait 5 units before next”
Time windows for batches: “Batch must start between 8am and 5pm”
Hierarchical constraints: “Department must complete before project starts”
All methods use @optional_override, so implementing classes only need to override methods for constraints they actually use.
- get_entity_end_to_end_max_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get max time lags between entity ends.
- Returns:
end(entity1) + offset >= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_end_min_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get min time lags between entity ends.
- Returns:
end(entity1) + offset <= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_start_max_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get max time lags between entity end and start.
- Returns:
end(entity1) + offset >= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_start_min_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get min time lags between entity end and start.
- Returns:
end(entity1) + offset <= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_precedence_constraints() dict[SchedulingEntity[Task], Iterable[SchedulingEntity[Task]]][source]
Get precedence constraints between entities.
- Returns:
Mapping from entity to entities that must follow it. entity1 → [entity2, entity3] means entity1.end <= entity2.start AND entity1.end <= entity3.start
Example
>>> # Project phase must complete before individual task >>> phase1 = GroupEntity(frozenset({t1, t2, t3}), "phase1") >>> task_a = TaskEntity("task_a") >>> return {phase1: [task_a]} # phase1 → task_a
Default: No entity precedence constraints.
- get_entity_start_to_end_max_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get max time lags between entity start and end.
- Returns:
start(entity1) + offset >= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_end_min_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get min time lags between entity start and end.
- Returns:
start(entity1) + offset <= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_start_max_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get max time lags between entity starts.
- Returns:
start(entity1) + offset >= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_start_min_time_lags() list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get min time lags between entity starts.
- Returns:
start(entity1) + offset <= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_time_lags(entity1_start_or_end: StartOrEnd, entity2_start_or_end: StartOrEnd, min_or_max: MinOrMax) list[tuple[SchedulingEntity[Task], SchedulingEntity[Task], int]][source]
Get entity time lags for specific combination.
Dispatches to appropriate method based on start/end/min/max combination.
- Parameters:
entity1_start_or_end – Whether to use start or end of first entity
entity2_start_or_end – Whether to use start or end of second entity
min_or_max – Whether this is a minimum or maximum constraint
- Returns:
List of (entity1, entity2, offset) tuples
- get_entity_time_window_lower_bound(entity: SchedulingEntity[Task], start_or_end: StartOrEnd) int | None[source]
Get lower bound on entity start or end time.
- Parameters:
entity – The entity to constrain
start_or_end – Whether constraint applies to start or end
- Returns:
Lower bound (entity time >= bound), or None if no constraint
Example
>>> batch_entity = VariableBatchEntity("batch_1", candidate_tasks) >>> # Batch must start no earlier than time 10 >>> if entity == batch_entity and start_or_end == StartOrEnd.START: ... return 10
Default: No lower bound.
- get_entity_time_window_upper_bound(entity: SchedulingEntity[Task], start_or_end: StartOrEnd) int | None[source]
Get upper bound on entity start or end time.
- Parameters:
entity – The entity to constrain
start_or_end – Whether constraint applies to start or end
- Returns:
Upper bound (entity time <= bound), or None if no constraint
Example
>>> # Batch must complete by time 100 >>> if entity == batch_entity and start_or_end == StartOrEnd.END: ... return 100
Default: No upper bound.
- class discrete_optimization.generic_tasks_tools.entity_constraints.EntityConstraintsSolution[source]
Bases:
Generic[Task]Mixin for solutions to problems with entity constraints.
Provides checking methods for entity-based constraints.
This is a mixin class that should be combined with a SchedulingSolution subclass. The concrete class must provide: - self (SchedulingSolution instance for entity.get_start_time(self), etc.) - self.problem (EntityConstraintsProblem instance)
- check_entity_precedence_constraints() bool[source]
Check that all entity precedence constraints are satisfied.
- Returns:
True if all constraints satisfied, False otherwise
- check_entity_time_lags() bool[source]
Check all entity time lag constraints.
- Returns:
True if all constraints satisfied, False otherwise
- check_entity_time_windows() bool[source]
Check all entity time window constraints.
- Returns:
True if all constraints satisfied, False otherwise
- problem: EntityConstraintsProblem[Task]
discrete_optimization.generic_tasks_tools.enums module
- class discrete_optimization.generic_tasks_tools.enums.AbsentValue(*values)[source]
Bases:
Enum- ABSENT = 'absent'
- class discrete_optimization.generic_tasks_tools.enums.MinOrMax(*values)[source]
Bases:
Enum- MAX = 'max'
- MIN = 'min'
discrete_optimization.generic_tasks_tools.exclusions module
- class discrete_optimization.generic_tasks_tools.exclusions.ExclusionProblem[source]
Bases:
MultimodeSchedulingProblem[Task],Generic[Task,ExclusionResource]- property exclusion_resources_list: list[ExclusionResource]
- get_task_consumption_exclusion_resource(resource: ExclusionResource, task: Task, mode: int)[source]
- class discrete_optimization.generic_tasks_tools.exclusions.ExclusionSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task],MultimodeSolution[Task],Generic[Task,ExclusionResource]- problem: ExclusionProblem[Task, ExclusionResource]
- class discrete_optimization.generic_tasks_tools.exclusions.WithoutExclusionProblem[source]
Bases:
ExclusionProblem[Task,None],Generic[Task]
discrete_optimization.generic_tasks_tools.generic_scheduling module
- class discrete_optimization.generic_tasks_tools.generic_scheduling.GenericSchedulingProblem[source]
Bases:
RoutingProblem[Task],BatchingProblem[Task],ResourceBlockingProblem[Task,Skill|NonSkillCumulativeResource,UnaryResource],ExclusionProblem[Task,ExclusionResource],SkillProblem[Task,UnaryResource,Skill,NonSkillCumulativeResource,UnaryResource],CumulativeResourceGenericProblem[Task,Skill|NonSkillCumulativeResource,UnaryResource],NonRenewableResourceProblem[Task,NonRenewableResource,UnaryResource],PrecedenceSchedulingProblem[Task],TimelagProblem[Task],TimewindowProblem[Task],NoOverlapProblem[Task],AlternativeSchedulingProblem[Task],Generic[Task,UnaryResource,Skill,NonSkillCumulativeResource,NonRenewableResource,ExclusionResource]Scheduling problem with all optional features
This class derives from other mixins to provide utilities that require that mix: - scheduling: tasks need to be scheduled - calendar: the renewable resources have their own calendar that will be used for constraining allocations and schedule - multimode: the tasks have several mode on which the duration depends - cumulative: the tasks consume cumulative resources according to the chosen mode - allocation: the tasks can have unary resources allocated to them - skill: some cumulative resource are skills that are brought to tasks by allocated unary resources - non-renewable: the tasks consume non-renewable resources according to the chosen mode - precedence: precedence constraints between tasks - resource blocking: resources blocked during non-execution periods (gaps, spans) - entity constraints: precedence, time lags, and time windows for any SchedulingEntity (tasks, groups, batches, etc.) - batching: tasks grouped into batches with capacity, compatibility, and setup constraints - cost: the choice of a mode or of an allocation has a given cost
Even though this class is generic but encompasses also more specific cases: - singlemode: actually only one mode per task - no skills: if skills_list is empty - no allocation: unary_resources is empty - no cumulative ressources: if resources_list list only unary resources - no calendar: resource capacity can be given as a constant on [0, horizon) - no non-renewable ressources: if non_renewable_resources_list empty - no precedence constraints: precedence constraints empty - no resource blocking: no blocking constraints defined - no entity constraints: no entity precedence/time lags/time windows defined - no batching: no batch entities or variable batch assignment - no cost: cost = 0
We suppose that all renewable resources are - either cumulative ones - or unary resources
This generic class is to be used to construct generic automatic solvers (e.g. ).
- property calendar_resources_list: list[Skill | NonSkillCumulativeResource | UnaryResource]
Renewable resources with an availability calendar used by the tasks.
Notes
renewable = the resource replenishes as soon as a task using it ends;
it can be a mix of unary resources (e.g. employees) and cumulative resources (e.g. tool types).
calendar can be constant
- check_calendar_resources_list() None[source]
Check calendar resources list.
- Raises:
AssertionError – if duplicates appear in the list
Returns:
- compute_tighter_task_bounds(use_cpm: bool = False, horizon: int | None = None) dict[Task, tuple[int, int, int, int]][source]
Compute tighter task bounds from problem time windows and min-max tak durations.
- Parameters:
use_cpm – whether to use CPM propagating bounds through precedence graph
horizon – new horizon to take into account when computing tighter bounds, default to problem horizon.
- Returns:
(start_lower_bound, end_lower_bound, start_upper_bound, end_upper_bound)}
- Return type:
{task
- evaluate(variable: GenericSchedulingSolution) dict[str, float][source]
Evaluate a given solution object for the given problem.
This method should return a dictionnary of KPI, that can be then used for mono or multiobjective optimization.
- Parameters:
variable (Solution) – the Solution object to evaluate.
Returns: dictionnary of float kpi for the solution.
- get_consolidated_precedence_constraints() dict[Task, set[Task]][source]
Consolidate precedence constraints defined by problem.
It takes into account time lags constraints. - end to start min constraint with non-negative offsets => precedence constraint - start synchronization => corresponding tasks should appear together in successors - end synchornization => corresponding tasks should share their successors
- get_consolidated_time_lags(task1_start_or_end: StartOrEnd, task2_start_or_end: StartOrEnd, min_or_max: MinOrMax)[source]
Get consolidated time lags.
Same normalization as in TimelagProblem parent class. Also taking into account precedence constraints to enrich end to start min time lags.
- Parameters:
task1_start_or_end
task2_start_or_end
min_or_max
Returns:
- abstractmethod get_list_objective_computer() list[ObjectiveComputer][source]
- get_makespan_lower_bound() int[source]
Get a lower bound on global makespan.
Computed tighter lower bounds on last tasks can be used to get a better makespan lower bound.
- get_makespan_tighter_lower_bound(use_cpm: bool = False, horizon: int | None = None) int[source]
Get a tighter lower bound on global makespan.
- Parameters:
use_cpm – whether to use CPM bound propagation through precedence graph to improve tightness
horizon – new horizon to take into account when computing tighter bounds, default to problem horizon. NB: The choice of horizon should not affect the result for the lower bound, but it could avoid CPM complete recomputation thanks to caching if it was already launched with same horizon.
- get_makespan_tighter_upper_bound() int[source]
Compute a tighter upper bound on makespan.
The original makespan upper bound is used when computing tighter bounds for tasks starts and ends, via self.compute_tighter_task_bounds() or self.get_task_start_or_end_tighter_upper_bound(). From that tighter bounds, we can derive a new makespan upper bound.
- get_objective_computer(objective: str) list[ObjectiveComputer][source]
- get_objective_register() ObjectiveRegister[source]
Returns the objective definition.
Returns (ObjectiveRegister): object defining the objective criteria.
- get_task_start_or_end_tighter_lower_bound(task: Task, start_or_end: StartOrEnd, use_cpm: bool = False, horizon: int | None = None) int[source]
Get a tighter lower bound on task start or end using possible durations.
- Parameters:
use_cpm – whether to use CPM propagating bounds through precedence graph
horizon – new horizon to take into account when computing tighter bounds, default to problem horizon.
- get_task_start_or_end_tighter_upper_bound(task: Task, start_or_end: StartOrEnd, use_cpm: bool = False, horizon: int | None = None) int[source]
Get a tighter upper bound on task start or end using possible durations.
- Parameters:
use_cpm – whether to use CPM propagating bounds through precedence graph
horizon – new horizon to take into account when computing tighter bounds, default to problem horizon.
- is_unary_resource(resource: Skill | NonSkillCumulativeResource | UnaryResource) bool[source]
Check if given resource is a unary resource.
- satisfy(variable: GenericSchedulingSolution) bool[source]
Computes if a solution satisfies or not the constraints of the problem.
- Parameters:
variable – the Solution object to check satisfability
Returns (bool): boolean true if the constraints are fulfilled, false elsewhere.
- satisfy_partial(variable: GenericSchedulingSolution, duration: bool = True, calendar: bool = True, non_renewable_capacity: bool = True, precedence: bool = True, skill: bool = True, allocation: bool = True, time_lags: bool = True, time_windows: bool = True, no_overlap: bool = True, forbidden_intervals: bool = True, resource_blocking: bool = True, mode_constraints: bool = True, optional_tasks: bool = True, alternative_scheduling: bool = True, exclusion_resources: bool = True, entity_constraints: bool = True, batching: bool = True, routing: bool = True) bool[source]
Partial checks on solution.
One can switch off some checks by setting the corresponding parameter to False.
- Parameters:
variable
duration
calendar
non_renewable_capacity
precedence
skill
allocation
time_lags
time_windows
no_overlap
forbidden_intervals
resource_blocking
mode_constraints
optional_tasks
alternative_scheduling
exclusion_resources
entity_constraints
batching
Returns:
- update_precedence_constraints() None[source]
Method to call when precedence constraints have been updated.
Clear cache from consolidated precedence constraints and time lags.
Returns:
- update_resource_availabilities() None[source]
Method to call when the resource availabilities have changed.
Default implementation clears the cache on get_resource_max_capacity().
- class discrete_optimization.generic_tasks_tools.generic_scheduling.GenericSchedulingSolution(problem: Problem)[source]
Bases:
RoutingSolution[Task],BatchingSolution[Task],ResourceBlockingSolution[Task,Skill|NonSkillCumulativeResource,UnaryResource],ExclusionSolution[Task,ExclusionResource],SkillSolution[Task,UnaryResource,Skill,NonSkillCumulativeResource,UnaryResource],NonRenewableResourceSolution[Task,NonRenewableResource,UnaryResource],PrecedenceSchedulingSolution[Task],TimelagSolution[Task],TimewindowSolution[Task],NoOverlapSolution[Task],AlternativeSchedulingSolution[Task],Generic[Task,UnaryResource,Skill,NonSkillCumulativeResource,NonRenewableResource,ExclusionResource]Solution type associated to GenericSchedulingProblem.
- get_calendar_resource_consumption(resource: Skill | NonSkillCumulativeResource | UnaryResource, task: Task) int[source]
- is_present(task: Task) bool[source]
Tell whether the task is present in the solution.
It can mean several thing: - scheduling problem: start and end of the task are defined - allocation problem: a ressource has been allocated to the task - multimode: a mode has been chosen for the task - or a mix of it
Sometimes a scheduling allocation problem will allow no resource allocation for present task, it has to be defined problem by problem.
For convenience, a default implementation is provided which assumes that all tasks are present. To be overriden in subclasses.
If and only if this method returns False, the mode, start, and end of the task can have the value AbsentValue.ABSENT.
If the method returns False, the task is removed from all constraints during checks.
- problem: GenericSchedulingProblem[Task, UnaryResource, Skill, NonSkillCumulativeResource, NonRenewableResource, ExclusionResource]
discrete_optimization.generic_tasks_tools.generic_scheduling_impl module
- class discrete_optimization.generic_tasks_tools.generic_scheduling_impl.BatchingData(fixed_batches: list[~discrete_optimization.generic_tasks_tools.batching.Batch] = <factory>, batch_size_bounds: dict[~collections.abc.Hashable, tuple[int | None, int | None]] = <factory>, batch_optional: dict[~collections.abc.Hashable, bool] = <factory>, task_sizes: dict[~collections.abc.Hashable, int | float | tuple[int | float, ...]] = <factory>, task_attributes: dict[~collections.abc.Hashable, ~collections.abc.Hashable] = <factory>, task_batching_mandatory: set[~collections.abc.Hashable] = <factory>, task_batching_forbidden: set[~collections.abc.Hashable] = <factory>, batch_capacities: dict[~collections.abc.Hashable, int | float | tuple[int | float, ...]] = <factory>, batch_duration_bounds: dict[~collections.abc.Hashable, dict[frozenset[~collections.abc.Hashable], tuple[int | None, int | None]]] = <factory>, incompatible_task_pairs: set[frozenset[~collections.abc.Hashable]] = <factory>, batch_presence_chains: list[list[~collections.abc.Hashable]] = <factory>, default_task_size: int | float | tuple[int | float, ...] = 1, default_batch_capacity: int | float | tuple[int | float, ...] = inf, default_batch_optional: bool = True)[source]
Bases:
objectContainer for all batching-related data.
This dataclass groups all batching parameters together for cleaner problem specification.
- batch_capacities: dict[Hashable, int | float | tuple[int | float, ...]]
- batch_duration_bounds: dict[Hashable, dict[frozenset[Hashable], tuple[int | None, int | None]]]
- batch_optional: dict[Hashable, bool]
- batch_presence_chains: list[list[Hashable]]
- batch_size_bounds: dict[Hashable, tuple[int | None, int | None]]
- default_batch_capacity: int | float | tuple[int | float, ...] = inf
- default_batch_optional: bool = True
- default_task_size: int | float | tuple[int | float, ...] = 1
- incompatible_task_pairs: set[frozenset[Hashable]]
- task_attributes: dict[Hashable, Hashable]
- task_batching_forbidden: set[Hashable]
- task_batching_mandatory: set[Hashable]
- task_sizes: dict[Hashable, int | float | tuple[int | float, ...]]
- class discrete_optimization.generic_tasks_tools.generic_scheduling_impl.GenericSchedulingImplProblem(horizon: int, durations_per_mode: dict[~collections.abc.Hashable, dict[int, int]], resource_consumptions: dict[~collections.abc.Hashable, dict[int, dict[~collections.abc.Hashable, int]]] = <factory>, resource_consumptions_dependent: dict[~collections.abc.Hashable, dict[int, dict[~collections.abc.Hashable, dict[frozenset[tuple[~collections.abc.Hashable, int]], int]]]] = <factory>, unary_resource_consumptions_dependent: dict[~collections.abc.Hashable, dict[int, dict[~collections.abc.Hashable, dict[~collections.abc.Hashable, int]]]] = <factory>, successors: dict[~collections.abc.Hashable, set[~collections.abc.Hashable]] = <factory>, unary_resources: set[~collections.abc.Hashable] = <factory>, unary_resources_skills: dict[~collections.abc.Hashable, dict[~collections.abc.Hashable, int]] = <factory>, unary_resources_availabilities: dict[~collections.abc.Hashable, list[tuple[int, int]]] = <factory>, unary_resources_task_compatibility: dict[~collections.abc.Hashable, set[~collections.abc.Hashable]] = <factory>, unary_resources_task_mode_compatibility: dict[~collections.abc.Hashable, dict[~collections.abc.Hashable, set[int]]] = <factory>, skills: set[~collections.abc.Hashable] = <factory>, non_skill_cumulative_resources: dict[~collections.abc.Hashable, int | list[tuple[int, int, int]]] = <factory>, non_renewable_resources: dict[~collections.abc.Hashable, int] = <factory>, time_windows: dict[~collections.abc.Hashable, tuple[int | None, int | None, int | None, int | None]] = <factory>, start_to_start_min_time_lags: list[tuple[~collections.abc.Hashable, ~collections.abc.Hashable, int]] = <factory>, start_to_end_min_time_lags: list[tuple[~collections.abc.Hashable, ~collections.abc.Hashable, int]] = <factory>, end_to_start_min_time_lags: list[tuple[~collections.abc.Hashable, ~collections.abc.Hashable, int]] = <factory>, end_to_end_min_time_lags: list[tuple[~collections.abc.Hashable, ~collections.abc.Hashable, int]] = <factory>, no_overlap_sets: set[frozenset[~collections.abc.Hashable]] = <factory>, forbidden_intervals: dict[~collections.abc.Hashable, list[tuple[int, int]]] = <factory>, flexible_gap_blocking_constraints: list[~discrete_optimization.generic_tasks_tools.resource_blocking.FlexibleGapBlockingConstraint] = <factory>, span_blocking_constraints: list[~discrete_optimization.generic_tasks_tools.resource_blocking.SpanBlockingConstraint] = <factory>, mode_constraints: list[tuple[~discrete_optimization.generic_tasks_tools.multimode.ModeConstraintType, list[tuple[~collections.abc.Hashable, int]]]] = <factory>, mode_subset_constraints: list[tuple[~discrete_optimization.generic_tasks_tools.multimode.ModeConstraintType, list[tuple[~collections.abc.Hashable, set[int]]]]] = <factory>, same_unary_allocation: list[set[~collections.abc.Hashable]] = <factory>, optional_tasks: set[~collections.abc.Hashable] = <factory>, list_objective_computer: list[~discrete_optimization.generic_tasks_tools.objectives.objective_computer.ObjectiveComputer] = None, alternative_scheduling_subproblems: list[~discrete_optimization.generic_tasks_tools.alternative_subproblems.AlternativeSchedulingSubProblem] = <factory>, calendar_preemptive_tasks: set[~collections.abc.Hashable] = <factory>, exclusion_resource_capacity: dict[~collections.abc.Hashable, int] = <factory>, exclusion_resource_consumptions: dict[~collections.abc.Hashable, dict[int, dict[~collections.abc.Hashable, int]]] = <factory>, exclusion_resource_boolean: dict[~collections.abc.Hashable, dict[int, dict[~collections.abc.Hashable, bool]]] = <factory>, linear_cstrs_presence_tasks: list[tuple[list[tuple[~collections.abc.Hashable, int]], int | None, int | None]] = <factory>, entity_precedence_constraints: dict[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~collections.abc.Iterable[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity]] = <factory>, entity_start_to_start_min_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_start_to_start_max_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_end_to_start_min_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_end_to_start_max_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_end_to_end_min_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_end_to_end_max_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_start_to_end_min_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_start_to_end_max_time_lags: list[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, int]] = <factory>, entity_time_window_bounds: dict[tuple[~discrete_optimization.generic_tasks_tools.entities.SchedulingEntity, ~discrete_optimization.generic_tasks_tools.enums.StartOrEnd], tuple[int | None, int | None]] = <factory>, batch_entities: list = <factory>, task_to_batch_assignment: dict[~collections.abc.Hashable, ~collections.abc.Hashable] = <factory>, batching_data: ~discrete_optimization.generic_tasks_tools.generic_scheduling_impl.BatchingData = <factory>, list_routing_entities: list[~discrete_optimization.generic_tasks_tools.routing.RoutingEntity] = <factory>, list_ordered_routing_entities: list[~discrete_optimization.generic_tasks_tools.routing.OrderedRoutingEntity] = <factory>)[source]
Bases:
GenericSchedulingProblem[Hashable,Hashable,Hashable,Hashable,Hashable,Hashable]Generic implementation of a scheduling problem.
It implements the abstract class GenericSchedulingProblem.
- horizon
max allowed time to finish the tasks
- Type:
int
- durations_per_mode
task -> mode -> duration. Tasks durations, mode by mode. This is used to know all available tasks, all available modes for a given task, and corresponding durations.
- Type:
dict[collections.abc.Hashable, dict[int, int]]
- resource_consumptions
task -> mode -> resource -> conso. Cumulative or non-renewable resource consumption, task by task, mode by mode. The resource can be a skill. Missing key => conso = 0
- Type:
dict[collections.abc.Hashable, dict[int, dict[collections.abc.Hashable, int]]]
- successors
maps a task to its successors in the precedence graph. Each successor task must start after the given task ends. Default to no precedence constraints. Note that a consolidated version of it will be constructed using the time lags constraints.
- Type:
dict[collections.abc.Hashable, set[collections.abc.Hashable]]
- unary_resources
available unary resources. Default to none.
- Type:
set[collections.abc.Hashable]
- unary_resources_skills
skill values of each unary resource. Missing key => skill value = 0
- Type:
dict[collections.abc.Hashable, dict[collections.abc.Hashable, int]]
- unary_resources_availabilities
availability of unary resources on the form of list of intervals (start, end) Missing key => always available.
- Type:
dict[collections.abc.Hashable, list[tuple[int, int]]]
- unary_resources_task_compatibility
maps a task to its compatible unary resources. Missing key => all unary resources allowed.
- Type:
dict[collections.abc.Hashable, set[collections.abc.Hashable]]
- skills
available skills
- Type:
set[collections.abc.Hashable]
- non_skill_cumulative_resources
cumulative resources (excluding skills) availabilities. Format: either int => always available at the given max capacity, or list of intervals + capacity (start, end, value)
- Type:
dict[collections.abc.Hashable, int | list[tuple[int, int, int]]]
- non_renewable_resources
non-renewable resources max capacities
- Type:
dict[collections.abc.Hashable, int]
- time_windows
maps task to start_lb, end_lb, start_ub, end_ub s.t. start_lb <= start(task) <= start_ub and end_lb <= end(task) <= end_ub missing or none value means 0 (lb) or self.horizon (ub)
- Type:
dict[collections.abc.Hashable, tuple[int | None, int | None, int | None, int | None]]
- start_to_start_min_time_lags
min time lags constraints between task starts. task1, task2, offset meaning start(task1) + offset <= start(task2) Note that using negative offset can model start-to-start max time lags.
- Type:
list[tuple[collections.abc.Hashable, collections.abc.Hashable, int]]
- start_to_end_min_time_lags
min time lags constraints first task start and second task end. task1, task2, offset meaning start(task1) + offset <= end(task2) Note that using negative offset can model end-to-start max time lags.
- Type:
list[tuple[collections.abc.Hashable, collections.abc.Hashable, int]]
- end_to_start_min_time_lags
min time lags constraints between first task end and second task start. task1, task2, offset meaning end(task1) + offset <= start(task2) Note that using negative offset can model start-to-end max time lags.
- Type:
list[tuple[collections.abc.Hashable, collections.abc.Hashable, int]]
- end_to_end_min_time_lags
min time lags constraints between task ends. task1, task2, offset meaning end(task1) + offset <= end(task2) Note that using negative offset can model end-to-end max time lags.
- Type:
list[tuple[collections.abc.Hashable, collections.abc.Hashable, int]]
- no_overlap_sets
a set of (set of tasks that should not overlap together)
- Type:
set[frozenset[collections.abc.Hashable]]
- forbidden_intervals
maps task to forbidden intervals that cannot overlap with it. Missing key => no forbidden intervals.
- Type:
dict[collections.abc.Hashable, list[tuple[int, int]]]
- flexible_gap_blocking_constraints
list of blocking constraints between entity points. Each constraint is (entity1, point1, entity2, point2, resources, metadata). Default to no blocking constraints.
- span_blocking_constraints
list of span blocking constraints. Each constraint is (tasks, resources, metadata) where tasks is a frozenset. Default to no blocking constraints.
- alternative_scheduling_subproblems: list[AlternativeSchedulingSubProblem]
- batch_entities: list
- batching_data: BatchingData
- calendar_preemptive_tasks: set[Hashable]
- can_batch_together(task1: Hashable, task2: Hashable) bool[source]
Check if two tasks are compatible for batching together.
Tasks are incompatible if they cannot be in the same batch due to: - Different attributes (e.g., different product types) - Conflicting resource requirements - Incompatible processing characteristics
- Parameters:
task1 – First task
task2 – Second task
- Returns:
True if tasks can be batched together, False otherwise
Default: All tasks are compatible (can batch together).
Example
>>> # Oven scheduling: only same-attribute tasks can batch >>> def can_batch_together(self, task1, task2): ... return self.get_task_attribute(task1) == self.get_task_attribute(task2) >>> >>> # Size-based compatibility >>> def can_batch_together(self, task1, task2): ... return self.task_sizes[task1] + self.task_sizes[task2] <= self.max_batch_size
- can_be_batched(task: Hashable) bool[source]
Check if a task CAN be assigned to a batch.
- Parameters:
task – Task to query
- Returns:
True if task can be in a batch, False if it must run individually
Default: All tasks can be batched.
Example
>>> # Large items cannot be batched >>> def can_be_batched(self, task): ... return self.get_task_size(task) <= self.single_task_threshold
- create_subproblem_from_partial_solution(partial_solution: RawSolution[Hashable, Hashable, Hashable]) GenericSchedulingImplProblem[source]
Create a subproblem according to a partial solution.
Tasks already scheduled are removed from subproblem.
Add time windows constraints to model timelags/precedence constraints with removed tasks.
Update resource calendars with scheduled allocations
Update non-renewable resources max capacities
Transform no_overlap constraints into forbidden intervals constraints
- durations_per_mode: dict[Hashable, dict[int, int]]
- end_to_end_min_time_lags: list[tuple[Hashable, Hashable, int]]
- end_to_start_min_time_lags: list[tuple[Hashable, Hashable, int]]
- entity_end_to_end_max_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_end_to_end_min_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_end_to_start_max_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_end_to_start_min_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_precedence_constraints: dict[SchedulingEntity, Iterable[SchedulingEntity]]
- entity_start_to_end_max_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_start_to_end_min_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_start_to_start_max_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_start_to_start_min_time_lags: list[tuple[SchedulingEntity, SchedulingEntity, int]]
- entity_time_window_bounds: dict[tuple[SchedulingEntity, StartOrEnd], tuple[int | None, int | None]]
variable batch assignment with capacity, compatibility, setup constraints
- Type:
Batching
- exclusion_resource_boolean: dict[Hashable, dict[int, dict[Hashable, bool]]]
Specify custom constraint on presence of tasks
- exclusion_resource_capacity: dict[Hashable, int]
- exclusion_resource_consumptions: dict[Hashable, dict[int, dict[Hashable, int]]]
- property exclusion_resources_list: list[Hashable]
- flexible_gap_blocking_constraints: list[FlexibleGapBlockingConstraint]
- forbidden_intervals: dict[Hashable, list[tuple[int, int]]]
- get_alternative_scheduling_subproblem() list[AlternativeSchedulingSubProblem][source]
- get_attribute_register() EncodingRegister[source]
Returns how the Solution should be encoded.
Useful to find automatically available mutations for local search. Used by genetic algorithms Ga and Nsga.
This needs only to be implemented in child classes when GA or LS solvers are to be used.
Returns (EncodingRegister): content of the encoding of the solution
- get_batch_capacity(batch_id: Hashable) int | float | tuple[int | float, ...][source]
Get capacity of a batch for bin packing.
Batch capacity constrains total size of tasks in batch: sum(get_task_size(task) for task in batch) <= get_batch_capacity(batch)
For multi-dimensional sizes (tuples), capacity is also a tuple and constraint applies element-wise.
- Parameters:
batch_id – Batch identifier
- Returns:
Batch capacity (int, float, or tuple for multi-dimensional)
Default: Infinite capacity (no constraint).
Example
>>> # Oven scheduling: machine has capacity >>> def get_batch_capacity(self, batch_id): ... machine_id = self._get_machine_from_batch(batch_id) ... return self.machines_data[machine_id].capacity >>> >>> # Multi-dimensional: (max_weight, max_volume) >>> def get_batch_capacity(self, batch_id): ... return (self.max_weight, self.max_volume)
- get_batch_duration_bounds(batch_id: Hashable, tasks: frozenset[Hashable]) tuple[int | None, int | None][source]
Get minimum and maximum duration for a batch based on its tasks.
Batch duration depends on tasks assigned to it and batch attribute. This is separate from size bounds (number of tasks).
- Parameters:
batch_id – Batch identifier
tasks – Tasks assigned to this batch
- Returns:
Tuple of (min_duration, max_duration). None means no constraint.
Default: No duration constraints.
Example
>>> # Oven: duration based on task min/max durations >>> def get_batch_duration_bounds(self, batch_id, tasks): ... if not tasks: ... return None, None ... min_dur = max(self.tasks_data[t].min_duration for t in tasks) ... max_dur = min(self.tasks_data[t].max_duration for t in tasks) ... return min_dur, max_dur
- get_batch_entities()[source]
Get all batch entities in the problem.
This is the PRIMARY method - batch entities are created first, before the problem, and stored. This method returns them.
- Returns:
List of VariableBatchEntity instances
Example
>>> def __init__(self, tasks, batch_entities): ... self._tasks = tasks ... self.batch_entities = batch_entities ... >>> def get_batch_entities(self): ... return self.batch_entities
- get_batch_presence_chains() list[list[Hashable]][source]
Get batch presence ordering chains for symmetry breaking.
Returns chains of batches where if batch[i+1] is used, batch[i] must be used. This helps avoid symmetric solutions by enforcing a canonical ordering.
- Returns:
List of batch chains. Each chain is a list of batch IDs in order. Empty list means no presence constraints (all batches independent).
- Example - Single machine (one chain):
>>> def get_batch_presence_chains(self): ... return [self.get_batch_ids()] # All batches in one chain
- Example - Multi-machine (multiple chains):
>>> def get_batch_presence_chains(self): ... # Batches 0-4 for machine 1, batches 5-9 for machine 2 ... return [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
- Example - No presence constraints:
>>> def get_batch_presence_chains(self): ... return [] # Batches can be used in any order
- get_batch_size_bounds(batch_id: Hashable) tuple[int | None, int | None][source]
Get minimum and maximum NUMBER OF TASKS in a batch.
This is about cardinality (count), not weight/capacity. For capacity constraints, use get_task_size() and get_batch_capacity().
- Parameters:
batch_id – Batch identifier
- Returns:
Tuple of (min_size, max_size). None means no constraint.
Default: No size constraints.
- get_cumulative_resource_consumption(resource: Hashable, task: Hashable, mode: int) int[source]
Get cumulative resource consumption of the task in the given mode
- Parameters:
resource – cumulative resource
task
mode – not used for single mode problems
- Returns:
the consumption for cumulative resources.
- get_cumulative_resource_consumption_mapping(resource: Hashable, task: Hashable, mode: int) dict[frozenset[tuple[Hashable, int]], int][source]
Get resource consumption mapping for resource-dependent tasks.
- Parameters:
resource – The cumulative resource
task – The task
mode – The task mode
- Returns:
Mapping from task/mode configurations to consumption values. Keys are frozensets of (task, mode) tuples. Returns None if task has standard (non-dependent) consumption.
Example
>>> mapping = problem.get_cumulative_resource_consumption_mapping( ... "electricity", task_A, 0 ... ) {frozenset([("task_B", 0)]): 100, frozenset([("task_B", 1)]): 80}
- get_dummy_solution() Solution[source]
Create a trivial solution for the problem.
Should satisfy the problem ideally. Does not exist for all kind of problems.
- get_end_to_end_max_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get end-to-end max time lags (encoded as negative min lags).
- get_end_to_end_min_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get min time lags between task ends.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset <= end(task2)
- get_end_to_start_max_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get end-to-start max time lags (encoded as negative min lags).
- get_end_to_start_min_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get min time lags between first task end and second task start.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset <= start(task2)
- get_entity_end_to_end_max_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get max time lags between entity ends.
- Returns:
end(entity1) + offset >= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_end_min_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get min time lags between entity ends.
- Returns:
end(entity1) + offset <= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_start_max_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get max time lags between entity end and start.
- Returns:
end(entity1) + offset >= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_end_to_start_min_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get min time lags between entity end and start.
- Returns:
end(entity1) + offset <= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_precedence_constraints() dict[SchedulingEntity, Iterable[SchedulingEntity]][source]
Get precedence constraints between entities.
- Returns:
Mapping from entity to entities that must follow it. entity1 → [entity2, entity3] means entity1.end <= entity2.start AND entity1.end <= entity3.start
Example
>>> # Project phase must complete before individual task >>> phase1 = GroupEntity(frozenset({t1, t2, t3}), "phase1") >>> task_a = TaskEntity("task_a") >>> return {phase1: [task_a]} # phase1 → task_a
Default: No entity precedence constraints.
- get_entity_start_to_end_max_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get max time lags between entity start and end.
- Returns:
start(entity1) + offset >= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_end_min_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get min time lags between entity start and end.
- Returns:
start(entity1) + offset <= end(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_start_max_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get max time lags between entity starts.
- Returns:
start(entity1) + offset >= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_start_to_start_min_time_lags() list[tuple[SchedulingEntity, SchedulingEntity, int]][source]
Get min time lags between entity starts.
- Returns:
start(entity1) + offset <= start(entity2)
- Return type:
List of (entity1, entity2, offset) where
Default: No constraints.
- get_entity_time_window_lower_bound(entity: SchedulingEntity, start_or_end: StartOrEnd) int | None[source]
Get lower bound on entity start or end time.
- Parameters:
entity – The entity to constrain
start_or_end – Whether constraint applies to start or end
- Returns:
Lower bound (entity time >= bound), or None if no constraint
Example
>>> batch_entity = VariableBatchEntity("batch_1", candidate_tasks) >>> # Batch must start no earlier than time 10 >>> if entity == batch_entity and start_or_end == StartOrEnd.START: ... return 10
Default: No lower bound.
- get_entity_time_window_upper_bound(entity: SchedulingEntity, start_or_end: StartOrEnd) int | None[source]
Get upper bound on entity start or end time.
- Parameters:
entity – The entity to constrain
start_or_end – Whether constraint applies to start or end
- Returns:
Upper bound (entity time <= bound), or None if no constraint
Example
>>> # Batch must complete by time 100 >>> if entity == batch_entity and start_or_end == StartOrEnd.END: ... return 100
Default: No upper bound.
- get_fixed_batches() list[Batch][source]
Get batches with predetermined task membership.
- Returns:
List of Batch objects with fixed task assignment.
Default: No fixed batches.
- get_flexible_gap_blocking_constraints() list[FlexibleGapBlockingConstraint][source]
Return flexible gap blocking constraints.
- get_forbidden_intervals(task: Hashable) list[tuple[int, int]][source]
Get fixed intervals that should not overlap with given task.
Default to empty list. To be overridden in child classes.
- Parameters:
task
- Returns:
List of intervals (start, end) with start <= end (will not be checked)
- get_list_objective_computer() list[ObjectiveComputer][source]
- get_mode_constraints() list[tuple[ModeConstraintType, list[tuple[Hashable, int]]]][source]
An element of the list is a tuple of (ModeConstraintType, list of (task,mode)) that implies the other choice of mode. For example (SORTED_IMPLICATION, [(T1, 1), (T2, 2), (T3, 1)]) means : if T1 is in mode 1, T2 is in mode 2, T3 is in mode 1.. This can be useful to model mode choice that has an influence on the future mode choice. For example, in an assembly line if we choose a given station path for a product, it should stay on it ! if mode_constraint_type == ModeConstraintType.SORTED_IMPLICATION:
then the constraint is not active only when T1 is in mode 1, it should be true if any of the task,mode is active. So if mode(T2)==2 then the other mode are also forced!
- Returns:
- get_mode_subset_constraints() list[tuple[ModeConstraintType, list[tuple[Hashable, set[int]]]]][source]
An element of the list is a tuple of (ModeConstraintType, list of (task,mode)) that implies the other choice of mode. For example (SORTED_IMPLICATION, [(T1, {1, 2}), (T2, {2}), (T3, {1, 3})]) means : if T1 is in mode 1 or 2, T2 is in mode 2, T3 is in mode 1 or 3.. This can be useful to model mode choice that has an influence on the future mode choice. For example, in an assembly line if we choose a given station path for a product, it should stay on it ! if mode_constraint_type == ModeConstraintType.SORTED_IMPLICATION:
then the constraint is not active only when T1 is in mode 1, it should be true if any of the task,mode is active. So if mode(T2)==2 then the other mode are also forced!
- Returns:
- get_no_overlap() set[frozenset[Hashable]][source]
An object in this returned set is a (frozen) set of task, where no task should overlap with another one in this set.
Default to no such sets.
- get_non_renewable_resource_capacity(resource: Hashable) int[source]
Get resource max capacity
- Parameters:
resource
Returns:
- get_non_renewable_resource_consumption(resource: Hashable, task: Hashable, mode: int) int[source]
Get resource consumption of the task in the given mode
- Parameters:
resource – non-renewable resource
task
mode – not used for single mode problems
Returns:.
- Raises:
ValueError – if resource consumption is depending on other variables than mode
- get_non_renewable_resource_consumption_mapping(resource: Hashable, task: Hashable, mode: int) dict[frozenset[tuple[Hashable, int]], int][source]
- get_nr_resource_consumption_when_unary_resource_allocated(task: Hashable, mode: int, resource: Hashable, unary_resource: Hashable)[source]
- get_ordered_routing_entities() list[OrderedRoutingEntity][source]
- get_precedence_constraints() dict[Hashable, Iterable[Hashable]][source]
Map each task to the tasks that need to be performed after it.
- get_resource_availabilities(resource: Hashable) list[tuple[int, int, int]][source]
Get availabilities intervals for a given resource
List of availability intervals of a resource. If the resource is not available, potentially no interval returned.
It is assumed that the intervals are disjunct though.
- Parameters:
resource
- Returns:
list of intervals of the form (start, end, value), which means from time start to time end, there are value of the resource available. NB: the start is included, the end is excluded (start <= t < end)
- get_resource_consumption_when_unary_resource_allocated(task: Hashable, mode: int, resource: Hashable, unary_resource: Hashable)[source]
- get_routing_entities() list[RoutingEntity][source]
- get_same_unary_allocation() list[set[Hashable]][source]
a element (t1, t2, t3..) of this means corresponds to task for which we want the same resource to be allocated. WARNING: To be overriden if meaningful in the problem :return:
- get_solution_type() type[Solution][source]
Returns the class implementation of a Solution.
Returns (class): class object of the given Problem.
- get_span_blocking_constraints() list[SpanBlockingConstraint][source]
Return span blocking constraints.
- get_start_to_end_max_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get start-to-end max time lags (encoded as negative min lags).
- get_start_to_end_min_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get min time lags between first task start and second task end.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning start(task1) + offset <= end(task2)
- get_start_to_start_max_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get start-to-start max time lags (encoded as negative min lags).
- get_start_to_start_min_time_lags() list[tuple[Hashable, Hashable, int]][source]
Get min time lags between tasks starts.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning start(task1) + offset <= start(task2)
- get_task_attribute(task: Hashable) Hashable | None[source]
Get attribute of a task.
Task attribute determines batching compatibility and batch characteristics. Common examples: - Product type/color/recipe in manufacturing - Priority class in scheduling - Resource requirements
- Parameters:
task – Task to query
- Returns:
Task attribute (any hashable type), or None if no attribute concept
Default: No task attributes.
Example
>>> # Oven scheduling: tasks have product types >>> def get_task_attribute(self, task): ... return self.tasks_data[task].attribute # 0, 1, 2, ...
- get_task_mode_duration(task: Hashable, mode: int) int[source]
Get task duration according to mode.
- Parameters:
task
mode – not used for single-mode problems
Returns:
- get_task_modes(task: Hashable) set[int][source]
Retrieve mode found for given task.
- Parameters:
task
Returns:
- get_task_size(task: Hashable) int | float | tuple[int | float, ...][source]
Get size/weight of a task for bin packing.
Task size is used in batch capacity constraints: sum(task_sizes in batch) <= batch_capacity
Size can be: - Scalar: single dimension (weight, volume, processing time) - Tuple: multiple dimensions (weight AND volume)
- Parameters:
task – Task to query
- Returns:
Task size (int, float, or tuple for multi-dimensional)
Default: Size 1 for all tasks.
Example
>>> # Oven scheduling: tasks have physical size >>> def get_task_size(self, task): ... return self.tasks_data[task].size >>> >>> # Multi-dimensional: (weight, volume) >>> def get_task_size(self, task): ... return (self.task_weight[task], self.task_volume[task])
- get_task_start_or_end_lower_bound(task: Hashable, start_or_end: StartOrEnd) int[source]
Get a lower bound on start or end of a given task as specified by the problem.
For tighter computed bounds, see GenericSchedulingProblem.get_tight_task_start_or_end_lower_bound() and GenericSchedulingProblem.compute_task_bounds().
Default implementation: 0
- Parameters:
task
start_or_end
Returns:
- get_task_start_or_end_upper_bound(task: Hashable, start_or_end: StartOrEnd) int[source]
Get an upper bound on start or end of a given task as specified by the problem.
For tighter computed bounds, see GenericSchedulingProblem.get_tight_task_start_or_end_upper_bound() and GenericSchedulingProblem.compute_task_bounds().
Default implementation: makespan upper bound
- Parameters:
task
start_or_end
Returns:
- get_unary_resource_skill_value(unary_resource: Hashable, skill: Hashable) int[source]
Skill value of given resource for given skill.
- horizon: int
- is_batch_optional(batch_id: Hashable) bool[source]
Check if batch can be empty (no tasks assigned).
- Parameters:
batch_id – Batch identifier
- Returns:
True if batch can be empty, False if it must have at least one task
Default: All batches are optional.
- is_compatible_task_mode_unary_resource(task: Hashable, mode: int, unary_resource: Hashable)[source]
- is_compatible_task_unary_resource(task: Hashable, unary_resource: Hashable) bool[source]
Should return False if the unary_resource can never be allocated to task.
This is only a hint used to reduce the number of variables or constraints generated.
Default to True, to be overriden in subclasses.
- is_cumulative_resource_task_mode_consumption_dependent(resource: Hashable, task: Hashable, mode: int) bool[source]
- is_non_renewable_resource_task_mode_consumption_dependent(resource: Hashable, task: Hashable, mode: int) bool[source]
- is_optional(task: Hashable) bool[source]
Whether a task is optional or not.
It means that the task can be ignored in the solution. If absent of the solution, it can also be removed from the constraints.
Default to no optional task.
- is_task_calendar_preempted(task: Hashable) bool[source]
Returns True if the task can calendar preempted To be implemented by subclasses.
- linear_constraints_presence_tasks() list[tuple[list[tuple[Hashable, int]], int | None, int | None]][source]
- linear_cstrs_presence_tasks: list[tuple[list[tuple[Hashable, int]], int | None, int | None]]
precedence, time lags, time windows on any SchedulingEntity
- Type:
Entity constraints
- list_objective_computer: list[ObjectiveComputer] = None
- list_ordered_routing_entities: list[OrderedRoutingEntity]
- list_routing_entities: list[RoutingEntity]
- mode_constraints: list[tuple[ModeConstraintType, list[tuple[Hashable, int]]]]
- mode_subset_constraints: list[tuple[ModeConstraintType, list[tuple[Hashable, set[int]]]]]
- must_be_batched(task: Hashable) bool[source]
Check if a task MUST be assigned to a batch.
- Parameters:
task – Task to query
- Returns:
True if task must be in a batch, False if batching is optional
Default: Batching is optional for all tasks.
Example
>>> # Some products must be batched, others can run individually >>> def must_be_batched(self, task): ... return self.tasks_data[task].requires_batching
- no_overlap_sets: set[frozenset[Hashable]]
- non_renewable_resources: dict[Hashable, int]
- property non_renewable_resources_list: list[Hashable]
Non-renewable resources used by the tasks.
- non_skill_cumulative_resources: dict[Hashable, int | list[tuple[int, int, int]]]
- property non_skill_cumulative_resources_list: list[Hashable]
List of cumulative resources that are not skills.
- optional_tasks: set[Hashable]
- resource_consumptions: dict[Hashable, dict[int, dict[Hashable, int]]]
- resource_consumptions_dependent: dict[Hashable, dict[int, dict[Hashable, dict[frozenset[tuple[Hashable, int]], int]]]]
- same_unary_allocation: list[set[Hashable]]
- set_fixed_attributes(attribute_name: str, solution: Solution) None[source]
Fix some solution attribute.
Useful when applying successively GA on different attribute of the solution, fixing the others.
Should be implemented at least for attributes described by attribute_register.
- Parameters:
attribute_name – an attribute name
solution
Returns:
- skills: set[Hashable]
- property skills_list: list[Hashable]
List of skills needed by tasks and brought by unary resources.
- span_blocking_constraints: list[SpanBlockingConstraint]
- start_to_end_min_time_lags: list[tuple[Hashable, Hashable, int]]
- start_to_start_min_time_lags: list[tuple[Hashable, Hashable, int]]
- successors: dict[Hashable, set[Hashable]]
- task_to_batch_assignment: dict[Hashable, Hashable]
- property tasks_list: list[Hashable]
List of all tasks to schedule or allocate to.
- time_windows: dict[Hashable, tuple[int | None, int | None, int | None, int | None]]
- unary_resource_consumptions_dependent: dict[Hashable, dict[int, dict[Hashable, dict[Hashable, int]]]]
- unary_resources: set[Hashable]
- unary_resources_availabilities: dict[Hashable, list[tuple[int, int]]]
- property unary_resources_list: list[Hashable]
Available unary resources.
It can correspond to employees (rcpsp-multiskill), teams (workforce-scheduling), or a mix of several types.
- unary_resources_skills: dict[Hashable, dict[Hashable, int]]
- unary_resources_task_compatibility: dict[Hashable, set[Hashable]]
- unary_resources_task_mode_compatibility: dict[Hashable, dict[Hashable, set[int]]]
- class discrete_optimization.generic_tasks_tools.generic_scheduling_impl.GenericSchedulingImplSolution(problem: GenericSchedulingImplProblem, raw_sol: RawSolution[Hashable, Hashable, Hashable])[source]
Bases:
GenericSchedulingSolution[Hashable,Hashable,Hashable,Hashable,Hashable,Hashable]Generic implementation of a solution to a scheduling problem.
It implements the abstract class GenericSchedulingSolution.
- copy() Solution[source]
Deep copy of the solution.
The copy() function should return a new object containing the same input as the current object, that respects the following expected behaviour: -y = x.copy() -if do some inplace change of y, the changes are not done in x.
Returns: a new object from which you can manipulate attributes without changing the original object.
- get_choice_of_resource_blocking(blocking_constraint: SpanBlockingConstraint | FlexibleGapBlockingConstraint) int | None[source]
- get_end_time(task: Hashable) int | AbsentValue[source]
Get end time of the task
- Hypothesis:
The returned time can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- get_mode(task: Hashable) int | AbsentValue[source]
Retrieve mode found for given task.
- Hypothesis:
The returned mode can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- get_start_time(task: Hashable) int | AbsentValue[source]
Get start time of the task
- Hypothesis:
The returned time can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- get_task_batch_assignment(task: Hashable) Hashable | None[source]
Get which batch a task is assigned to.
- is_allocated(task: Hashable, unary_resource: Hashable) bool[source]
Return the usage of the unary resource for the given task.
- Parameters:
task
unary_resource
Returns:
- is_present(task: Hashable) bool[source]
Tell whether the task is present in the solution.
It can mean several thing: - scheduling problem: start and end of the task are defined - allocation problem: a ressource has been allocated to the task - multimode: a mode has been chosen for the task - or a mix of it
Sometimes a scheduling allocation problem will allow no resource allocation for present task, it has to be defined problem by problem.
For convenience, a default implementation is provided which assumes that all tasks are present. To be overriden in subclasses.
If and only if this method returns False, the mode, start, and end of the task can have the value AbsentValue.ABSENT.
If the method returns False, the task is removed from all constraints during checks.
- is_skill_used(task: Hashable, unary_resource: Hashable, skill: Hashable) bool[source]
Tell whether the given skill from given unary_resource is used in given task.
If True, self.is_allocated(task, unary_resource) must also be True. If the skill is not needed by the task or not in unary_resource skills, should return False.
- lazy_copy() Solution[source]
This function should return a new object but possibly with mutable attributes from the original objects.
A typical use of lazy copy is in evolutionary algorithms or genetic algorithm where the use of local move don’t need to do a possibly costly deepcopy.
Returns (Solution): copy (possibly shallow) of the Solution
- problem: GenericSchedulingImplProblem
discrete_optimization.generic_tasks_tools.generic_scheduling_utils module
- class discrete_optimization.generic_tasks_tools.generic_scheduling_utils.Objective[source]
Bases:
objectNames of possible objective for a generic scheduling problem.
Will be used by the objective computers and thus be found in - ObjectiveRegister - ParamsObjectiveFunction - problem.evaluate() output keys
- ALLOCATION_CHANGES = 'allocation_changes'
- ALLOCATION_COST = 'allocation_cost'
- CALENDAR_RESOURCES_LEVELS = 'calendar_resources_levels'
Weighted sum of resources levels (i.e. needed capacities), to minimize.
- COST_ON_ALTERNATIVE_SUBPROBLEMS = 'cost_on_alternatives_subproblem'
- CUMUL_COST = 'cumulative_cost'
- CUSTOM = 'custom_objective'
- EARLINESS_ONLY = 'earliness_only'
- EARLINESS_TARDINESS = 'earliness_tardiness'
- MAKESPAN = 'makespan'
Global makespan of the schedule, to minimize.
- MODE_COST = 'mode_cost'
- NB_CAL_PREEMPTED_TASKS = 'nb_cal_preempted_tasks'
- NB_TASKS_ALLOCATED = 'nb_tasks_allocated'
Number of tasks with at least one resource allocated, to maximize.
- NB_TASKS_SCHEDULED = 'nb_tasks_scheduled'
Number of tasks actually scheduled, to maximize (usually).
- NB_UNARY_RESOURCES_USED = 'nb_unary_resources_used'
Number of allocated unary resources, to minimize.
- NON_RENEWABLE_RESOURCES_LEVELS = 'non_renewable_resources_levels'
Weighted sum of non-renewable resources levels (i.e. needed capacities), to minimize.
- ROUTING_COSTS = 'routing_costs'
- SCHEDULE_CHANGES = 'scheduling_changes'
- TARDINESS_ONLY = 'tardiness_only'
- TIME_PENALTY = 'time_penalty'
- WEIGHTED_NB_LATE_TASKS = 'weighted_nb_late_tasks'
- WEIGHTED_NB_LATE_TASKS_BATCH = 'weighted_nb_late_tasks_batch'
- WEIGHTED_SUM_START_OR_END = 'weighted_sum_start_or_end'
- WEIGHTED_SUM_START_OR_END_ENTITIES = 'weighted_sum_start_or_end_entities'
- class discrete_optimization.generic_tasks_tools.generic_scheduling_utils.RawSolution(task_variables: dict[~discrete_optimization.generic_tasks_tools.base.Task, ~discrete_optimization.generic_tasks_tools.generic_scheduling_utils.TaskVariable[~discrete_optimization.generic_tasks_tools.allocation.UnaryResource, ~discrete_optimization.generic_tasks_tools.skill.Skill]], metadata: dict[str, ~typing.Any] = <factory>)[source]
Bases:
Generic[Task,UnaryResource,Skill]Raw format for a generic scheduling solution
Does not inherit from d-o Solution class.
You can do raw_sol_1 | raw_sol_2, it will return another raw solution merging both task_variables dictionaries, but dropping metadata.
.
- metadata: dict[str, Any]
- take_subset(tasks: Container[Task]) RawSolution[Task, UnaryResource, Skill][source]
Take a subset of the solution by keeping only variables associated to given tasks
- Parameters:
tasks – subset of tasks to keep
- Returns:
The raw solution with variables for given tasks. Any metadata is dropped.
- task_variables: dict[Task, TaskVariable[UnaryResource, Skill]]
- class discrete_optimization.generic_tasks_tools.generic_scheduling_utils.TaskVariable(start: int | AbsentValue, end: int | AbsentValue, mode: int | AbsentValue, is_present: bool = True, allocated: dict[~discrete_optimization.generic_tasks_tools.allocation.UnaryResource, set[~discrete_optimization.generic_tasks_tools.skill.Skill]]=<factory>, batch_assignment: Any | None = None, info: dict[str, ~typing.Any]=<factory>)[source]
Bases:
Generic[UnaryResource,Skill]Task characteristics found in a generic scheduling solution.
- allocated: dict[UnaryResource, set[Skill]]
- batch_assignment: Any | None = None
- end: int | AbsentValue
- get_start_or_end(start_or_end: StartOrEnd) int | AbsentValue[source]
- info: dict[str, Any]
- is_present: bool = True
- mode: int | AbsentValue
- start: int | AbsentValue
discrete_optimization.generic_tasks_tools.multimode module
- class discrete_optimization.generic_tasks_tools.multimode.ModeConstraintType(*values)[source]
Bases:
Enum- SORTED_IMPLICATION = 0
- UNORDERED = 1
- class discrete_optimization.generic_tasks_tools.multimode.MultimodeProblem[source]
Bases:
TasksProblem[Task]Class inherited by a solution exposing tasks modes.
- get_mode_constraints() list[tuple[ModeConstraintType, list[tuple[Task, int]]]][source]
An element of the list is a tuple of (ModeConstraintType, list of (task,mode)) that implies the other choice of mode. For example (SORTED_IMPLICATION, [(T1, 1), (T2, 2), (T3, 1)]) means : if T1 is in mode 1, T2 is in mode 2, T3 is in mode 1.. This can be useful to model mode choice that has an influence on the future mode choice. For example, in an assembly line if we choose a given station path for a product, it should stay on it ! if mode_constraint_type == ModeConstraintType.SORTED_IMPLICATION:
then the constraint is not active only when T1 is in mode 1, it should be true if any of the task,mode is active. So if mode(T2)==2 then the other mode are also forced!
- Returns:
- get_mode_subset_constraints() list[tuple[ModeConstraintType, list[tuple[Task, set[int]]]]][source]
An element of the list is a tuple of (ModeConstraintType, list of (task,mode)) that implies the other choice of mode. For example (SORTED_IMPLICATION, [(T1, {1, 2}), (T2, {2}), (T3, {1, 3})]) means : if T1 is in mode 1 or 2, T2 is in mode 2, T3 is in mode 1 or 3.. This can be useful to model mode choice that has an influence on the future mode choice. For example, in an assembly line if we choose a given station path for a product, it should stay on it ! if mode_constraint_type == ModeConstraintType.SORTED_IMPLICATION:
then the constraint is not active only when T1 is in mode 1, it should be true if any of the task,mode is active. So if mode(T2)==2 then the other mode are also forced!
- Returns:
- abstractmethod get_task_modes(task: Task) set[int][source]
Retrieve mode found for given task.
- Parameters:
task
Returns:
- property is_multimode: bool
- property max_number_of_mode: int
- class discrete_optimization.generic_tasks_tools.multimode.MultimodeSolution(problem: Problem)[source]
Bases:
TasksSolution[Task]Class inherited by a solution exposing tasks modes.
- abstractmethod get_mode(task: Task) int | AbsentValue[source]
Retrieve mode found for given task.
- Hypothesis:
The returned mode can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- is_present(task: Task) bool[source]
Tell whether the task is present in the solution.
It can mean several thing: - scheduling problem: start and end of the task are defined - allocation problem: a ressource has been allocated to the task - multimode: a mode has been chosen for the task - or a mix of it
Sometimes a scheduling allocation problem will allow no resource allocation for present task, it has to be defined problem by problem.
For convenience, a default implementation is provided which assumes that all tasks are present. To be overriden in subclasses.
If and only if this method returns False, the mode, start, and end of the task can have the value AbsentValue.ABSENT.
If the method returns False, the task is removed from all constraints during checks.
- problem: MultimodeProblem[Task]
- class discrete_optimization.generic_tasks_tools.multimode.SinglemodeProblem[source]
Bases:
MultimodeProblem[Task]- property default_mode
Default single mode.
To be overriden when default value has more sense with another value (ex: in rcpsp, default mode is 1)
- get_task_modes(task: Task) set[int][source]
Retrieve mode found for given task.
- Parameters:
task
Returns:
- property is_multimode: bool
- property max_number_of_mode: int
- class discrete_optimization.generic_tasks_tools.multimode.SinglemodeSolution(problem: Problem)[source]
Bases:
MultimodeSolution[Task]- get_mode(task: Task) int[source]
Retrieve mode found for given task.
- Hypothesis:
The returned mode can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- problem: SinglemodeProblem[Task]
discrete_optimization.generic_tasks_tools.multimode_scheduling module
- class discrete_optimization.generic_tasks_tools.multimode_scheduling.MultimodeSchedulingProblem[source]
Bases:
SchedulingProblem[Task],MultimodeProblem[Task],Generic[Task]Scheduling problem whose tasks durations depend only on mode.
- class discrete_optimization.generic_tasks_tools.multimode_scheduling.MultimodeSchedulingSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task],MultimodeSolution[Task],Generic[Task]Solution type associated to MultimodeSchedulingProblem.
- problem: MultimodeSchedulingProblem[Task]
- class discrete_optimization.generic_tasks_tools.multimode_scheduling.SinglemodeSchedulingProblem[source]
Bases:
SinglemodeProblem[Task],MultimodeSchedulingProblem[Task]Single mode scheduling problems with fixed task durations.
Utility class simplifying MultimodeSchedulingProblem when single mode only.
- class discrete_optimization.generic_tasks_tools.multimode_scheduling.SinglemodeSchedulingSolution(problem: Problem)[source]
Bases:
SinglemodeSolution[Task],MultimodeSchedulingSolution[Task]Solution for single mode scheduling problem with fixed task durations.
Utility class useful when needing to derive from GenericSchedulingSolution without multi mode to be able to use cpsat auto solver.
discrete_optimization.generic_tasks_tools.no_overlap module
- class discrete_optimization.generic_tasks_tools.no_overlap.NoOverlapProblem[source]
Bases:
SchedulingProblem[Task]Problem with no overlap between tasks: For example for open-shop problem, where the order of each operations is arbitrary, but still no overlap.
- get_forbidden_intervals(task: Task) list[tuple[int, int]][source]
Get fixed intervals that should not overlap with given task.
Default to empty list. To be overridden in child classes.
- Parameters:
task
- Returns:
List of intervals (start, end) with start <= end (will not be checked)
- class discrete_optimization.generic_tasks_tools.no_overlap.NoOverlapSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task]Solution for problem with precedence constraints.
- problem: NoOverlapProblem[Task]
discrete_optimization.generic_tasks_tools.non_renewable_resource module
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.NonRenewableResourceProblem[source]
Bases:
MultimodeAllocationProblem[Task,UnaryResource],Generic[Task,NonRenewableResource,UnaryResource]Base class for problems dealing with non-renewable resources consumed by tasks. Just like CumulativeResourceProblem, it supports two consumption modes:
Standard: Task consumption is fixed by task mode. Example: Task A in mode 1 always consumes 5 units.
Resource-dependent: Task consumption depends on other tasks’ modes. Modeled via a consumption mapping. If the task/mode dont depend on any other task, returns empty condition with the static resource need.
Resource via unary resource allocation : when given unary resource is allocated it consumes a given nr resource.
- abstractmethod get_non_renewable_resource_capacity(resource: NonRenewableResource) int[source]
Get resource max capacity
- Parameters:
resource
Returns:
- abstractmethod get_non_renewable_resource_consumption(resource: NonRenewableResource, task: Task, mode: int) int[source]
Get resource consumption of the task in the given mode
- Parameters:
resource – non-renewable resource
task
mode – not used for single mode problems
Returns:.
- Raises:
ValueError – if resource consumption is depending on other variables than mode
- get_non_renewable_resource_consumption_mapping(resource: NonRenewableResource, task: Task, mode: int) dict[frozenset[tuple[Task, int]], int][source]
- get_non_zero_mode_nr_res_unary(task: Task) list[tuple[int, NonRenewableResource, UnaryResource]][source]
- get_nr_resource_consumption_when_unary_resource_allocated(task: Task, mode: int, resource: NonRenewableResource, unary_resource: UnaryResource)[source]
- get_possible_non_renewable_resource_consumption(resource: NonRenewableResource, task: Task, mode: int) set[int][source]
- get_possible_non_renewable_resource_consumption_all_modes(resource: NonRenewableResource, task: Task) set[int][source]
- is_non_renewable_resource_task_consumption_dependent(resource: NonRenewableResource, task: Task)[source]
- is_non_renewable_resource_task_mode_consumption_dependent(resource: NonRenewableResource, task: Task, mode: int) bool[source]
- abstract property non_renewable_resources_list: list[NonRenewableResource]
Non-renewable resources used by the tasks.
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.NonRenewableResourceSolution(problem: Problem)[source]
Bases:
MultiModeAllocationSolution[Task,UnaryResource],Generic[Task,NonRenewableResource,UnaryResource]- check_all_non_renewable_resource_capacity_constraints() bool[source]
Check capacity constraint on all renewable resources.
- check_non_renewable_resource_capacity_constraint(resource: NonRenewableResource) bool[source]
Check capacity constraint on given renewable resource.
- check_non_renewable_resource_capacity_constraints(resources: Iterable[NonRenewableResource])[source]
- compute_aggregated_non_renewable_resources_consumptions(weights: dict[NonRenewableResource, int] | None = None)[source]
Compute aggregated consumption of each non-renewable resource by the solution.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
- compute_nb_non_renewable_resources_used(weights: dict[NonRenewableResource, int] | None = None) int[source]
Compute number of non-renewable resources used by at least one task.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
Returns:
- compute_non_renewable_resources_consumptions() dict[NonRenewableResource, int][source]
Compute total consumption of each non-renewable resource by the solution.
- get_non_renewable_resource_consumption(resource: NonRenewableResource, task: Task) int[source]
Get resource consumption by given task.
- Parameters:
resource
task
Returns:
- get_non_renewable_resource_consumption_by_unary_allocation(task: Task, resource: NonRenewableResource)[source]
- get_non_renewable_resource_consumption_from_mapping(resource: NonRenewableResource, task: Task) int[source]
- problem: NonRenewableResourceProblem[Task, NonRenewableResource, UnaryResource]
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.NonRenewableResourceWithoutAllocationProblem[source]
Bases:
NonRenewableResourceProblem[Task,NonRenewableResource,None],WithoutAllocationProblem[Task]
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.NonRenewableResourceWithoutAllocationSolution(problem: Problem)[source]
Bases:
NonRenewableResourceSolution[Task,NonRenewableResource,None],WithoutAllocationSolution[Task]
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.WithoutNonRenewableResourceProblem[source]
Bases:
NonRenewableResourceProblem[Task,None,UnaryResource],Generic[Task,UnaryResource]Mixin for problem without non-renewable resources.
To be used has an additional mixin with generic GenericSchedulingProblem.
- get_non_renewable_resource_capacity(resource: NonRenewableResource) int[source]
Get resource max capacity
- Parameters:
resource
Returns:
- get_non_renewable_resource_consumption(resource: NonRenewableResource, task: Task, mode: int) int[source]
Get resource consumption of the task in the given mode
- Parameters:
resource – non-renewable resource
task
mode – not used for single mode problems
Returns:.
- Raises:
ValueError – if resource consumption is depending on other variables than mode
- property non_renewable_resources_list: list[NonRenewableResource]
Non-renewable resources used by the tasks.
- class discrete_optimization.generic_tasks_tools.non_renewable_resource.WithoutNonRenewableResourceSolution(problem: Problem)[source]
Bases:
NonRenewableResourceSolution[Task,None,UnaryResource],Generic[Task,UnaryResource]Mixin for solution without non-renewable resources.
To be used has an additional mixin with generic GenericSchedulingSolution.
- check_all_non_renewable_resource_capacity_constraints() bool[source]
Check capacity constraint on all renewable resources.
- check_non_renewable_resource_capacity_constraint(resource: NonRenewableResource) bool[source]
Check capacity constraint on given renewable resource.
- check_non_renewable_resource_capacity_constraints(resources: Iterable[NonRenewableResource])[source]
- compute_aggregated_non_renewable_resources_consumptions(weights: dict[NonRenewableResource, int] | None = None)[source]
Compute aggregated consumption of each non-renewable resource by the solution.
- Parameters:
weights – optional weights to apply to each resource in the sum. Default to 1.
discrete_optimization.generic_tasks_tools.plot_utils module
- discrete_optimization.generic_tasks_tools.plot_utils.compute_nice_resource_consumption(scheduling_problem: GenericSchedulingProblem, scheduling_sol: GenericSchedulingSolution, list_resources: list[str] | None = None) tuple[dict[int, NDArray[int64]], dict[int, NDArray[int64]]][source]
- discrete_optimization.generic_tasks_tools.plot_utils.compute_resource_consumption(scheduling_problem: GenericSchedulingProblem, scheduling_sol: GenericSchedulingSolution, list_resources: list[str] | None = None, future_view: bool = True) tuple[NDArray[int64], NDArray[int64]][source]
- discrete_optimization.generic_tasks_tools.plot_utils.plot_ressource_view(scheduling_problem: GenericSchedulingProblem, scheduling_sol: GenericSchedulingSolution, list_resource: list[str] | None = None, title_figure: str = '', x_lim: list[int] | None = None, fig: Figure | None = None, ax: NDArray[object_] | None = None) Figure[source]
- discrete_optimization.generic_tasks_tools.plot_utils.plot_task_gantt(scheduling_problem: GenericSchedulingProblem, scheduling_sol: GenericSchedulingSolution, fig: Figure | None = None, ax: Axes | None = None, x_lim: list[int] | None = None, title: str | None = None) Figure[source]
discrete_optimization.generic_tasks_tools.precedence module
- class discrete_optimization.generic_tasks_tools.precedence.PrecedenceProblem[source]
Bases:
TasksProblem[Task]Problem with precedence constraints on tasks.
- get_consolidated_precedence_constraints() dict[Task, set[Task]][source]
Consolidate precedence constraints defined by problem.
In GenericSchedulingProblem it will also take into account time lags constraints. Default implementation is only taking get_precededence_constraints, removing the potential duplicates.
- class discrete_optimization.generic_tasks_tools.precedence.PrecedenceSolution(problem: Problem)[source]
Bases:
TasksSolution[Task]Solution for problem with precedence constraints.
- check_precedence_constraints() bool[source]
Check that all precedence constraints are satisfied.
Returns:
- abstractmethod check_tasks_order(task1, task2) bool[source]
Check whether task1 is performed before task2.
- Parameters:
task1
task2
- Returns:
True if task1 is finished before task2 starts, False else.
- problem: PrecedenceProblem[Task]
- class discrete_optimization.generic_tasks_tools.precedence.WithoutPrecedenceProblem[source]
Bases:
PrecedenceProblem[Task]Utility mixin for problem w/o precedence constraints.
To be used has an additional mixin with generic GenericSchedulingProblem.
discrete_optimization.generic_tasks_tools.precedence_scheduling module
- class discrete_optimization.generic_tasks_tools.precedence_scheduling.PrecedenceSchedulingProblem[source]
Bases:
PrecedenceProblem[Task],SchedulingProblem[Task]Scheduling problem with precedence constraints on tasks.
- class discrete_optimization.generic_tasks_tools.precedence_scheduling.PrecedenceSchedulingSolution(problem: Problem)[source]
Bases:
PrecedenceSolution[Task],SchedulingSolution[Task]Solution for scheduling problem with precedence constraints.
Can implement check_tasks_order by using start and end times.
- check_tasks_order(task1, task2) bool[source]
Check whether task1 is performed before task2.
- Parameters:
task1
task2
- Returns:
True if task1 is finished before task2 starts, False else.
- problem: PrecedenceSchedulingProblem[Task]
discrete_optimization.generic_tasks_tools.resource_blocking module
Resource blocking constraints for scheduling problems.
This module provides mixins for modeling resource blocking during non-execution periods: - Gap blocking: Resources blocked between two entities (e.g., changeover time) - Span blocking: Resources blocked for entire span of task group (e.g., project reservation)
Key features: - Flexible blocking points: START/END of entities (tasks, groups, conditional) - Calendar awareness: RESERVATION (spans unavailable periods) vs ACTIVE (must be available) - Overlap handling: Strategies to avoid double-counting when tasks overlap with blocking
- class discrete_optimization.generic_tasks_tools.resource_blocking.BlockingConstraint(metadata: 'BlockingConstraintMetadata', default_resource_blocked: 'dict[CumulativeResource, int]', choice_resource_blocked: 'dict[int, dict[CumulativeResource, int]]'=<factory>)[source]
Bases:
Generic[CumulativeResource]- choice_resource_blocked: dict[int, dict[CumulativeResource, int]]
- default_resource_blocked: dict[CumulativeResource, int]
- metadata: BlockingConstraintMetadata
- class discrete_optimization.generic_tasks_tools.resource_blocking.BlockingConstraintMetadata(mode: BlockingMode = BlockingMode.RESERVATION, description: str = '', name_choice: str = '')[source]
Bases:
objectMetadata for a blocking constraint.
Resource blocking intervals are ALWAYS ADDITIVE with task consumption. The blocking demand is added on top of task consumption during the blocking period. Users should adjust their blocking demands accordingly: - If a task uses 2 units and blocking adds 1 unit, total consumption = 3 units - Ensure resource capacity can accommodate task + blocking consumption
- mode
Calendar awareness mode controlling interaction with resource availability: - RESERVATION: Blocking can span unavailable periods (nights, weekends).
Resource is reserved even when “OFF”. Enforced without calendar constraints.
- ACTIVE: Blocking only during available periods. Resource must be “ON”.
Enforced with calendar constraints.
- description
Optional human-readable description of the constraint
- Type:
str
- name_choice
- Type:
str
- the name of the underlying choice to be made,
- if choice_resource_blocked is not empty.
- description: str = ''
- mode: BlockingMode = 'reservation'
- name_choice: str = ''
- class discrete_optimization.generic_tasks_tools.resource_blocking.BlockingMode(*values)[source]
Bases:
EnumMode for resource blocking behavior.
- RESERVATION
Resource slot is reserved but doesn’t need to be “ON” or available. Blocking can span periods when resource is unavailable (nights, weekends).
- ACTIVE
Resource must be available/ON during blocking period. Blocking invalid if resource unavailable during any part of the period.
- ACTIVE = 'active'
- RESERVATION = 'reservation'
- class discrete_optimization.generic_tasks_tools.resource_blocking.FlexibleGapBlockingConstraint(metadata: 'BlockingConstraintMetadata', default_resource_blocked: 'dict[CumulativeResource, int]', choice_resource_blocked: 'dict[int, dict[CumulativeResource, int]]'=<factory>, left_entity: 'SchedulingEntity' = <factory>, start_or_end_left_entity: 'StartOrEnd' = <StartOrEnd.START: 'start'>, right_entity: 'SchedulingEntity' = <factory>, start_or_end_right_entity: 'StartOrEnd' = <StartOrEnd.START: 'start'>)[source]
Bases:
BlockingConstraint[CumulativeResource]- left_entity: SchedulingEntity
- right_entity: SchedulingEntity
- start_or_end_left_entity: StartOrEnd = 'start'
- start_or_end_right_entity: StartOrEnd = 'start'
- class discrete_optimization.generic_tasks_tools.resource_blocking.ResourceBlockingProblem[source]
Bases:
CumulativeResourceProblem[Task,CumulativeResource,OtherCalendarResource],Generic[Task,CumulativeResource,OtherCalendarResource]Mixin for problems with resource blocking constraints.
This mixin adds support for two types of blocking: 1. Flexible gap blocking: Block resources from one entity point to another 2. Span blocking: Block resources for entire span of task group
The problem should also inherit from CumulativeResourceProblem to provide resource definitions and capacity constraints.
- get_flexible_gap_blocking_constraints() list[FlexibleGapBlockingConstraint[CumulativeResource]][source]
Return flexible gap blocking constraints. Default to no flexible gap blocking constraints.
- get_span_blocking_constraints() list[SpanBlockingConstraint[CumulativeResource]][source]
Return span blocking constraints.
Each constraint blocks resources for the entire span of a task group: - From: minimum start time of any task in group - To: maximum end time of any task in group
- Returns:
tasks: Frozen set of tasks defining the span
resources: Dict mapping resources to consumption amounts
metadata: Blocking behavior configuration
- Return type:
Default to no span blocking constraints.
- class discrete_optimization.generic_tasks_tools.resource_blocking.ResourceBlockingSolution(problem: Problem)[source]
Bases:
CumulativeResourceSolution[Task,CumulativeResource,OtherCalendarResource],Generic[Task,CumulativeResource,OtherCalendarResource]Mixin for solutions to problems with resource blocking constraints.
Provides methods to: - Compute resource consumption from blocking constraints - Check constraint satisfaction with calendar awareness - Handle overlap between blocking and task execution
Should be mixed with SchedulingSolution subclass. Inherits from MultimodeSolution to ensure get_mode() is always available.
- check_blocking_constraints() bool[source]
Check if all blocking constraints are satisfied.
Mirrors the two-constraint approach from CP-SAT solver:
- Check 1 (RESERVATION constraint - no calendar):
Tasks + ALL blocking (RESERVATION + ACTIVE) <= base capacity
This allows RESERVATION blocking to span unavailable periods
- Check 2 (ACTIVE constraint - with calendar):
Tasks + ACTIVE blocking <= calendar capacity at each time
ACTIVE mode: Validate blocking only occurs during available periods
- Returns:
True if all constraints satisfied, False otherwise
- compute_blocking_consumption(horizon: int, resource: CumulativeResource, blocking_modes: set[BlockingMode] = None) ndarray[source]
Compute resource consumption from all blocking constraints.
Blocking is always ADDITIVE: consumption from blocking is added to task consumption. This means total resource usage = task consumption + blocking consumption.
This method: 1. Computes blocking periods from flexible gap and span constraints 2. Adds blocking consumption for each period (ADDITIVE behavior) 3. Validates ACTIVE mode constraints against resource calendar
- Parameters:
horizon – Time horizon for the schedule
resource – The resource to compute consumption for
blocking_modes – blocking modes to consider
- Returns:
Array of length horizon with blocking consumption at each time point. Note: This is blocking consumption only. Task consumption is computed separately. Total consumption should be verified: task_consumption + blocking_consumption <= capacity
- Raises:
ValueError – If ACTIVE mode blocking spans resource unavailable period
- get_all_resource_blocked(resource_blocking_constraint: BlockingConstraint[CumulativeResource]) dict[CumulativeResource, int][source]
- get_choice_of_resource_blocking(blocking_constraint: SpanBlockingConstraint | FlexibleGapBlockingConstraint) int | None[source]
- get_resource_blocked(resource_blocking_constraint: BlockingConstraint[CumulativeResource], resource: CumulativeResource) int[source]
- is_resource_blocking_active(resource_blocking_constraint: BlockingConstraint[CumulativeResource]) bool[source]
- problem: ResourceBlockingProblem[Task, CumulativeResource, OtherCalendarResource]
- class discrete_optimization.generic_tasks_tools.resource_blocking.SpanBlockingConstraint(metadata: 'BlockingConstraintMetadata', default_resource_blocked: 'dict[CumulativeResource, int]', choice_resource_blocked: 'dict[int, dict[CumulativeResource, int]]'=<factory>, entity: 'SchedulingEntity' = <factory>, remove_individual_task_contrib: 'bool' = False)[source]
Bases:
BlockingConstraint[CumulativeResource]- entity: SchedulingEntity
- remove_individual_task_contrib: bool = False
discrete_optimization.generic_tasks_tools.resource_usage_by_unary module
- class discrete_optimization.generic_tasks_tools.resource_usage_by_unary.CumulativeResourceUsageByUnaryResourceProblem[source]
Bases:
MultimodeAllocationProblem[Task,UnaryResource],CumulativeResourceProblem[Task,CumulativeResource,UnaryResource],Generic[Task,CumulativeResource,UnaryResource]
- class discrete_optimization.generic_tasks_tools.resource_usage_by_unary.CumulativeResourceUsageByUnarySolution(problem: Problem)[source]
Bases:
MultiModeAllocationSolution[Task,UnaryResource],CumulativeResourceSolution[Task,CumulativeResource,UnaryResource]- problem: CumulativeResourceUsageByUnaryResourceProblem[Task, CumulativeResource, UnaryResource]
discrete_optimization.generic_tasks_tools.routing module
- class discrete_optimization.generic_tasks_tools.routing.OrderedRoutingEntity(entities: frozenset[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task]], attributes: list[AttributeEntities], cumul_dimensions: list[CumulDimensions], possible_attributes: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], set[AttributeEntities]], transition_times: numpy.ndarray, cumul_matrix: dict[CumulDimensions, numpy.ndarray], cumul_bounds: dict[CumulDimensions, tuple[int | None, int | None]] = None, has_to_be_visited: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], bool] = None, has_to_be_visited_if_present: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], bool] = None, first_entity: discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task] = None, last_entity: discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task] = None, graph: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], set[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task]]] = None, nb_means: int = 1, list_entities: list[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity] = None)[source]
Bases:
RoutingEntity[Task,AttributeEntities,CumulDimensions]- list_entities: list[SchedulingEntity] = None
- class discrete_optimization.generic_tasks_tools.routing.RoutingEntity(entities: frozenset[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task]], attributes: list[AttributeEntities], cumul_dimensions: list[CumulDimensions], possible_attributes: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], set[AttributeEntities]], transition_times: numpy.ndarray, cumul_matrix: dict[CumulDimensions, numpy.ndarray], cumul_bounds: dict[CumulDimensions, tuple[int | None, int | None]] = None, has_to_be_visited: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], bool] = None, has_to_be_visited_if_present: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], bool] = None, first_entity: discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task] = None, last_entity: discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task] = None, graph: dict[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task], set[discrete_optimization.generic_tasks_tools.entities.SchedulingEntity[Task]]] = None, nb_means: int = 1)[source]
Bases:
Generic[Task,AttributeEntities,CumulDimensions]- attributes: list[AttributeEntities]
- cumul_bounds: dict[CumulDimensions, tuple[int | None, int | None]] = None
- cumul_dimensions: list[CumulDimensions]
- cumul_matrix: dict[CumulDimensions, ndarray]
- entities: frozenset[SchedulingEntity[Task]]
- first_entity: SchedulingEntity[Task] = None
- get_active_entities(solution: EntityConstraintsSolution) set[SchedulingEntity][source]
- get_possible_attributes(scheduling_entity: SchedulingEntity) set[AttributeEntities][source]
- graph: dict[SchedulingEntity[Task], set[SchedulingEntity[Task]]] = None
- has_to_be_visited: dict[SchedulingEntity[Task], bool] = None
- has_to_be_visited_if_present: dict[SchedulingEntity[Task], bool] = None
- property index_attributes
- last_entity: SchedulingEntity[Task] = None
- nb_means: int = 1
- possible_attributes: dict[SchedulingEntity[Task], set[AttributeEntities]]
- transition_times: ndarray
- class discrete_optimization.generic_tasks_tools.routing.RoutingProblem[source]
Bases:
EntityConstraintsProblem[Task]- from_entity_to_ordered_routing_entity: dict[SchedulingEntity, list[OrderedRoutingEntity]] = None
- from_entity_to_routing_entity: dict[SchedulingEntity, list[RoutingEntity]] = None
- get_attribute_of_entity(entity: SchedulingEntity[Task]) AttributeEntities[source]
- get_bounds_cumul_dimension(routing_entity: RoutingEntity, cumul_dimension: CumulDimensions) tuple[int | None, int | None][source]
- get_dynamic_cumul_dimensions_between_entities(cumul_dimension: CumulDimensions, entity_from: SchedulingEntity, attribute_from: int, entity_to: SchedulingEntity, attribute_to: int)[source]
- get_dynamic_setup_time_between_entities(entity_from: SchedulingEntity, attribute_from: int, entity_to: SchedulingEntity, attribute_to: int)[source]
- get_ordered_routing_entities() list[OrderedRoutingEntity][source]
- get_routing_entities() list[RoutingEntity][source]
- get_routing_entity(entity: SchedulingEntity) RoutingEntity[source]
- get_static_setup_time_between_entities(entity_from: SchedulingEntity, entity_to: SchedulingEntity)[source]
- class discrete_optimization.generic_tasks_tools.routing.RoutingSolution[source]
Bases:
EntityConstraintsSolution[Task]- get_attribute_of_entity(scheduling_entity: SchedulingEntity[Task]) AttributeEntities[source]
- get_routing_path(routing_entity: RoutingEntity) list[tuple[int, int, SchedulingEntity[Task]]][source]
Works for mono vehicle only
- problem: RoutingProblem
discrete_optimization.generic_tasks_tools.scheduling module
- class discrete_optimization.generic_tasks_tools.scheduling.SchedulingProblem[source]
Bases:
TasksProblem[Task]Base class for scheduling problems.
A scheduling problems is about finding start and end times to tasks.
- get_last_tasks() list[Task][source]
Get a sublist of tasks that are candidate to be the last one scheduled.
Default to all tasks.
- class discrete_optimization.generic_tasks_tools.scheduling.SchedulingSolution(problem: Problem)[source]
Bases:
TasksSolution[Task]Base class for solution to scheduling problems.
- constraint_on_task_satisfied(task: Task, start_or_end: StartOrEnd, sign: SignEnum, time: int) bool[source]
- get_duration(task: Task) int | AbsentValue[source]
- abstractmethod get_end_time(task: Task) int | AbsentValue[source]
Get end time of the task
- Hypothesis:
The returned time can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- get_max_end_time() int[source]
Get makespan of the solution.
If no tasks are done, will return 0.
Returns:
- get_running_tasks(time: int) list[Task][source]
Extract tasks running at given time.
Optional tasks not “present” (according to is_present()) are removed from the list.
- get_start_or_end_time(task: Task, start_or_end: StartOrEnd) int | AbsentValue[source]
Get the start or end time for a given task.
The returned time can have AbsentValue.ABSENT only if self.is_present(task) is False.
- abstractmethod get_start_time(task: Task) int | AbsentValue[source]
Get start time of the task
- Hypothesis:
The returned time can have AbsentValue.ABSENT only if self.is_present(task) is False.
- Parameters:
task
Returns:
- is_present(task: Task) bool[source]
Tell whether the task is present in the solution.
It can mean several thing: - scheduling problem: start and end of the task are defined - allocation problem: a ressource has been allocated to the task - multimode: a mode has been chosen for the task - or a mix of it
Sometimes a scheduling allocation problem will allow no resource allocation for present task, it has to be defined problem by problem.
For convenience, a default implementation is provided which assumes that all tasks are present. To be overriden in subclasses.
If and only if this method returns False, the mode, start, and end of the task can have the value AbsentValue.ABSENT.
If the method returns False, the task is removed from all constraints during checks.
- problem: SchedulingProblem[Task]
discrete_optimization.generic_tasks_tools.skill module
Module containing mixins for skills.
A skill is a cumulative resource which is attached to a unary resource.
- class discrete_optimization.generic_tasks_tools.skill.SkillProblem[source]
Bases:
CumulativeResourceProblem[Task,Skill|NonSkillCumulativeResource,UnaryResource],Generic[Task,UnaryResource,Skill,NonSkillCumulativeResource,OtherCalendarResource]- compute_skill_availabilities(skill: Skill) list[tuple[int, int, int]][source]
Deduce skill availabilities from unary_resource availabilities and skill values.
- property cumulative_resources_list: list[Skill | NonSkillCumulativeResource]
- abstractmethod get_unary_resource_skill_value(unary_resource: UnaryResource, skill: Skill) int[source]
Skill value of given resource for given skill.
- abstract property non_skill_cumulative_resources_list: list[NonSkillCumulativeResource]
List of cumulative resources that are not skills.
- only_one_skill_per_task: bool = False
Only one skill from each unary resource allocated to a given task can be used for the task.
- abstract property skills_list: list[Skill]
List of skills needed by tasks and brought by unary resources.
- class discrete_optimization.generic_tasks_tools.skill.SkillSolution(problem: Problem)[source]
Bases:
CumulativeResourceGenericSolution[Task,Skill|NonSkillCumulativeResource,UnaryResource],AllocationSolution[Task,UnaryResource],Generic[Task,UnaryResource,Skill,NonSkillCumulativeResource,OtherCalendarResource]- abstractmethod is_skill_used(task: Task, unary_resource: UnaryResource, skill: Skill) bool[source]
Tell whether the given skill from given unary_resource is used in given task.
If True, self.is_allocated(task, unary_resource) must also be True. If the skill is not needed by the task or not in unary_resource skills, should return False.
- problem: SkillProblem[Task, UnaryResource, Skill, NonSkillCumulativeResource, OtherCalendarResource]
- class discrete_optimization.generic_tasks_tools.skill.WithoutSkillProblem[source]
Bases:
SkillProblem[Task,UnaryResource,None,NonSkillCumulativeResource,OtherCalendarResource],Generic[Task,UnaryResource,NonSkillCumulativeResource,OtherCalendarResource]- get_unary_resource_skill_value(unary_resource: UnaryResource, skill: Skill) int[source]
Skill value of given resource for given skill.
- property skills_list: list[Skill]
List of skills needed by tasks and brought by unary resources.
- class discrete_optimization.generic_tasks_tools.skill.WithoutSkillSolution(problem: Problem)[source]
Bases:
SkillSolution[Task,UnaryResource,None,NonSkillCumulativeResource,OtherCalendarResource],Generic[Task,UnaryResource,NonSkillCumulativeResource,OtherCalendarResource]- is_skill_used(task: Task, unary_resource: UnaryResource, skill: Skill) bool[source]
Tell whether the given skill from given unary_resource is used in given task.
If True, self.is_allocated(task, unary_resource) must also be True. If the skill is not needed by the task or not in unary_resource skills, should return False.
discrete_optimization.generic_tasks_tools.solvers_map module
- discrete_optimization.generic_tasks_tools.solvers_map.get_solver_default_arguments(method: type[SolverDO]) dict[str, Any][source]
- discrete_optimization.generic_tasks_tools.solvers_map.look_for_solver(domain: Problem) list[type[SolverDO]][source]
- discrete_optimization.generic_tasks_tools.solvers_map.look_for_solver_class(class_domain: type[Problem]) list[type[SolverDO]][source]
- discrete_optimization.generic_tasks_tools.solvers_map.return_solver(method: type[SolverDO], problem: Problem, **kwargs: Any) SolverDO[source]
discrete_optimization.generic_tasks_tools.timelag module
- class discrete_optimization.generic_tasks_tools.timelag.TimelagProblem[source]
Bases:
SchedulingProblem[Task],Generic[Task]Class for problem having time lags between tasks.
- get_consolidated_time_lags(task1_start_or_end: StartOrEnd, task2_start_or_end: StartOrEnd, min_or_max: MinOrMax) list[tuple[Task, Task, int]][source]
Get consolidated time lags.
The goal is to normalize the time lags list to avoid having duplicates or constraints implied by others. Note that it encompasses - same tuples in one of the lists - (t1, t2, offset) in end_to_start_min_time_lags and (t2, t1, -offset) in start_to_end_max_time_lags - several offsets for the same tasks (t1, t2)
The choices made here to normalize are: 1. keep only positive offsets in max time lags (the others are converted to min time lags) 2. keep only non-negative offsets in min time lags (the others are converted to max time lags) 3. take max(offsets) in min time lags when several offsets are available for the same tasks (t1, t2) 4. take min(offsets) in max time lags when several offsets are available for the same tasks (t1, t2) 5. drop (t1, t2, offset) in max time lag (with offset>0) if (t2, t1, offset’) with offset’>=0 is already in corresponding min time lag
as the latter implies trivially the other
Note that points 1, 4, and 5 amounts to taking min(offsets) on all tuples in max time lags + converted ones from min time lags (t2,t1 -offset), whichever the sign, and drop it if this min(offsets) is non-negative (whhich corresponds to the existence of (t2, t1, offset’) with offset’>=0 in min time lags.
Moreover this method makes the mapping between all methods according to start/end/min/max.
- Parameters:
task1_start_or_end
task2_start_or_end
min_or_max
Returns:
- get_end_to_end_max_time_lags() list[tuple[Task, Task, int]][source]
Get max time lags between task ends.
Default to no max time lags. Should be overriden in child class for problems with max time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset >= end(task2)
- get_end_to_end_min_time_lags() list[tuple[Task, Task, int]][source]
Get min time lags between task ends.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset <= end(task2)
- get_end_to_start_max_time_lags() list[tuple[Task, Task, int]][source]
Get max time lags between first task end and second task start.
Default to no max time lags. Should be overriden in child class for problems with max time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset >= start(task2)
- get_end_to_start_min_time_lags() list[tuple[Task, Task, int]][source]
Get min time lags between first task end and second task start.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning end(task1) + offset <= start(task2)
- get_original_time_lags(task1_start_or_end: StartOrEnd, task2_start_or_end: StartOrEnd, min_or_max: MinOrMax) list[tuple[Task, Task, int]][source]
Maps strt/end/min/max choices to corresponding list of timelags
- Parameters:
task1_start_or_end
task2_start_or_end
min_or_max
Returns:
- get_start_to_end_max_time_lags() list[tuple[Task, Task, int]][source]
Get max time lags between first task start and second task end.
Default to no max time lags. Should be overriden in child class for problems with max time lags.
- Returns:
list of task1, task2, offset meaning start(task1) + offset >= end(task2)
- get_start_to_end_min_time_lags() list[tuple[Task, Task, int]][source]
Get min time lags between first task start and second task end.
Default to no min time lags. Should be overriden in child class for problems with min time lags.
- Returns:
list of task1, task2, offset meaning start(task1) + offset <= end(task2)
- get_start_to_start_max_time_lags() list[tuple[Task, Task, int]][source]
Get max time lags between tasks starts.
Default to no max time lags. Should be overriden in child class for problems with max time lags.
- Returns:
list of task1, task2, offset meaning start(task1) + offset >= start(task2)
- class discrete_optimization.generic_tasks_tools.timelag.TimelagSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task],Generic[Task]Class for solution of problems having time lags between tasks.
- problem: TimelagProblem[Task]
discrete_optimization.generic_tasks_tools.timewindow module
- class discrete_optimization.generic_tasks_tools.timewindow.TimewindowProblem[source]
Bases:
SchedulingProblem[Task],Generic[Task]Class for problem having time windows between tasks.
- get_makespan_lower_bound() int[source]
Get a lower bound on global makespan.
Time windows on last tasks can be used to get a better makespan lower bound.
- get_task_bound(task: Task, start_or_end: StartOrEnd, min_or_max: MinOrMax) int[source]
Get a lower or upper bound on a task start or end.
- Parameters:
task
start_or_end
min_or_max – min -> lower bound, max -> upper bound
Returns:
- get_task_start_or_end_lower_bound(task: Task, start_or_end: StartOrEnd) int[source]
Get a lower bound on start or end of a given task as specified by the problem.
For tighter computed bounds, see GenericSchedulingProblem.get_tight_task_start_or_end_lower_bound() and GenericSchedulingProblem.compute_task_bounds().
Default implementation: 0
- Parameters:
task
start_or_end
Returns:
- get_task_start_or_end_upper_bound(task: Task, start_or_end: StartOrEnd) int[source]
Get an upper bound on start or end of a given task as specified by the problem.
For tighter computed bounds, see GenericSchedulingProblem.get_tight_task_start_or_end_upper_bound() and GenericSchedulingProblem.compute_task_bounds().
Default implementation: makespan upper bound
- Parameters:
task
start_or_end
Returns:
- class discrete_optimization.generic_tasks_tools.timewindow.TimewindowSolution(problem: Problem)[source]
Bases:
SchedulingSolution[Task],Generic[Task]Class for solution of problems having time windows between tasks.
- problem: TimewindowProblem[Task]
discrete_optimization.generic_tasks_tools.utils module
- discrete_optimization.generic_tasks_tools.utils.get_mandatory_methods_to_implement(cls: type[TasksProblem]) dict[str, Callable[[...], Any]][source]
Find methods mandatory to implement when deriving from the given class.
- Parameters:
cls – class to inspect
- Returns:
A dictionary mapping abstract method names to their class methods.
Example
>>> from discrete_optimization.generic_tasks_tools.generic_scheduling import GenericSchedulingProblem >>> get_mandatory_methods_to_implement(GenericSchedulingProblem) {...}
- discrete_optimization.generic_tasks_tools.utils.get_optional_methods_to_override(cls: type[TasksProblem] | TasksProblem, include_subclass_overrides: bool = False) dict[str, Callable[[...], Any]][source]
Find methods likely to be overriden when deriving from the given task problem class.
It finds methods decorated with @optional_override. If the option is activated, it also finds such methods already overriden (including abstract methods).
- Parameters:
cls – The class (or instance) to inspect.
include_subclass_overrides – If True, also includes - methods that overrode an @optional_override method from a parent mixin without re-applying the decorator - methods that overrode an @abstractmethod method from a parent mixin
- Returns:
A dictionary mapping method names to their class methods.
Example
>>> from discrete_optimization.generic_tasks_tools.generic_scheduling import GenericSchedulingProblem >>> optional_methods = get_optional_methods_to_override(GenericSchedulingProblem) >>> optional_methods_including_subclasses = get_optional_methods_to_override(GenericSchedulingProblem, include_subclass_overrides=True) >>> assert len(optional_methods_including_subclasses) > len(optional_methods)
- discrete_optimization.generic_tasks_tools.utils.optional_override(funcobj)[source]
A decorator indicating primitive methods likely to be overriden when creating a new task problem class.
Many tasks mixins are defining abstract methods to be implemented. To reduce the burden when implementing a new tasks problem class, some other primitive methods have a default implementation. Other methods of the mixins are then derived from these primitive methods.
This decorator helps the problem developper to identify such primitive methods with default implementation that he could be interested in overriding.
Note: This does not modify the function behaviour, and is merely used as documentation.