optimaru.max_cut¶
Generated from the sources of optimaru/max_cut/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.max_cut ¶
Max-Cut — Python wrapper of the C++ solver on the optimaru engine.
Weighted Max-Cut with fixed vertex sides, same-side and different-side pairs, side-size bounds and an optional balance term: one assignment-shape decision variable (the side, 0 or 1) per vertex; a fixed vertex is pinned and never moves.
Score, at the default weights:
hard = -(fixed vertices off their side + split same-side pairs
+ different-side pairs left together + side-size shortfall/excess)
soft = +(cut weight) # cut_weight_cost is a reward
(partition_imbalance_cost is an opt-in objective: default weight 0.) The
problem carries no weights: change one through a constraint selection, e.g.::
picks = [
PartitionImbalanceCost(weight=2) if spec.name == "partition_imbalance_cost" else spec
for spec in get_constraints()
]
solve(problem, constraints=picks)
See optimaru.max_cut.constraints; constraint_info() lists every constraint with its
default level and weight.
Basic usage::
from optimaru import max_cut
from optimaru.max_cut.models import MaxCutProblemModel
problem = MaxCutProblemModel.model_validate(data)
problem = max_cut.solve(problem, time_limit_seconds=5.0, random_seed=42) # a new, solved model
core = problem.to_core(); max_cut.solve(core) # or the engine object, solved in place
solve, calculate_score and constraint_costs take the pydantic model or the engine
object (MaxCutProblem, models.MaxCutProblemModel.to_core()). calculate_score and
constraint_costs need a complete partition (every vertex on side 0 or 1) and raise
ValueError on a partial one; solve fills in the missing sides.
optimaru.max_cut.models ¶
Pydantic models of the max-cut problem — the canonical JSON contract.
MaxCutProblemModel is the JSON contract (vertices by id); to_core() builds the
engine object (optimaru.max_cut._core.MaxCutProblem, vertices by index) and
from_core() builds the model back, partition and results included::
core = MaxCutProblemModel.model_validate(data).to_core()
max_cut.solve(core, time_limit_seconds=5)
result = MaxCutProblemModel.from_core(core)
max_cut.solve(model) does the same round trip and returns the result as a new
model; the model passed in is not changed.
MaxCutProblemModel ¶
Bases: StrictModel
is_complete ¶
is_complete() -> bool
Whether partition gives every vertex a side (scoring needs a complete partition).
to_core ¶
to_core() -> _core.MaxCutProblem
pydantic -> engine object: ids become vertex indices (positions in vertices).
fixed_partition becomes the per-vertex fixed_side (-1 = free), partition
the per-vertex side (assignment(), -1 = left out), the size bounds stay None
when not given, repeated edges and pairs stay repeated; warm_start is copied.
The result fields are ignored (the engine recomputes them).
from_core
classmethod
¶
from_core(problem: MaxCutProblem) -> MaxCutProblemModel
engine object -> pydantic: the facts, the partition (vertices on side -1 are
left out), warm_start and the results (cut_weight and the score once the core
was scored by calculate_score or a solve, else None).
MaxCutRequest ¶
Bases: SolveRequest
The max-cut problem 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 a solved problem model or a dict of the same shape; vertices are matched by id. A vertex the
solution leaves out takes the default start: its fixed_partition side, otherwise the alternating side. Anything
solve returns is accepted, feasible or not. With exact size bounds the search only swaps sides, so a seed of the
wrong size, complete or filled in, keeps that size and its hard penalty. A side that contradicts fixed_partition
raises ValueError: solve never returns one, and the search never moves a fixed vertex.
parameter_uses ¶
parameter_uses(model: MaxCutProblemModel) -> 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.
solve_request ¶
solve_request(request: MaxCutRequest, *, constraints=None) -> MaxCutProblemModel
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.max_cut.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (max_cut.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::
from optimaru import max_cut
from optimaru.max_cut.constraints import (
CutWeightCost, PartitionImbalanceCost, PartitionSizeBoundsCost, get_constraints,
)
problem = max_cut.solve(problem, constraints=get_constraints()) # defaults as-is
picks = [
PartitionImbalanceCost(weight=2) if spec.name == "partition_imbalance_cost" else spec
for spec in get_constraints()
]
problem = max_cut.solve(problem, constraints=picks) # one default changed
problem = max_cut.solve(problem, constraints=[PartitionSizeBoundsCost(), CutWeightCost()]) # picked
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: cut_weight_cost is
CutWeightCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (1, exceptPartitionImbalanceCost: 0, an opt-in objective). The problem carries no weights;max_cut.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.CutWeightCostis a reward and always soft:level="hard"raises ValueError.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent. The four unit constraints (fixed, same-side, different-side, size bounds) shape each SIDE's cost; the two globals (imbalance, cut) their single total.offset(keyword) shifts that shaping, per side 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 side (or total) below the offset — a raw 0 included — lowers the penalty; a unit constraint charges both sides. With an offset it is refused on hard (the four unit constraints by default), because hard 0 must mean no violation. On theCutWeightCostreward (raw-cut) a threshold offset rewards only the cut beyond it, a literal one addsoffsetto the reward.
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 imbalance plus its square beyond 2 vertices::
problem = max_cut.solve(problem, constraints=[
*(spec for spec in get_constraints() if spec.name != "partition_imbalance_cost"),
PartitionImbalanceCost(weight=1),
PartitionImbalanceCost(weight=5, exponent=2, offset=2),
])
max_cut.constraint_costs(problem, picks) keys the second pick
"partition_imbalance_cost#2".
Names (name) are the C++ component names in snake_case
(FixedPartitionCost -> fixed_partition_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
max_cut.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.
FixedPartitionCost
dataclass
¶
SamePartitionPairsCost
dataclass
¶
Bases: Constraint
Must-be-together pairs that are split, per side of the first vertex. Default: hard, weight 1.
DifferentPartitionPairsCost
dataclass
¶
PartitionSizeBoundsCost
dataclass
¶
Bases: Constraint
Vertices a side has below the minimum or above the maximum size. Default: hard, weight 1.
PartitionImbalanceCost
dataclass
¶
Bases: Constraint
Size difference between the two sides, an opt-in objective. Default: soft, weight 0.
CutWeightCost
dataclass
¶
Bases: Constraint
Total weight of the cut edges, a reward (raw cost <= 0). Default: soft, weight 1; never hard.
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 = [
PartitionImbalanceCost(weight=2) if spec.name == "partition_imbalance_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 max_cut.constraint_costs(problem) returns: per constraint
its raw costs (per side for the four unit constraints, one total for the
imbalance and the cut), before weight, exponent, offset and level rounding. Fetch
it once and rescore with different weights without re-solving::
raw = max_cut.constraint_costs(problem)
score(raw) # default set
score(raw, [PartitionSizeBoundsCost(), PartitionImbalanceCost(weight=2), CutWeightCost()])
score(raw, [CutWeightCost(), CutWeightCost(weight=0.5, offset=10)])
No solver and no search are involved. The arithmetic matches the engine —
each side (or global total) contributes weight * shape(cost, exponent, offset,
clip) and hard contributions are rounded per side 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; so do
level="medium" (no medium level here) and level="hard" on the
cut_weight_cost reward.
optimaru.max_cut._core ¶
Type stubs for optimaru.max_cut._core — the max-cut C++ solver.
The problem object holds the solution: each vertex's side (0 or 1; -1 =
unassigned, in no side) is the single assignment-shape decision variable, read and
written with assignment() / set_assignment(). A vertex with a fixed side
is pinned: the search never moves it.
Score (hard/soft, lexicographic), at the default weights: hard = -(fixed vertices off their side + split same-side pairs + different-side pairs left together + side-size shortfall/excess), soft = +(cut weight), a reward (partition_imbalance_cost is an opt-in objective, weight 0). The weights are the C++ components' defaults (constraint_info()); the problem carries none.
Edge ¶
Problem fact: an undirected weighted edge between two vertex indices. A self-loop is never cut; parallel edges add up.
VertexPair ¶
Problem fact: two vertex indices that must share a side (same-side pairs) or sit on different sides (different-side pairs).
MaxCutProblem ¶
Problem and solution in one object. NOTE: list attributes return copies; assign whole lists and use set_assignment for the partition. Every entry point re-validates the facts (ValueError on an invalid one).
fixed_side
instance-attribute
¶
fixed_side: list[int]
Per vertex: -1 = free, 0 / 1 = pinned to that side.
max_partition_size
instance-attribute
¶
max_partition_size: int | None
None = the vertex count. min == max (both given) = exact size: the search only swaps.
warm_start
instance-attribute
¶
warm_start: bool
Start the next solve from the current partition (unassigned vertices take the default start); the solve resets it to False.
__init__ ¶
__init__(vertex_ids: list[str], edges: list[Edge] = ..., fixed_side: list[int] | None = None, same_partition_pairs: list[VertexPair] = ..., different_partition_pairs: list[VertexPair] = ..., min_partition_size: int | None = None, max_partition_size: int | None = None, side: list[int] | None = None, warm_start: bool = False) -> None
fixed_side / side: one entry per vertex, each -1, 0 or 1 (None = all -1).
cut_weight ¶
cut_weight() -> int
Weight of the edges with both endpoints assigned and on different sides.
set_assignment ¶
set_assignment(assignment: list[int]) -> None
Bulk write of the decision variable (one entry per vertex, each -1, 0 or 1).
SolverConfig ¶
spent_limit_seconds
instance-attribute
¶
spent_limit_seconds: float
Wall-clock budget (30 s by default). 0 returns the start partition unchanged.
parallel_solver_count
instance-attribute
¶
parallel_solver_count: int
Independent starts (seed + i each); the best wins. Ignored by solve_with_constraints.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(8 * vertex 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
instance-attribute
¶
ruin_recreate: bool
Adaptive ruin-and-recreate kicks on stagnation (off in exact-size mode).
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); 0 (default) = off; off in exact-size mode.
change_move_weight
instance-attribute
¶
change_move_weight: float
A change move flips one vertex (0.8 by default; 0 in exact-size mode).
swap_move_weight
instance-attribute
¶
swap_move_weight: float
A swap move exchanges a side-0 and a side-1 vertex (0.2 by default; 1 in exact-size mode).
descent_weight
instance-attribute
¶
descent_weight: float
Assignment-shape best-improvement descent strategy weight. 0 = off (off in exact-size mode).
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.
on_new_best
instance-attribute
¶
on_new_best: Callable[[int, Score], None] | None
Called as on_new_best(step, score) on every new best (by the first parallel start only). An exception it raises stops the solve and is raised by solve().
Solver ¶
Start partition + Late Acceptance local search (+ adaptive ruin-and-recreate). Solves IN PLACE: sets the partition, problem.score, scored = True and warm_start = False.
solve_with_constraints ¶
solve_with_constraints(problem: MaxCutProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.max_cut.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: MaxCutProblem) -> Score
Full recompute of the score at the default constraints (also stores problem.score and sets problem.scored). Raises ValueError on invalid facts. An unassigned vertex (-1) is in no side: it adds nothing to the cut, the sizes or the pair costs, except that a same-side pair whose FIRST vertex is assigned and whose second is not counts as split. (max_cut.calculate_score refuses a partial partition instead.)
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): fixed_partition_cost, same_partition_pairs_cost, different_partition_pairs_cost, partition_size_bounds_cost, partition_imbalance_cost, cut_weight_cost. The same names optimaru.max_cut.constraints uses.
constraint_costs ¶
constraint_costs(problem: MaxCutProblem, 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}}, "level" being the level in
effect (the pick's, or the default) and "hard" the same as level == "hard". The
four unit constraints report [side 0, side 1]; partition_imbalance_cost and
cut_weight_cost one total each ("global": True). 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 four hard constraints at weight 1 (flippable), partition_imbalance_cost (soft, weight 0: opt-in, default_enabled False), then cut_weight_cost (soft, weight 1, a reward: level="hard" is refused and its level cannot change).