Skip to content

Constraint-spec base

optimaru._constraint

The constraint-spec base shared by every optimaru use-case package.

Every optimaru.<use case>.constraints module builds on it, so a constraint spec behaves the same way in every use case.

A package's constraints.py builds on it::

from .._constraint import Constraint, Score, score_costs, select

class FacilityCapacityCost(Constraint):
    name = "facility_capacity_cost"
    label_en = "Facility capacity"
    label_ko = "시설 용량"
    description_en = "..."
    description_ko = "..."

facility_capacity_cost = FacilityCapacityCost()  # the ready-made FacilityCapacityCost()
_DEFAULTS = (facility_capacity_cost, ...)

def get_constraints(constraints=None):
    return select(constraints, _DEFAULTS)

def score(costs, constraints=None):
    return score_costs(costs, get_constraints(constraints))

Every spec takes the same five knobs, and only those:

  • weight None = the component's default weight (C++ kDefaultWeight, in units of its level); otherwise a finite number >= 0.
  • level None = the component's default level; otherwise a :class:Level or its name ("hard", "medium", "soft"). Level.MEDIUM needs a domain with a medium level. A reward refuses hard, and refuses medium where medium folds below hard, and so does a constraint whose raw cost can be negative on the problem's data (constraint_costs() marks it "signed"); a constraint whose level is not flippable refuses any change.
  • exponent sign-preserving power shaping, > 0 (1.0 = none): per unit for a unit constraint, on the single total for a global one.
  • offset a shift of that shaping, any finite number (0.0 = none), at the same granularity as exponent. Keyword-only.
  • clip what happens below the offset (keyword-only). True (the default, the threshold): sign(x) * max(0, |x| - offset) ** exponent, so only the part beyond the offset counts. With a negative offset that is a fixed charge per non-zero unit, which the engine recomputes for every unit a move changes instead of updating it by the difference: the same score, but a slower solve (about half the steps per second in vehicle routing). False (the literal formula): shape(x - offset, exponent), which is negative below the offset (a reward) and charges every unit the constraint evaluates, a raw 0 included. With an offset != 0 it is refused on a level that counts toward the hard score (hard, or medium where it folds below hard), because hard 0 must mean no violation.

