Skip to content

optimaru.bed_allocation (Python)

Hospital bed allocation (PAS), derived from the Timefold Quickstarts bed-allocation example (Apache-2.0; see the repository NOTICE): the pybind11 package of the optimaru/bed_allocation/cpp implementation on the generic C++ engine in core/optimaru/. An assignment-shaped domain that picks one bed (Bed) per stay (Stay).

Install and test

OPTIMARU_USE_CASES=bed_allocation uv sync      # builds only this use case's C++ extension
uv run pytest -q tests/bed_allocation

Usage

from optimaru import bed_allocation as ba
from optimaru.bed_allocation.demo import generate_demo_data

plan = generate_demo_data()          # pydantic BedPlanModel (1 department, 10 rooms, 13 beds, 80 stays)
result = ba.solve(plan, time_limit_seconds=10.0, random_seed=42)
print(result.score_hard, result.score_medium, result.score_soft)
print([s.bed_id for s in result.stays][:5])

Passing a hand-built _core.BedPlan solves it in place. For JSON serialization use optimaru.bed_allocation.models.BedPlanModel (pydantic v2).

JSON in, JSON out

solve_request takes a pydantic request, models.BedPlanRequest: the problem model as model_input, with the settings of the solve under the names of solve's keywords (time_limit_seconds, random_seed, parallel_solver_count, stop_at_first_feasible, full_assert, and solver_parameters for further SolverConfig fields by name). It returns the solved BedPlanModel, as solve(model, ...) does, and leaves the request unchanged. constraints= is the selection solve takes.

from optimaru.bed_allocation import solve_request
from optimaru.bed_allocation.models import BedPlanRequest

request = BedPlanRequest.model_validate_json(text)  # or BedPlanRequest(model_input=model, time_limit_seconds=5.0)
solved = solve_request(request)

Domain and decision variables

Stay.bed is the only decision variable (the engine's assignment shape):

Value Meaning
-1 uninitialized — no score contribution (input state)
0..bed_count()-1 real bed index
bed_count() (= no_bed_value()) "no bed" sentinel — the stay is left unassigned

A stay may be left unassigned: the value range carries one extra sentinel value, so the search can move a stay to "no bed", and that stay is penalized per night at the medium level (unassigned_stays_cost). So hard 0 is always reachable (every hard violation can be resolved by giving up the assignment).

Score mapping (hard / medium / soft -> engine Score)

The domain scores on three levels (hard / medium / soft); the engine only has Score(int64 hard, double soft). The mapping rule (optimaru/bed_allocation/cpp/ba/model/domain.hpp):

engine.hard = hard
engine.soft = medium * 10^9 + soft      # every constraint is a penalty (<= 0) and an integer

While |soft| < 10^9, medium dominates soft lexicographically within a double (exact up to 2^53) — the soft sum is bounded by about 228 x total stay-nights, so it stays exact up to millions of stay-nights. The Python Score exposes all three levels as-is.

The 10^9 is the domain's medium fold (kMediumFold = MediumFold::intoSoft(10^9), declared once in domain.hpp); it is not part of any weight. Every constraint_costs() entry carries it as "medium_fold": {"kind": "into_soft", "unit": 1e9}, and optimaru.bed_allocation.constraints.score() applies it, so score(raw) equals (score.hard, score.medium * 10**9 + score.soft).

Constraints (12 of them)

In list_constraints() order; constraint_info() reports the default level and weight of each from the C++ components (kDefaultLevel / kDefaultWeight):

Level Constraint (Python name) C++ component Default weight Penalty
hard bed_conflict_cost BedConflictCost 1000 overlapping nights in one bed x 1000
hard female_in_male_room_cost / male_in_female_room_cost FemaleInMaleRoomCost / MaleInFemaleRoomCost 50 nights x 50
hard department_min_age_cost / department_max_age_cost DepartmentMinAgeCost / DepartmentMaxAgeCost 100 nights x 100
hard required_patient_equipment_cost RequiredPatientEquipmentCost 50 nights x (required equipment the room has) x 50
medium unassigned_stays_cost UnassignedStaysCost 1 (medium units) nights of "no bed" stays x 1
soft preferred_max_room_capacity_cost PreferredMaxRoomCapacityCost 8 nights x 8
soft department_specialty_cost DepartmentSpecialtyCost 10 nights x 10
soft department_specialty_priority_cost DepartmentSpecialtyPriorityCost 10 nights x (priority-1) x 10
soft preferred_patient_equipment_cost PreferredPatientEquipmentCost 50 nights x (missing preferred equipment) x 50
hard mixed_gender_room_cost (global, last) MixedGenderRoomCost 1000 overlapping mixed-gender nights in a SAME_GENDER room x 1000

Pick, reweight or flip them through optimaru.bed_allocation.constraints (ba.solve(plan, constraints=[BedConflictCost(), UnassignedStaysCost(weight=3), ...])). Every spec takes weight=None (the C++ default, in units of its level), level=None (the default level, otherwise a Level or its name), exponent=1.0 and the keyword-only offset=0.0 / clip=True (clip=True counts only what lies beyond the offset, clip=False shapes x - offset as it is, per evaluated unit, and is refused with an offset on hard, because hard 0 must mean no violation). unassigned_stays_cost is the only medium constraint by default: level="hard" charges one hard unit per night, level="soft" one soft unit per night (outside the 10^9 fold), and an explicit weight is in units of the level in effect. Any constraint may take any of the three levels, so PreferredMaxRoomCapacityCost(level="medium") charges one medium unit per night. A constraint may be picked several times; each pick is its own instance with its own knobs, its level included, the instances add up, and constraint_costs(plan.to_core(), picks) (it takes the engine BedPlan) keys the k-th pick <name>#<k>.

unassigned_stays_cost defaults to weight 1 in medium units, and level="soft" demotes it to soft in the engine as well. The package re-exports ConstraintInfo / constraint_info().

Caveats:

  • required_patient_equipment_cost weighs by the required equipment the room HAS. The filter fires when any required equipment is missing, and the match weight is the count present, not the count missing — a room with none costs 0. Counterintuitive, but intended: the tests pin these semantics.
  • department_specialty_priority_cost applies only when the department offers that specialty. When it does not, the constraint is skipped, and the missing specialty only gets the department_specialty_cost penalty.
  • Dates are integer day indices (models uses datetime.date.toordinal()). night_count = departure - arrival + 1 (arrival and departure day both count).

Demo

optimaru.bed_allocation.demo.generate_demo_data() builds the demo instance: 1 department (3 specialties), 10 rooms, all SAME_GENDER (13 beds), 28 nights, 80 stays (the default seed) laid out sequentially along each room's timeline, with gender/age/equipment distributions drawn from a seeded random.Random. The C++ demo (build/bed_allocation/ba_demo, built as shown in ../README.md) reaches hard 0 / medium 0 (everyone assigned) within 10 s.

Parameters and their costs

A request that sets a field which acts only through a cost, while its constraints leave every such cost out, is refused with ValueError naming the field and the costs to add; a pick at weight 0 counts. models.parameter_uses(model) lists the fields an input sets, and Parameters and their costs has the table. It is checked where the input is the JSON model (solve_request, solve(model)); a compiled problem is solved as given.