optimaru.quadratic_assignment¶
Generated from the sources of optimaru/quadratic_assignment/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.quadratic_assignment ¶
Quadratic assignment — Python wrapper of the C++ solver on the optimaru engine.
Place n facilities on n locations, one each, minimizing the flow between every
pair of facilities times the distance between their locations (plus an optional
direct facility-location cost), with pinned and forbidden placements and
location capacities as hard constraints. One assignment-shape decision variable
(Facility.location) per facility; the search only swaps two facilities'
locations, so every state is a permutation.
Score, at the default weights (all 1): hard = -(pinned locations not holding their facility + facilities at a forbidden location + demand above location capacities) soft = -(direct assignment cost + flow-distance cost) The problem carries no weights: change one through a constraint selection, e.g.::
picks = [FlowDistanceCost(weight=2) if spec.name == "flow_distance_cost" else spec for spec in get_constraints()]
solve(problem, constraints=picks)
See optimaru.quadratic_assignment.constraints; constraint_info() lists every constraint with its
default level and weight.
Basic usage::
import optimaru.quadratic_assignment as qap
from optimaru.quadratic_assignment.models import QuadraticAssignmentProblemModel
problem = QuadraticAssignmentProblemModel.model_validate(data)
problem = qap.solve(problem, time_limit_seconds=5.0, random_seed=42) # a new, solved model
core = problem.to_core(); qap.solve(core) # or the engine object, solved in place
solve, calculate_score and constraint_costs take the pydantic model or the
engine object (QuadraticAssignmentProblem, models.QuadraticAssignmentProblemModel.to_core()).
On a model, calculate_score and constraint_costs need an assignment that covers
every location (ValueError naming the missing ones); the engine object scores a
partial assignment too (an unassigned facility contributes nothing).
optimaru.quadratic_assignment.models ¶
Pydantic models of the quadratic assignment problem — the canonical JSON contract.
QuadraticAssignmentProblemModel is the JSON contract (facilities and locations
by id); to_core() builds the engine object
(optimaru.quadratic_assignment._core.QuadraticAssignmentProblem, by index) and
from_core() builds the model back, assignment and results included::
core = QuadraticAssignmentProblemModel.model_validate(data).to_core()
quadratic_assignment.solve(core, time_limit_seconds=5)
result = QuadraticAssignmentProblemModel.from_core(core)
quadratic_assignment.solve(model) does the same round trip and returns the result
as a new model; the model passed in is not changed.
QuadraticAssignmentProblemModel ¶
Bases: StrictModel
missing_locations ¶
missing_locations() -> list[str]
The locations assignment leaves empty, in location order.
to_core ¶
to_core() -> _core.QuadraticAssignmentProblem
pydantic -> engine object: ids become indices.
facility_demands / location_capacities become the facility's demand /
the location's capacity (None where the dict has no key: demand 0 / no
limit), fixed_assignments a FixedAssignment list in dict order,
forbidden_assignments a ForbiddenAssignment list as given (repeated rows
kept; scoring counts a pair once). assignment is written into the
facilities' location (a location it leaves out stays empty); an unknown
id or a facility at two locations raises ValueError, with the words of
with_initial_solution. warm_start is copied; the result fields are
ignored (the engine recomputes them).
from_core
classmethod
¶
from_core(problem: QuadraticAssignmentProblem) -> QuadraticAssignmentProblemModel
engine object -> pydantic: the facts, the assignment (in location order;
an empty location is left out), warm_start and — when the assignment is a
full bijection — the results: total_cost from the assignment, and
score_hard / score_soft from the score last computed on the core (None
while the core has not been scored).
QuadraticAssignmentRequest ¶
Bases: SolveRequest
The quadratic assignment problem with the settings of one solve (see SolveRequest for those).
parameter_uses ¶
parameter_uses(problem: QuadraticAssignmentProblemModel) -> list[ParameterUse]
The parameters problem sets away from their defaults that act only through a cost.
quadratic_assignment.solve refuses a selection that holds none of a parameter's costs
(optimaru._constraint.require_costs); the table is in docs/use-cases/README.md
("Parameters and their costs").
with_initial_solution ¶
with_initial_solution(problem, solution)
Return a copy of problem whose search starts from solution.
solution is a solved problem model or a dict of the same shape. Its assignment must map every location to a
different facility: the search only swaps facilities, so a partial assignment raises ValueError.
solve_request ¶
solve_request(request: QuadraticAssignmentRequest, *, constraints=None) -> QuadraticAssignmentProblemModel
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.quadratic_assignment.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (quadratic_assignment.solve(problem)) scores every default
constraint at its default weight. 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.quadratic_assignment as qap
from optimaru.quadratic_assignment.constraints import (
FlowDistanceCost, PinnedAssignmentsCost, get_constraints,
)
problem = qap.solve(problem, constraints=get_constraints()) # defaults as-is
picks = [
FlowDistanceCost(weight=2) if spec.name == "flow_distance_cost" else spec
for spec in get_constraints()
]
problem = qap.solve(problem, constraints=picks) # one default changed
problem = qap.solve(problem, constraints=[PinnedAssignmentsCost(), FlowDistanceCost()]) # picked
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: flow_distance_cost
is FlowDistanceCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (1 for every quadratic-assignment constraint). The problem carries no weights;quadratic_assignment.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:level="medium"raises ValueError.exponentsign-preserving power shapingweight * sign(c) * |c| ** exponent: per location for the three side constraints (pinned, forbidden, capacity), on the single total forAssignmentCostandFlowDistanceCost.offset(keyword) shifts that shaping, per location or on the total; 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 location (or total) below the offset — a raw 0 included — lowers the penalty. The three side constraints are scoped: they evaluate only their locations (PinnedAssignmentsCostthe fixed ones,ForbiddenAssignmentsCostthose named by a forbidden row,LocationCapacityCostthose with a capacity), so a literal offset charges exactly those (constraint_costs()reports them as"units"). With an offset it is refused on hard (the three side constraints by 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 (its level included) and the picks add up. The flow cost plus a steep penalty on what exceeds a budget of 1000::
problem = qap.solve(problem, constraints=[
*(spec for spec in get_constraints() if spec.name != "flow_distance_cost"),
FlowDistanceCost(),
FlowDistanceCost(weight=10, offset=1000),
])
qap.constraint_costs(problem, picks) keys the second pick "flow_distance_cost#2".
Names (name) are the C++ component names in snake_case
(PinnedAssignmentsCost -> pinned_assignments_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
quadratic_assignment.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.
PinnedAssignmentsCost
dataclass
¶
ForbiddenAssignmentsCost
dataclass
¶
LocationCapacityCost
dataclass
¶
AssignmentCost
dataclass
¶
FlowDistanceCost
dataclass
¶
Bases: Constraint
Facility flow multiplied by the distance between their locations. Default: soft, weight 1.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, every default constraint.
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::
picks = [
FlowDistanceCost(weight=2) if spec.name == "flow_distance_cost" else spec
for spec in get_constraints()
]
get_constraints(picks)
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 quadratic_assignment.constraint_costs(problem) returns: per
constraint its raw costs (one per location for the side constraints, one
total for the objectives), before weight, exponent, offset and level rounding.
Fetch it once and rescore with different weights without re-solving::
raw = quadratic_assignment.constraint_costs(problem)
score(raw) # default set
score(raw, [PinnedAssignmentsCost(), FlowDistanceCost(weight=2)])
score(raw, [FlowDistanceCost(), FlowDistanceCost(weight=10, offset=1000)])
No solver and no search are involved. The arithmetic matches the engine —
each evaluated unit (a scoped constraint's "units") 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 for fractional hard weights). 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, and so does
level="medium" (no medium level here).
optimaru.quadratic_assignment._core ¶
Type stubs for optimaru.quadratic_assignment._core — the quadratic-assignment C++
solver.
The problem object holds the solution: each facility's location (an index
into problem.locations, -1 == unassigned) is the single assignment-shape decision
variable. The solver keeps the facilities a permutation of the locations
(swap moves only).
Score (hard/soft, lexicographic), at the default weights: hard = -(pinned locations not holding their facility + facilities at a forbidden location + demand above location capacities), soft = -(direct assignment cost + flow-distance cost). The weights are the C++ components' defaults (constraint_info()); the problem carries none.
Facility ¶
Location ¶
Problem fact: a site that holds one facility.
capacity
instance-attribute
¶
capacity: int | None
location_capacities[id]; None = no capacity limit.
FixedAssignment ¶
One fixed_assignments entry, by index: location must hold facility.
ForbiddenAssignment ¶
One forbidden_assignments row, by index: facility must not stand at
location. Repeated rows are kept; scoring counts a pair once.
QuadraticAssignmentProblem ¶
Problem and solution in one object. NOTE: element access returns copies (use set_assignment for bulk location writes); assigning a fact drops the prepared caches, so the next score or solve re-validates the problem.
assignment_costs
instance-attribute
¶
assignment_costs: list[list[int]] | None
n x n, facility by location; None = no direct assignment cost.
warm_start
instance-attribute
¶
warm_start: bool
Start the next solve from the current assignment, which must be a full bijection (else ValueError); the solve resets it to False. Without it the solve starts from the identity (facility i at location i).
score
property
¶
score: Score | None
The score last computed on this problem (a copy): None until calculate_score() or a solve has scored it. Later writes to the assignment or the facts do not reset it.
is_bijection ¶
is_bijection() -> bool
Every facility at its own location and every location used once.
flow_distance_cost ¶
flow_distance_cost() -> int
sum over assigned facilities a, b of flows[a][b] * distances[loc a][loc b].
assignment_cost ¶
assignment_cost() -> int
sum over assigned facilities f of assignment_costs[f][loc f] (0 without a matrix).
total_cost ¶
total_cost() -> int
The model's total_cost: flow-distance plus direct assignment cost, raw.
assignment ¶
assignment() -> list[int]
Per location, the index of the facility standing there (-1 = empty).
set_assignment ¶
set_assignment(assignment: list[int]) -> None
Bulk write of the decision variable, per location (-1 = empty). A facility named twice or an index out of range raises ValueError; facilities not named become unassigned.
SolverConfig ¶
spent_limit_seconds
instance-attribute
¶
spent_limit_seconds: float
Wall-clock budget (30 s by default). 0 returns the start unchanged.
parallel_solver_count
instance-attribute
¶
parallel_solver_count: int
Independent starts (seed + i each); ignored by solve_with_constraints.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
LATE_ACCEPTANCE: 0 = auto: clamp(8 * facility 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.
entity_tabu_size
instance-attribute
¶
entity_tabu_size: int
ENTITY_TABU: for how many steps a moved facility stays tabu (7 by default; >= 0). ENTITY_TABU accepts only non-worsening swaps (sideways ones blocked on tabu facilities), so it climbs like HILL_CLIMBING.
simulated_annealing_starting_temperature
instance-attribute
¶
simulated_annealing_starting_temperature: tuple[int, float]
SIMULATED_ANNEALING's (hard, soft) starting temperature, cooling to 0 over the solve. (0, 0), the default, = auto: hard 0, soft = simulated_annealing_temperature_fraction x |start soft| (at least 1).
simulated_annealing_temperature_fraction
instance-attribute
¶
simulated_annealing_temperature_fraction: float
The auto temperature's fraction of the start's |soft| (0.01 by default; > 0).
great_deluge_water_level_step
instance-attribute
¶
great_deluge_water_level_step: tuple[int, float]
GREAT_DELUGE: how much the (hard, soft) water level, which starts at the start's score, rises per step. (0, 0), the default, leaves it there: only moves that keep the score at or above the start's are taken.
step_counting_hill_climbing_size
instance-attribute
¶
step_counting_hill_climbing_size: int
STEP_COUNTING_HILL_CLIMBING: the bar is reset to the current score every this many steps (400 by default; > 0).
record_to_record_start_gap
instance-attribute
¶
record_to_record_start_gap: float
RECORD_TO_RECORD_TRAVEL: the gap below the best score that is still accepted at the start of the solve, as a fraction of the start's |soft| (0.02 by default; >= 0).
record_to_record_end_gap
instance-attribute
¶
record_to_record_end_gap: float
RECORD_TO_RECORD_TRAVEL: the same gap at the end of the solve (0.0 by default; >= 0); the gap shrinks from the start gap to this one.
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 ¶
Identity (or warm-start) start + local search over swap moves (late acceptance by default). Solves IN PLACE: sets facility.location, problem.score and warm_start = False; the result is always a bijection.
solve_with_constraints ¶
solve_with_constraints(problem: QuadraticAssignmentProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.quadratic_assignment.constraints). The given list replaces the default set; None keeps the default set. Single start. 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. There is no medium level: level="medium" raises ValueError.
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_score ¶
calculate_score(problem: QuadraticAssignmentProblem) -> Score
Full recompute of the score at the default constraints (also stores problem.score).
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): pinned_assignments_cost, forbidden_assignments_cost, location_capacity_cost, assignment_cost, flow_distance_cost. The same names optimaru.quadratic_assignment.constraints uses.
constraint_costs ¶
constraint_costs(problem: QuadraticAssignmentProblem, 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" | "soft",
"reward": bool, "level_flippable": bool, "name": str, "label": str,
"default_weight": float, "default_level": str, optionally "units": [int, ...] and "signed": True}},
"level" being the level in effect (the pick's, or the default) and "hard" the same as
level == "hard". "signed" marks an objective whose data holds a negative entry (its
total can be negative, so it cannot be hard). The three side constraints list one
raw cost per location (location order) and are scoped: "units" holds the locations
each evaluates (ascending: the fixed, the forbidden-row and the capacitated
locations), the only ones a literal offset charges; assignment_cost and
flow_distance_cost are global (one total each). 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: the three hard side constraints, then the two soft objectives, all at weight 1, flippable and scored by default (default_enabled).