With offset=0 both modes are the plain shape(x, exponent), so a spec that leaves offset and clip at their defaults scores the plain weight * shape(x, exponent). Each unit (or a global's total) then contributes weight * shape(x, exponent, offset, clip). The formula applies PER UNIT (per vehicle, per slot, ...), on every unit the constraint evaluates, raw 0 included; it is not one formula over the total violation.

Defaults (weight, level, flippability, reward) live in C++ only and are reported by <package>.constraint_info(); there are no default ClassVars here. Domain parameters are extra dataclass fields on a subclass (decorate it with @dataclass(frozen=True) and call super().__post_init__() from its own __post_init__, if it has one).

One constraint may be picked several times, in every package: each pick is its own instance with its own knobs (and, where the constraint has domain parameters, its own parameters), scored independently, and the instances add up. x**2 + x**3 is two picks, exponent=2 and exponent=3; two identical picks simply count twice. constraint_costs() keys the k-th instance of a name "<name>#<k>" (the first keeps the plain name), and instance_keys / score_costs follow the same rule.

Level

Bases: StrEnum

The score level a constraint is charged on. Hard dominates medium, medium dominates soft.

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.

ParameterUse

Bases: NamedTuple

An input parameter set away from its default, and the costs that give it an effect.

where names what carries it ("vehicle V1"), field the parameter, default the value that leaves it unset, and costs the constraint names that read it: the selection must hold at least one of them, at any weight.

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.

select

select(constraints: Iterable[Any] | None, defaults: Sequence[Any]) -> list[Any]

The get_constraints contract: None = defaults; a list replaces them.

Only the listed constraints are scored. An empty list is an error, not "the defaults" (a filter that came back empty is a mistake). A name may appear several times: every pick is its own instance with its own knobs (and parameters), scored on its own, and the instances add up; identical picks count twice. The same rules as the C++ applyConstraints.

with_always_on

with_always_on(picks: list[Any], costs: Mapping[str, Any], spec_type: type) -> list[Any]

picks with the always-on constraint spec_type appended where the engine added it.

A use case whose engine adds a constraint to every selection that does not score it as a rule (routing's forbidden visits and requests: addAlwaysOnConstraints) reports that instance in constraint_costs() after the picks' own. Its key there is the next instance key of the name, so score() appends the default spec exactly when costs holds it.

is_set

is_set(value: Any, default: Any) -> bool

Whether a parameter is away from its default. For a default of None or empty (no group, no list), any empty value (None, "", []) leaves it unset too.

require_costs

require_costs(uses: Iterable[ParameterUse], constraints: Iterable[Any], *, check_picks: Callable[[], Any] | None = None) -> None

Refuse parameters that the selection gives no effect: ValueError naming each one.

uses are the parameters an input sets away from their defaults, with the costs that read them (models.parameter_uses of a use case); constraints is the effective selection (get_constraints(constraints): the defaults when None). A parameter whose costs are all missing would be silently ignored by the solve, so it is an error: add one of its costs (a weight of 0 is an explicit choice and counts), or leave the parameter at its default. Each missing pair is named once, with the first place that sets it and how many more do.

check_picks runs the engine's own checks of the picks (scoring them once with constraint_costs) before a refusal, so a misspelt name or a bad knob is reported as what it is. constraints is read once: pass a list, and hand the same list on to the solve (get_constraints would use up a generator).

instance_keys

instance_keys(constraints: Iterable[Any]) -> list[str]

The constraint_costs() key of each pick, in order.

The name itself, and "<name>#<k>" for the k-th pick (k >= 2) of a name the selection states several times: the rule the C++ constraint_costs() (python::instanceKeys) keys its entries by, given the same list in the same order.

shape

shape(cost: float, exponent: float, offset: float = 0.0, clip: bool = True) -> float

Sign-preserving power, shifted by offset: the engine's shapeCost.

shape(x, e) raises |x| to e and keeps the sign (rewards, i.e. negative costs, never flip into penalties). With an offset:

  • clip=True (the threshold): sign(x) * max(0, |x| - offset) ** e; x == 0 stays 0 at any offset.
  • clip=False (the literal formula): shape(x - offset, e).

offset=0 is shape(x, e) in both modes. The steps are the C++ ones, so both give the same float.

score_costs

score_costs(costs: Mapping[str, Mapping[str, Any]], constraints: Iterable[Any]) -> Score

Apply specs to raw constraint costs and produce the engine score — pure Python.

costs is what <package>.constraint_costs(solution) returns: per constraint the raw cost of each unit (before weight, exponent and level), its default weight and level (default_weight / default_level; costs computed under a selection carry that selection's weight / level next to them, and an unset knob here still means the default), for a scoped constraint the units it evaluates, and on a domain with a medium level the domain's medium fold (on every entry). No solver and no search are involved, so one scoring pass answers every "what would this cost at weight 10 / as a soft term / squared beyond 10" question. A weight of 0 contributes exactly 0 whatever the exponent or offset.

The arithmetic is the engine's: each evaluated unit (every unit, or the entry's units) contributes weight * shape(cost, exponent, offset, clip), per unit and a raw 0 included, not one formula over the total; hard contributions are rounded per unit (half away from zero) before summing; then the domain's medium fold applies to the whole score, whatever the selection holds: into_soft adds medium * unit to soft, below_hard reports hard * unit + medium (medium rounded per unit too) — so a below_hard domain scores hard * unit even with no medium constraint selected. The engine's range rules apply too: a contribution that is not finite, or a hard one of 2**62 or more, raises OverflowError; the hard total saturates at -(2**63 - 1) (never wraps to a feasible-looking score). Every listed spec is scored (pass select(...)'s result), each looked up under its instance_keys key; an unknown one raises ValueError. The k-th pick of a constraint without domain parameters may also be scored from costs that hold the name only once (the default constraint_costs()): every instance of it has the same raw costs, so its entry is read with the pick's own knobs.

clip=False with an offset != 0 is refused (ValueError, in the engine's words) on a level that counts toward the hard score: hard, or medium in a below_hard domain; the level is the pick's, or the default. So is an entry marked "signed" (its raw cost can be negative on this problem although it is not a reward) on such a level. It also needs entries that carry "clip", as constraint_costs() reports them: an entry without it (built by hand) does not say which units a constraint evaluates, so scoring the literal formula from it raises ValueError.

A pick must carry name, weight, level and exponent. offset and clip are optional and default to 0.0 and True. They only add shaping, and their defaults change nothing. A missing weight, level or exponent stays an AttributeError, because it is more likely a mistake than a request for the default.

A numeric knob counts as the double float() makes of it, as the engine reads it: an offset of Fraction(1, 10**400) is 0.0 (no shift), and a numpy.longdouble weight or offset is scored as a double.