optimaru.bed_allocation¶
Generated from the sources of optimaru/bed_allocation/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.bed_allocation ¶
Bed allocation — Python wrapper of the C++ solver on the optimaru engine.
Department/Room/Bed/Stay/BedPlan/Score/Solver/SolverConfig and
calculate_score come from the compiled C++ core (_core). Stay.bed is the
decision variable::
-1 uninitialized (no score contribution)
0..bed_count()-1 real bed index
bed_count() (no_bed_value) "no bed" — the stay is left unassigned
(penalized at the medium level)
Score convention (three levels, hard / medium / soft): hard is bed/gender/
age/required-equipment violations (0 == feasible), medium is the nights of unassigned
stays (unassigned_stays_cost), soft is preference penalties (room size/specialty/
preferred equipment). Lexicographic comparison (hard first). Internally it maps onto
Score(int64, double) as engine.soft = medium * 10**9 + soft (the domain's medium
fold; level order preserved).
The constraints and their defaults (level, weight in units of that level) live in the C++
components; constraint_info() reports them and list_constraints() lists the names::
{row.name: (row.default_level, row.default_weight) for row in ba.constraint_info()}
# {'bed_conflict_cost': ('hard', 1000.0), ..., 'unassigned_stays_cost': ('medium', 1.0), ...}
The high-level entry point is solve::
import optimaru.bed_allocation as ba
from optimaru.bed_allocation.demo import generate_demo_data
plan = generate_demo_data() # models.BedPlanModel
result = ba.solve(plan, 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.bed_allocation.models.
optimaru.bed_allocation.models ¶
Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.
Mirrors _core's Department/Room/Bed/Stay/BedPlan 1:1, but in a
JSON-friendly shape: references are id strings (department_id/room_id/bed_id) and
dates are datetime.date. The engine conversion (to_core) turns ids into indices and
dates into integer days (day ordinals)::
from optimaru.bed_allocation.models import BedPlanModel
model = BedPlanModel.model_validate_json(payload) # JSON -> pydantic
plan = model.to_core() # pydantic -> engine
...solve...
solved = BedPlanModel.from_core(plan) # engine -> pydantic
stays[i].bed_id is the assigned bed id, or None when unassigned (including "no bed").
DepartmentModel ¶
Bases: StrictModel
A department. specialty_to_priority holds the specialties the department offers and their priority (1 == highest).
RoomModel ¶
Bases: StrictModel
A room. gender_limitation: ANY_GENDER / MALE_ONLY / FEMALE_ONLY / SAME_GENDER (concurrent patients in one room must share a gender).
BedModel ¶
Bases: StrictModel
A bed (the value a stay is assigned).
StayModel ¶
Bases: StrictModel
One patient stay. bed_id is the decision variable
(None == unassigned).
BedPlanModel ¶
Bases: StrictModel
Mirror of BedPlan (the whole problem and its solution). score_* are read-only results, kept as separate fields.
to_core ¶
to_core() -> _core.BedPlan
pydantic -> engine object (id references to indices, dates to day ordinals; the score field is ignored since the engine recomputes it). bed_id None becomes uninitialized (-1) — the solver decides the assignment.
from_core
classmethod
¶
from_core(plan: BedPlan) -> BedPlanModel
engine object -> pydantic (including the current assignment and score). Values that are not real beds (-1 uninitialized, the "no bed" sentinel) become bed_id None.
BedPlanRequest ¶
Bases: SolveRequest
The bed plan with the settings of one solve (see SolveRequest for those).
parameter_uses ¶
parameter_uses(plan: BedPlanModel) -> list[ParameterUse]
The parameters plan sets away from their defaults that act only through a cost.
solve refuses a model whose selection 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 room's gender_limitation needs the cost of its value.
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 BedPlanModel, or a plain dict of that shape
(the JSON the API returned). Stays are matched by id. A stay 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.
A "no bed" stay has no bed id, so from_core reports it as bed_id None and it
comes back here as unassigned: construction places it again, on a bed or on "no
bed" whichever scores best.
Raises ValueError naming the stay for an unknown or repeated stay id and for an unknown bed id (the engine does not range-check).
solve_request ¶
solve_request(request: BedPlanRequest, *, constraints=None) -> BedPlanModel
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.bed_allocation.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (ba.solve(plan)) enables all twelve constraints at their 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(plan, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.bed_allocation as ba
from optimaru.bed_allocation.constraints import (
BedConflictCost, DepartmentSpecialtyCost, UnassignedStaysCost, get_constraints,
)
ba.solve(plan, constraints=get_constraints()) # the defaults as-is
ba.solve(plan, constraints=[ # picked
BedConflictCost(), UnassignedStaysCost(), DepartmentSpecialtyCost(weight=40),
])
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: bed_conflict_cost is
BedConflictCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost, in units of its level.None= the component default (ba.constraint_info()reports them; the plan carries none).levelNone= the default level, otherwise aLevelor its name (Level.MEDIUMor"medium"). Any flippable constraint may take any of the three levels.UnassignedStaysCostis the one MEDIUM constraint by default:level="hard"makes it one hard unit per night andlevel="soft"one soft unit per night (outside the 10^9 medium fold), in the solver and in :func:scorealike. Aweightis in units of the level in effect.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent, per bed for the unit constraints and on the single total for the globalMixedGenderRoomCost. 2.0 = squared, so concentrated violations grow much costlier.offset(keyword) shifts that shaping, at the same granularity; 0.0 = none.clip(keyword)True(the default) counts only what lies beyond the offset,max(0, c - offset) ** exponent;Falseshapesc - offsetas it is, so a unit below the offset lowers the penalty. The literal form charges every unit the constraint evaluates, a raw 0 included: every real bed (an empty one included, never the "no bed" sentinel) for the per-bed constraints, only the sentinel forUnassignedStaysCost, and the one total forMixedGenderRoomCost; aconstraint_costs()entry lists its evaluated units as"units". With an offset it is refused on hard (the seven hard 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 unassigned nights on the medium level, plus the square of those beyond 10 (on the sentinel's total, the scoped unit)::
ba.solve(plan, constraints=[
*[spec for spec in get_constraints() if spec.name != "unassigned_stays_cost"],
UnassignedStaysCost(),
UnassignedStaysCost(exponent=2, offset=10),
])
ba.constraint_costs(plan.to_core(), picks) keys the second pick "unassigned_stays_cost#2".
Names (name) are the C++ component names in snake_case
(BedConflictCost -> bed_conflict_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
ba.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.
BedConflictCost
dataclass
¶
FemaleInMaleRoomCost
dataclass
¶
MaleInFemaleRoomCost
dataclass
¶
MixedGenderRoomCost
dataclass
¶
Bases: Constraint
Nights in which men and women share a SAME_GENDER room. Default: hard, weight 1000.
The pairing is per room while the calculator's unit is the bed, so this is a global constraint.
DepartmentMinAgeCost
dataclass
¶
Bases: Constraint
Nights a patient below the department minimum age spends there. Default: hard, weight 100.
DepartmentMaxAgeCost
dataclass
¶
Bases: Constraint
Nights a patient above the department maximum age spends there. Default: hard, weight 100.
RequiredPatientEquipmentCost
dataclass
¶
Bases: Constraint
Room assignments missing required equipment. Default: hard, weight 50.
If the room lacks any required equipment, it is valued by the number of required equipment items the room has (so a room with none of the required equipment costs 0); the tests pin these semantics.
UnassignedStaysCost
dataclass
¶
Bases: Constraint
Nights spent on the "no bed" sentinel. Default: medium, weight 1 (medium units).
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.
PreferredMaxRoomCapacityCost
dataclass
¶
Bases: Constraint
Nights spent in a room larger than the preferred capacity. Default: soft, weight 8.
DepartmentSpecialtyCost
dataclass
¶
Bases: Constraint
Nights spent in a department that does not offer the specialty at all. Default: soft, weight 10.
DepartmentSpecialtyPriorityCost
dataclass
¶
Bases: Constraint
Nights spent in a department offering the specialty only at priority > 1. Default: soft, weight 10.
Valued by (priority - 1). A department not offering the specialty at all is already
valued by department_specialty_cost, so this stays silent.
PreferredPatientEquipmentCost
dataclass
¶
Bases: Constraint
Nights spent in a room missing preferred equipment. Default: soft, weight 50.
Valued by the number of preferred equipment items the room lacks.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all twelve default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([BedConflictCost(), DepartmentSpecialtyCost(weight=40)])
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 ba.constraint_costs(plan) 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 = ba.constraint_costs(plan)
score(raw) # default set
score(raw, [BedConflictCost(), UnassignedStaysCost(weight=3)])
score(raw, [UnassignedStaysCost(), UnassignedStaysCost(exponent=2, offset=10)])
No solver and no search are involved. The arithmetic matches the engine —
each unit 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 plan scored by
the same constraints.
optimaru.bed_allocation._core ¶
Type stubs for optimaru.bed_allocation._core — the bed-allocation C++ solver.
The compiled module wraps the C++ domain in optimaru/bed_allocation/cpp,
which imports the generic engine in core/optimaru.
The only decision variable is Stay.bed (assignment-shape int)::
-1 uninitialized (no score contribution)
0..bed_count()-1 real bed index
bed_count() == no_bed_value() "no bed" sentinel — the stay is left
unassigned; penalized per night at the
medium level
Score convention (hard / medium / soft levels; all penalties), at the default weights (the C++ components' kDefaultWeight, see constraint_info()): hard 1. bed_conflict_cost overlapping nights in one bed x -1000 hard 2. female_in_male_room_cost female in a MALE_ONLY room, nights x -50 hard 3. male_in_female_room_cost male in a FEMALE_ONLY room, nights x -50 hard 4. mixed_gender_room_cost mixed overlapping nights in a SAME_GENDER room x -1000 (global) hard 5. department_min_age_cost below department minimum age, nights x -100 hard 6. department_max_age_cost above department maximum age, nights x -100 hard 7. required_patient_equipment_cost room short of required equipment: nights x (required equipment the room HAS) x -50 (so a room with none costs 0) medium 8. unassigned_stays_cost nights of "no bed" stays x -1 (medium units) soft 9. preferred_max_room_capacity_cost room above preferred capacity, nights x -8 soft 10. department_specialty_cost specialty not offered by the department, nights x -10 soft 11. department_specialty_priority_cost priority p > 1: nights x (p-1) x -10 soft 12. preferred_patient_equipment_cost nights x (missing preferred equipment) x -50
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/ba/model/domain.hpp for the exact rules). Medium weights are in medium units:
unassigned_stays_cost's default weight is 1, not 10**9.
Score ¶
Hard / medium / soft score. hard 0 == feasible. Lexicographic comparison (hard first).
Department ¶
Problem fact: a department. minimum_age/maximum_age None == no limit.
Room ¶
Problem fact: a room. department is an index into BedPlan.departments.
Bed ¶
Problem fact (the value a stay is assigned): a bed. room is an index into BedPlan.rooms.
Stay ¶
One patient stay. bed is the decision variable
(see the encoding in the module docstring), written by the solver. Dates are integer
day indices (only differences matter; night_count = departure - arrival + 1).
BedPlan ¶
The whole problem and its solution. solve changes the stays' bed and score in
place.
Note: list attributes such as stays return copies, so use set_assignment
to change assignments.
set_assignment ¶
set_assignment(assignment: list[int]) -> None
Bulk-write the decision variable (stays returns copies, so writing
individual elements has no effect).
SolverConfig ¶
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = automatic: clamp(8 * stays, 8000, 12000). The first stage's length: the search restarts with a doubled history when it stalls and the next stage fits in the budget. A solve that starts from a given solution keeps this one length.
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).
nearby_probability
instance-attribute
¶
nearby_probability: float
Biases swap partners / related ruin toward stays with nearby date ranges. 0 disables nearby selection.
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.
Solver ¶
solve ¶
solve(plan: BedPlan) -> None
Solves in place: fills stays[*].bed and plan.score. Every stay ends with a real bed or the "no bed" sentinel value (never -1).
solve_with_constraints ¶
solve_with_constraints(plan: BedPlan, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.bed_allocation.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. plan.score reports the three levels the assembly put the terms on (unassigned_stays_cost with level="soft" lands on soft, a soft constraint with level="medium" on medium), and so does every score passed to on_new_best.
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_score ¶
calculate_score(plan: BedPlan) -> Score
Full recompute of the hard / medium / soft score (also stored in plan.score).
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case: the unit constraints, then the global mixed_gender_room_cost). The same names optimaru.bed_allocation.constraints uses.
constraint_costs ¶
constraint_costs(plan: BedPlan, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw per-unit 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}}}. Units are the assignable values
(beds in order, then the "no bed" sentinel); a global constraint has one entry. A unit
constraint's "units" lists the units it evaluates, where a literal offset (clip=False)
charges a raw 0: the real beds for the per-bed constraints (never the sentinel),
[no_bed_value()] for unassigned_stays_cost. 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 "medium_fold is on EVERY entry (the fold belongs to the domain), and
optimaru.bed_allocation.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; unassigned_stays_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.