Skip to content

optimaru.project_job_scheduling

Generated from the sources of optimaru/project_job_scheduling/ and the stubs of its compiled extension. The guide explains the model and the constraints in prose.

optimaru.project_job_scheduling

Project job scheduling (multi-project RCPSP) — Python wrapper of the C++ solver on the optimaru engine.

Project/Resource/ResourceRequirement/ExecutionMode/Job/Allocation/ ProjectJobSchedule/JobType/Score/Solver/SolverConfig and calculate_score come from the compiled C++ core (_core).

The two decisions per allocation (execution mode, delay∈[0, 500)) are one composite-encoded assignment-shape variable Allocation.mode_delay::

-1                                  uninitialized (no resource use;
                                    dates pass through with delay 0/duration 0)
delay * max_mode_count + mode_slot  (real mode index = mode_slot %
                                    the job's mode count)

The dates (predecessors done → start → end) are derived state: calculate_score / Solver.solve recompute them in topological order and fill Allocation.start_date/end_date. SOURCE/SINK allocations are always pinned, and if uninitialized before solving they are fixed to (first mode, delay 0).

Score convention (hard / medium / soft levels), at the default weights: hard 1. non_renewable_resource_capacity_cost use per non-renewable resource above capacity, over the whole horizon hard 2. renewable_resource_capacity_cost use per renewable resource x day above capacity medium 3. project_delay_cost per-project delay (sink end - critical path end, positive only), in days soft 4. makespan_cost the latest sink end date (0 hard == feasible). Lexicographic comparison (hard first). Internally it maps onto Score(int64, double) with the domain's medium fold engine.soft = medium * 10**9 + soft (level order preserved).

The constraints and their defaults (level, weight in units of that level) live in the C++ components; constraint_info() reports them, list_constraints() lists the names and constraint_costs() gives the raw per-constraint costs of a schedule::

{row.name: (row.default_level, row.default_weight) for row in pjs.constraint_info()}
# {'non_renewable_resource_capacity_cost': ('hard', 1.0), ...,
#  'project_delay_cost': ('medium', 1.0), 'makespan_cost': ('soft', 1.0)}

The high-level entry point is solve::

import optimaru.project_job_scheduling as pj
from optimaru.project_job_scheduling.demo import generate_demo_data

schedule = generate_demo_data()                 # models.ProjectJobScheduleModel
result = pj.solve(schedule, time_limit_seconds=10.0, random_seed=42)
print(result.score_hard, result.score_medium, result.score_soft)

The pydantic mirror (for serialization) is in optimaru.project_job_scheduling.models.

optimaru.project_job_scheduling.models

Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.

Mirrors _core's Project/Resource/Job(ExecutionMode)/Allocation/ProjectJobSchedule 1:1, but references are id strings (project_id/resource_id/job_id/execution_mode_id), and precedence lives in each job's successor_job_ids. The engine conversion (to_core) turns ids into indices, successor lists into the allocations' predecessor lists, and (execution_mode_id, delay) into the composite decision value::

from optimaru.project_job_scheduling.models import ProjectJobScheduleModel

model = ProjectJobScheduleModel.model_validate_json(payload)
schedule = model.to_core()                          # pydantic -> engine
...solve...
solved = ProjectJobScheduleModel.from_core(schedule)  # engine -> pydantic

Allocations must be 1:1 with jobs. allocations[i].execution_mode_id None means uninitialized (delay must be None too); the solver decides (mode, delay). SOURCE/SINK allocations are always pinned, and when passed uninitialized the solver fixes them to (first mode, delay 0).

ProjectModel

Bases: StrictModel

A project. release_date is only the reference of the project_delay_cost constraint (critical_path_end = release_date + critical_path_duration) and does not force the start.

ResourceModel

Bases: StrictModel

A resource. Renewable capacity is 'per day', otherwise 'summed over the whole horizon'. project_id None == global resource (always renewable).

ResourceRequirementModel

Bases: StrictModel

How much of one resource one execution mode uses.

ExecutionModeModel

Bases: StrictModel

One execution mode of a job (duration + resource demand).

JobModel

Bases: StrictModel

A job. SOURCE/SINK are the project's start/end milestones, by convention with one execution mode (duration 0). successor_job_ids defines precedence (successor jobs can start once this job ends).

AllocationModel

Bases: StrictModel

The allocation of one job (1:1 with jobs). (execution_mode_id, delay) is the decision pair (both None == uninitialized). start_date/end_date are read-only derived results.

ProjectJobScheduleModel

Bases: StrictModel

The problem and its solution. score_* are read-only results, kept as separate fields.

to_core

to_core() -> _core.ProjectJobSchedule

pydantic -> engine object: id references to indices, job successor lists to allocation predecessor lists, (execution_mode_id, delay) to the composite decision value (ValueError if the predecessor graph has a cycle). score/start/end fields are ignored since the engine recomputes them.

from_core classmethod

from_core(schedule: ProjectJobSchedule) -> ProjectJobScheduleModel

engine object -> pydantic (including the current assignment, derived dates and score). Uninitialized (-1) allocations get execution_mode_id/delay None. Each job's successor_job_ids are filled by inverting the allocation predecessor lists.

ProjectJobScheduleRequest

Bases: SolveRequest

The project job schedule with the settings of one solve (see SolveRequest for those).

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns: a ProjectJobScheduleModel, or a plain dict of that shape (the JSON the API returned). A dict may list only some allocations. Allocations are matched by id. An allocation left out becomes unassigned and the construction heuristic places it, and only it, so a complete solution starts the search exactly from it. problem is not mutated. Pinned allocations, which always include SOURCE and SINK, keep their value on problem, whatever solution says.

Raises ValueError naming the allocation for an unknown or repeated id, for an execution mode that is not one of the job's, for a delay without a mode and for a delay outside 0..delay_range_size - 1 (the engine does not range-check). The derived start_date/end_date are cleared here and the solve fills them in again.

parameter_uses

parameter_uses(model: ProjectJobScheduleModel) -> list[ParameterUse]

The parameters model sets away from their defaults that act only through a cost.

solve refuses a selection that holds none of a parameter's costs (optimaru._constraint.require_costs); the table is "Parameters and their costs" in docs/use-cases/README.md. A resource with renewable=False is read by non_renewable_resource_capacity_cost alone.

solve_request

solve_request(request: ProjectJobScheduleRequest, *, constraints=None) -> ProjectJobScheduleModel

Solve a pydantic request and return the solved problem model.

This is solve(request.model_input, ...) with the request's settings as the keywords of the same names (see SolveRequest), and constraints the selection solve takes. The request is not changed.

optimaru.project_job_scheduling.constraints

Constraint assembly specs — an API for picking the cost function declaratively.

The default path (pjs.solve(schedule)) enables all four constraints at the default weights. This module is the alternative path next to it: pick constraints, change weights, change levels, shape the cost, and pass the list to solve(schedule, constraints=...).

A constraint list reads one way: one class call per constraint::

import optimaru.project_job_scheduling as pjs
from optimaru.project_job_scheduling.constraints import (
    MakespanCost, ProjectDelayCost, RenewableResourceCapacityCost, get_constraints,
)

pjs.solve(schedule, constraints=get_constraints())          # the defaults as-is
pjs.solve(schedule, constraints=[                            # picked
    RenewableResourceCapacityCost(), ProjectDelayCost(), MakespanCost(weight=10),
])

Only listed constraints are scored — leave one out and its term disappears from the score. (The module also carries ready-made default instances: makespan_cost is MakespanCost(), and so on.)

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost, in units of its level. None = the component default (pjs.constraint_info() reports them).
  • level None = the default level, otherwise a Level or its name (Level.MEDIUM or "medium"). Any flippable constraint may take any of the three levels. ProjectDelayCost is a MEDIUM constraint by default: level="hard" makes it one hard unit per day and level="soft" one soft unit per day (outside the 10^9 medium fold), in the solver and in :func:score alike. A weight is in units of the level in effect.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent. All four constraints are global, so it shapes each one's single total. 2.0 = squared, so concentrated violations grow much costlier.
  • offset (keyword) shifts that shaping of the total; 0.0 = none.
  • clip (keyword) True (the default) counts only what lies beyond the offset, max(0, c - offset) ** exponent; False shapes c - offset as it is, so a total below the offset lowers the penalty (a makespan under a target day is rewarded). With an offset it is refused on hard (both resource constraints by default), because hard 0 must mean no violation; medium folds into soft here, so it takes the literal formula.

The same constraint may be picked several times; each pick is scored on its own with its own knobs and the picks add up. The makespan, plus the square of the days beyond day 40::

pjs.solve(schedule, constraints=[
    *get_constraints(),
    MakespanCost(exponent=2, offset=40),
])

pjs.constraint_costs(schedule, picks) keys the second pick "makespan_cost#2".

Names (name) are the C++ component names in snake_case (ProjectDelayCost -> project_delay_cost). The core derives them mechanically, so there is no hand-maintained alias table — check them with pjs.list_constraints(). Module-level instance names use the same snake_case, so they match the strings list_constraints() prints.

Constraint dataclass

Spec selecting one constraint: weight / level / shaping.

Subclasses set the ClassVars: name (the snake_case registry name the core reports in list_constraints(); required), label_en / label_ko (a short title) and description_en / description_ko (one or two sentences on what one unit of raw cost means). An intermediate base that should not need a name passes abstract=True::

class _RouteLimit(Constraint, abstract=True): ...

offset and clip are keyword-only, so the positional order stays weight, level, exponent followed by a subclass's domain parameters. A name must not contain #, which constraint_costs() keys repeated picks with ("<name>#<k>").

params

params() -> dict[str, Any]

The domain parameters: every dataclass field but the five knobs.

Level

Bases: StrEnum

The score level a constraint is charged on. Hard dominates medium, medium dominates soft.

Score

Bases: NamedTuple

Engine-level (hard, soft) from score(). Penalties, so <= 0 without rewards.

A domain with a medium level folds it the way its C++ Score adapter does (into soft, or below hard), so this compares directly with the engine.

NonRenewableResourceCapacityCost dataclass

Bases: Constraint

Total demand on a non-renewable resource above its capacity. Default: hard, weight 1.

Stock that is gone once used, so "when" things run does not matter — the only component that does not read the date chain.

RenewableResourceCapacityCost dataclass

Bases: Constraint

Per (renewable resource, date), total demand of allocations busy that day above capacity. Default: hard, weight 1.

Capacity that recovers daily, so it is purely a question of "when" things run, and it reads the whole date chain.

ProjectDelayCost dataclass

Bases: Constraint

Days by which each project's SINK passes its critical path end. Default: medium, weight 1 (medium units).

Measured from (releaseDate + criticalPathDuration); finishing early costs nothing — only delay counts. The domain folds medium into the engine soft level as medium * 10^9; the fold belongs to the domain (every constraint_costs() entry carries it as medium_fold), so the weight carries no 10^9 factor.

MakespanCost dataclass

Bases: Constraint

Latest SINK end date — when the last project finishes. Default: soft, weight 1.

One penalty for the whole schedule, not per project (a max, not a sum), so pulling in a project that is not last is free in this term. The value is a day index counted from day 0 (release dates do not move it), not a duration.

get_constraints

get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]

