optimaru.facility_location¶
Generated from the sources of optimaru/facility_location/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.facility_location ¶
Facility location — Python wrapper of the C++ solver on the optimaru engine.
The facility-location use case: one assignment-shape decision variable
(Consumer.facility, a facility index, -1 = unassigned) picks one facility
per consumer.
Score, at the default weights:
hard = -(sum over used facilities of max(0, assigned demand - capacity)) # facility_capacity_cost
soft = -(2 x setup cost of used facilities # facility_setup_cost
+ 6 x consumer-facility distance) # distance_from_facility_cost
The problem carries no weights: change one through a constraint
selection, e.g. solve(problem, constraints=get_constraints([..., DistanceFromFacilityCost(weight=5)]))
(see optimaru.facility_location.constraints). constraint_info() lists every constraint with its
default level and weight.
Basic usage::
import optimaru.facility_location as fl
problem = fl.FacilityLocationProblem(facilities, consumers)
fl.solve(problem, time_limit_seconds=5.0, random_seed=42)
print(problem.score, problem.total_cost(), problem.total_distance_meters())
The pydantic mirror (for serialization) is in optimaru.facility_location.models.
optimaru.facility_location.models ¶
Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.
Mirrors _core's Location/Facility/Consumer/FacilityLocationProblem 1:1. Use it
to store or transfer the engine shape as-is (debug dumps, regression snapshots,
...)::
from optimaru.facility_location.models import FacilityLocationProblemModel
model = FacilityLocationProblemModel.from_core(problem) # engine -> pydantic
clone = FacilityLocationProblemModel.model_validate_json(model.model_dump_json())
problem2 = clone.to_core() # pydantic -> engine
LocationModel ¶
Bases: StrictModel
Latitude/longitude (degrees). Distance uses the 1 degree = 111 km Euclidean approximation.
FacilityModel ¶
Bases: StrictModel
Candidate facility: a problem fact with a setup cost and a capacity.
ConsumerModel ¶
Bases: StrictModel
Facility is a facility index (-1 = unassigned).
FacilityLocationProblemModel ¶
Bases: StrictModel
Solution mirror. score is a read-only result, kept as a separate field.
The canonical problem carries no constraint weights: weights
come only from constraint selections, and the defaults (setup 2, distance 6)
are the C++ components' (facility_location.constraint_info()).
to_core ¶
to_core() -> _core.FacilityLocationProblem
pydantic -> engine object (the score field is ignored; the engine recomputes it).
from_core
classmethod
¶
from_core(problem: FacilityLocationProblem) -> FacilityLocationProblemModel
engine object -> pydantic (including the current assignment and score).
FacilityLocationRequest ¶
Bases: SolveRequest
The facility location problem with the settings of one solve (see SolveRequest for those).
parameter_uses ¶
parameter_uses(problem: FacilityLocationProblemModel) -> list[ParameterUse]
The parameters problem sets away from their defaults that act only through a cost: none.
Every field a cost reads (setup costs, capacities, demands, locations) is required, and the two corners are read by nothing; the table is "Parameters and their costs" in docs/use-cases/README.md. Kept so every use case answers the same question.
with_initial_solution ¶
with_initial_solution(problem, solution)
Return a copy of problem whose search starts from solution.
solution is a solved problem (FacilityLocationProblemModel.from_core), or a
plain dict of that shape (the JSON the API returned). Consumers are matched by id.
A consumer 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.
facility is a position in facilities, so it is only valid for the same
facilities in the same order: ValueError if solution lists different ones.
Raises ValueError naming the consumer for an unknown or repeated id and for a
facility outside -1..facility_count - 1 (the engine does not range-check).
solve_request ¶
solve_request(request: FacilityLocationRequest, *, constraints=None) -> FacilityLocationProblemModel
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.facility_location.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (fl.solve(problem)) enables all three 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(problem, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.facility_location as fl
from optimaru.facility_location.constraints import (
DistanceFromFacilityCost, FacilityCapacityCost, FacilitySetupCost, get_constraints,
)
fl.solve(problem, constraints=get_constraints()) # the defaults as-is
fl.solve(problem, constraints=[ # picked
FacilityCapacityCost(), DistanceFromFacilityCost(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: facility_capacity_cost
is FacilityCapacityCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (FacilityCapacityCost 1, FacilitySetupCost 2, DistanceFromFacilityCost 6). The problem carries no weights;fl.constraint_info()reports the defaults.levelNone= the default level, otherwiseLevel.HARDorLevel.SOFT(or the names"hard"and"soft"). This use case has no medium level.exponentsign-preserving power shaping per facility:weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier.offset(keyword) shifts that shaping per facility; 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 facility below the offset — an unused one (cost 0) included — lowers the penalty. With an offset it is refused on hard (FacilityCapacityCostby default), because hard 0 must mean no violation.
The same constraint may be picked several times; each pick is scored on its own with its own knobs and the picks add up. Distance plus its square beyond 500 m per facility::
fl.solve(problem, constraints=[
FacilityCapacityCost(),
FacilitySetupCost(),
DistanceFromFacilityCost(),
DistanceFromFacilityCost(weight=0.01, exponent=2, offset=500),
])
fl.constraint_costs(problem, picks) keys the second pick
"distance_from_facility_cost#2".
Names (name) are the C++ component names in snake_case
(FacilityCapacityCost -> facility_capacity_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
fl.list_constraints().
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.
FacilityCapacityCost
dataclass
¶
FacilitySetupCost
dataclass
¶
Bases: Constraint
Setup cost of every facility serving at least one consumer. Default: soft, weight 2.
A step function of "is this facility used", so moving one consumer cannot cross it — that is why the domain carries a separate CloseFacilityMove.
DistanceFromFacilityCost
dataclass
¶
Bases: Constraint
Distance (m) from each assigned consumer to its facility. Default: soft, weight 6.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all three default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored. To change just one default, list the others as they are::
get_constraints([FacilityCapacityCost(), FacilitySetupCost(), DistanceFromFacilityCost(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 fl.constraint_costs(problem) returns: per constraint, the
raw cost of each facility (before weight, exponent, offset and level rounding).
Fetch it once and rescore with different weights without re-solving::
raw = fl.constraint_costs(problem)
score(raw) # default set
score(raw, [FacilityCapacityCost(), DistanceFromFacilityCost(weight=10)])
score(raw, [DistanceFromFacilityCost(), DistanceFromFacilityCost(exponent=2, offset=500)])
No solver and no search are involved. The arithmetic matches the engine —
each facility contributes weight * shape(cost, exponent, offset, clip) and
hard contributions are rounded per facility 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.
optimaru.facility_location._core ¶
Type stubs for optimaru.facility_location._core — the facility-location C++
solver.
The problem object holds the solution: each consumer's facility (an index
into problem.facilities, -1 == unassigned) is the single assignment-shape decision
variable.
Score (hard/soft, lexicographic), at the default weights: hard = -(over-capacity demand summed over used facilities), soft = -(2 * used facilities' setup cost + 6 * consumer->facility meters). The weights are the C++ components' defaults (constraint_info()); the problem carries none.
Location ¶
Facility ¶
Problem fact: a candidate facility with a setup cost and capacity.
Consumer ¶
Demand served by exactly one facility.
facility
instance-attribute
¶
facility: int
The decision variable: index into problem.facilities; -1 == unassigned.
FacilityLocationProblem ¶
Problem and solution in one object. NOTE: facilities / consumers element access
returns copies; use set_assignment for bulk facility writes.
SolverConfig ¶
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(8 * consumer count, 400, 3200). 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.
ruin_recreate_as_move_weight
instance-attribute
¶
ruin_recreate_as_move_weight: float
Destroy-and-repair as an ordinary acceptor-judged move (the engine's ruin_recreate.as_move_weight); one such move costs ~ruinCount * facility count score evaluations. 0 = off.
nearby_probability
instance-attribute
¶
nearby_probability: float
Bias swap partners (and the LNS related ruin) toward geographically close consumers with this probability. 0 = off (uniform-random).
value_recommender_probability
instance-attribute
¶
value_recommender_probability: float
Probability that a change move draws the consumer's new facility from its value_recommender_keep nearest facilities instead of uniformly.
descent_weight
instance-attribute
¶
descent_weight: float
Assignment-shape best-improvement descent strategy: probability a step runs a full nearby-pair descent (~2 * facility count evaluations per sweep) instead of one sampled move. 0 = off.
custom_move_probability
instance-attribute
¶
custom_move_probability: float
Gate on how often a step may draw one of the macro moves (CloseFacilityMove, SwapFacilityMove) instead of a change or a swap; 1 = unrestricted. A solve that starts from nothing draws them on a tenth of this once late acceptance has started over for the first time.
close_facility_moves
instance-attribute
¶
close_facility_moves: bool
Enable the facility-closing macro move: it empties one used facility in a single step, the only way past the setup-cost step function.
close_facility_keep
instance-attribute
¶
close_facility_keep: int
How far down a consumer's distance-ordered facility list the two macro moves look for a new home (SwapFacilityMove for the consumers of the facility it closes). 0 switches both moves off.
close_facility_migrate_probability
instance-attribute
¶
close_facility_migrate_probability: float
Probability that an emptied facility's consumers migrate together to one alternative site instead of being redistributed over the open ones.
swap_facility_moves
instance-attribute
¶
swap_facility_moves: bool
Enable SwapFacilityMove: open a closed facility and close the one that serves its surroundings in a single step; the closed one's consumers go to their nearest facility with room, and the facilities with room take the consumers nearer to them. Without it the search keeps the facilities it first settles on.
best_score_limit
instance-attribute
¶
best_score_limit: tuple[int, float]
(hard, soft): stop early once bestScore >= this. (0, -inf) stops at the first feasible solution.
Solver ¶
Construction heuristic + Late Acceptance local search (+ adaptive ruin-and-recreate). Solves IN PLACE: fills consumer.facility and problem.score.
solve_with_constraints ¶
solve_with_constraints(problem: FacilityLocationProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.facility_location.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, and the instances add up.
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_score ¶
calculate_score(problem: FacilityLocationProblem) -> Score
Full recompute of the score (also stores problem.score).
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): facility_capacity_cost, facility_setup_cost, distance_from_facility_cost. The same names optimaru.facility_location.constraints uses.
constraint_costs ¶
constraint_costs(problem: FacilityLocationProblem, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw per-facility 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}}. 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 "
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: facility_capacity_cost (hard, 1), facility_setup_cost (soft, 2), distance_from_facility_cost (soft, 6); all flippable, none a reward, all scored by default (default_enabled).