Return the cost function. Without arguments, all four default constraints.

When constraints is given, that list is used as-is — only the listed constraints are scored::

get_constraints([RenewableResourceCapacityCost(), MakespanCost(weight=10)])

Same contract as the C++ applyConstraints: an empty list (most likely a filter that came out empty) raises ValueError; a constraint named several times is scored once per pick, each with its own knobs.

score

score(costs: dict, constraints: list[Constraint] | None = None) -> Score

Apply specs to raw constraint costs and produce a score — pure Python.

costs is what pjs.constraint_costs(schedule) returns: per constraint, the raw cost of each unit (before weight, exponent, offset and level rounding). Fetch it once and rescore with different weights without re-solving::

raw = pjs.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [RenewableResourceCapacityCost(), MakespanCost(weight=10)])
score(raw, [MakespanCost(), MakespanCost(exponent=2, offset=40)])

No solver and no search are involved. The arithmetic matches the engine — each total contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per unit before summing (the same order as the engine; rounding the total afterwards gives different values). A second pick of a constraint reads the same raw costs with its own knobs.

When constraints is given, only those constraints are scored — the same semantics as get_constraints. Unknown names raise ValueError.

The returned value is the engine-level (hard, soft): the domain's medium fold (medium_fold on every entry, into soft at 10^9) is applied, so it equals (score.hard, score.medium * 10**9 + score.soft) of a schedule scored by the same constraints.

optimaru.project_job_scheduling._core

Type stubs for optimaru.project_job_scheduling._core — the project-job-scheduling C++ solver.

The compiled module wraps the C++ domain in optimaru/project_job_scheduling/cpp, which imports the generic engine in core/optimaru.

The only decision variable is Allocation.mode_delay (assignment-shape int) — a composite encoding of the two decisions per allocation (execution mode, delay∈[0, delay_range_size))::

-1                                  uninitialized (no resource use;
                                    dates pass through with delay 0/duration 0)
delay * max_mode_count + mode_slot  real mode index = mode_slot %
                                    the job's mode count — every value of
                                    the global range is valid for every
                                    job

The dates (predecessors_done_date → start_date → end_date) are derived state: calculate_score / Solver.solve recompute and fill them in topological order.

Score convention (hard / medium / soft levels; all penalties), at the default weights (the C++ components' kDefaultWeight, see constraint_info()): hard 1. non_renewable_resource_capacity_cost total use per non-renewable resource above capacity: -(excess) (global) hard 2. renewable_resource_capacity_cost use per renewable resource x day above capacity: -(excess) (global) medium 3. project_delay_cost SINK end date - critical path end date (positive only): -(sum of delays) (medium units, global) soft 4. makespan_cost -(latest SINK end date) (global)

Internally the engine uses Score(int64 hard, double soft), mapped as engine.soft = medium * 10**9 + soft (the domain's medium fold, "into_soft" with unit 109; level priority holds while |soft| < 109; see cpp/pjs/model/domain.hpp for the exact rules). Medium weights are in medium units: project_delay_cost's default weight is 1, not 10**9.

Score

Hard / medium / soft score. hard 0 == feasible. Lexicographic comparison (hard first).

is_feasible

is_feasible() -> bool

True when hard >= 0: no hard constraint is violated.

Project

Problem fact: a project. release_date is only the reference of the project_delay_cost constraint (it does not force the start).

critical_path_end_date

critical_path_end_date() -> int

release_date + critical_path_duration.

Resource

Problem fact: a resource. Renewable capacity is per day, otherwise for the whole horizon. project is an index into ProjectJobSchedule.projects, -1 == global (informational — constraints only look at capacity/renewable).

ResourceRequirement

Resource demand of an execution mode. resource is an index into ProjectJobSchedule.resources.

ExecutionMode

One execution mode of a job (duration + resource demand).

Job

Problem fact: a job. project is an index; every job needs at least one execution mode (SOURCE/SINK have one zero-duration mode by convention).

Allocation

The allocation of one job (1:1 with jobs). mode_delay is the decision variable (see the encoding in the module docstring), written by the solver. predecessor_allocations are predecessor allocation indices (must be acyclic). SOURCE/SINK allocations are always pinned; pinned also fixes a STANDARD one.

ProjectJobSchedule

The problem and its solution. The constructor validates the instance (index ranges, jobs without modes, predecessor graph cycles -> ValueError). solve changes the allocations' mode_delay, the derived dates and score in place.

Note: list attributes such as allocations return copies, so use set_assignment to change assignments.

value_count

value_count() -> int

delay_range_size * max_mode_count (size of the assignment-shape value range).

encode_value

encode_value(delay: int, mode_slot: int) -> int

delay * max_mode_count + mode_slot. A job's mode index is always a valid slot.

execution_mode_index_of_value

execution_mode_index_of_value(allocation: int, value: int) -> int

slot % the job's mode count (composite value -> real mode index).

assignment

assignment() -> list[int]

Current mode_delay value per allocation (the solution).

set_assignment

set_assignment(assignment: list[int]) -> None

Bulk-write the decision variable (allocations returns copies, so writing individual elements has no effect).

SolverConfig

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = automatic: clamp(16 * allocations, 400, 3200).

full_assert instance-attribute

full_assert: bool

Full score checks: compares the incremental score to a full recompute after every move (for debugging; very slow).

serial_schedule_moves instance-attribute

serial_schedule_moves: bool

Enable SerialScheduleMove: change the order of the schedule (one allocation's place, a group's, or an execution mode) and place every allocation again in that order, each as early as its predecessors and the renewable resources allow. Without it the search changes one delay or mode at a time and stalls above what the order of the allocations allows.

custom_move_probability instance-attribute

custom_move_probability: float

Cap on how often a step may draw the serial schedule move, which makes a few passes over the schedule where a built-in move changes one value. 1 means no cap.

best_score_limit instance-attribute

best_score_limit: tuple[int, int, int]

Stop early once (hard, medium, soft) is reached. -(263) on medium or soft means no floor on the soft side (only hard is compared), so (0, -(263), -(2**63)) stops at the first feasible solution.

on_new_best instance-attribute

on_new_best: Callable[[int, Score], None] | None

Called with (step, score) on every new best solution, in the same levels as the final schedule.score of the solve method in use.

Solver

solve

solve(schedule: ProjectJobSchedule) -> None

Solves in place: fills allocations[*].mode_delay, the derived dates and schedule.score. Pinned allocations (every SOURCE/SINK + user-pinned STANDARD) keep their values, and uninitialized pinned allocations are first fixed to (first mode, delay 0).

solve_with_constraints

solve_with_constraints(schedule: ProjectJobSchedule, constraints: Iterable[Any] | None = ...) -> None

Score the same solve with a caller-chosen constraint set (see optimaru.project_job_scheduling.constraints). The given list replaces the default set; None keeps the default set. A name may be picked several times: each pick is its own instance with its own knobs, its level included, and the instances add up. schedule.score reports the three levels the assembly put the terms on (a medium constraint with level="soft" lands on soft, a soft one with level="medium" on medium).

ConstraintInfo

Bases: NamedTuple

One constraint-catalog row, read off the C++ default assembly.

calculate_score

calculate_score(schedule: ProjectJobSchedule) -> Score

Full recompute of the hard / medium / soft score; also refreshes the derived dates (predecessors_done_date/start_date/end_date) (also stored in schedule.score).

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case). The same names optimaru.project_job_scheduling.constraints uses.

constraint_costs

constraint_costs(schedule: ProjectJobSchedule, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]

Raw cost of every constraint, before weight/exponent/offset/level: {key: {"costs": [...], "weight": float, "exponent": float, "offset": float, "clip": bool, "global": bool, "level": "hard" | "medium" | "soft", "reward": bool, "level_flippable": bool, "name": str, "label": str, "default_weight": float, "default_level": str, "medium_fold": {"kind": "into_soft", "unit": 1e9}}}. All four constraints are global, so each "costs" list holds the one total, which exponent / offset / clip shape once. None = the default constraints; a pick list (as for solve) scores exactly those picks, each entry carrying its pick's knobs, the k-th pick of a name keyed "#" from the second on. medium_fold is on EVERY entry (the fold belongs to the domain), and optimaru.project_job_scheduling.constraints.score() applies it.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: each component's default level and weight (in units of that level; project_delay_cost is medium, weight 1), whether its level may be flipped, whether it is a reward, and whether it is scored when no constraints are given.