ket.qulib.qubo

QUBO modeling helpers.

Tools for writing QUBO (Quadratic Unconstrained Binary Optimization) problems as Ket Hamiltonians. Each binary variable \(x_i\) is a qubit, read through the observable B, \(x_i = (1 - Z_i)/2\).

The module has two layers:

  • Functions that build Hamiltonian pieces: integer variables in binary (binary) or one-hot (one_hot) encoding, and penalty terms for constraints (exactly_one, at_most_one, equal, less_equal, greater_equal). They work on process qubits or on placeholder qubits from with obs(n) as q:, like any other Ket observable.

  • The QUBO model. Its variables are Expression objects: arithmetic builds new expressions and comparisons build Constraint objects. qubo += expr adds to the objective and qubo += constraint adds a restriction. The model allocates slack qubits, picks penalty weights, and compiles everything into one unbound Hamiltonian.

Example

from ket.qulib.qubo import QUBO
from ket.qulib import exact_solver

# Knapsack: pick items to maximize value with total weight <= 5
values, weights = [3, 4, 5], [2, 3, 4]

qubo = QUBO()
x = qubo.binary_vars(3)
qubo += -sum(v * xi for v, xi in zip(values, x))      # maximize value
qubo += sum(w * xi for w, xi in zip(weights, x)) <= 5, "capacity"

state, _ = exact_solver(qubo, qubo.num_qubits)
print(qubo.evaluate(state), qubo.is_feasible(state))   # -7.0 True

Summary

Classes

Expression

A diagonal expression over the binary variables of a QUBO.

Constraint

A restriction on Expression objects, written lhs sense rhs.

QUBO

A QUBO problem with constraints, compiled to a Hamiltonian.

Functions

binary

Integer variable in bounded binary encoding.

one_hot

Variable in one-hot encoding.

slack_size

Number of qubits needed to encode an integer in [0, max_value].

exactly_one

Penalty for the one-hot restriction: exactly one qubit is set.

at_most_one

Penalty for the restriction: at most one qubit is set.

equal

Penalty for the restriction expr == value.

less_equal

Penalty for the restriction expr <= bound.

greater_equal

Penalty for the restriction expr >= bound.

Classes

class Expression(
expr: Hamiltonian | Pauli | Number = 0,
qubits: ObsQubits | None = None,
)[source]

Bases: Hamiltonian

A diagonal expression over the binary variables of a QUBO.

Expressions come from QUBO.binary_var, QUBO.binary_vars, QUBO.int_var and QUBO.one_hot_var, or from wrapping an unbound diagonal Hamiltonian, Expression(B(q)). They support:

  • +, -, *, /, ** and unary -, with numbers, other expressions or unbound diagonal Hamiltonians. The product follows the Pauli algebra, so \(x \cdot x = x\) for a binary variable.

  • ==, <=, >=, < and >, which return a Constraint to add to the model with qubo += constraint. Strict comparisons assume integer values: e < b is e <= b - 1.

!= is not supported, and expressions are not hashable.

An expression is an unbound Hamiltonian, so it can also be bound to qubits or passed to exp_value.

Example

qubo = QUBO()
x, y = qubo.binary_vars(2)
n = qubo.int_var(5)

cost = 3 * x + 2 * y - x * y     # Expression
cap = n + 2 * x <= 6             # Constraint
Parameters:
  • expr – Unbound diagonal Hamiltonian, Pauli or number.

  • qubits – Qubits of the variable, when the expression is one.

qubits

Qubits of the variable, or None for a compound expression.

__eq__(other) → Constraint[source]

Return self==value.

__le__(other) → Constraint[source]

Return self<=value.

__ge__(other) → Constraint[source]

Return self>=value.

__lt__(other) → Constraint[source]

Return self<value.

__gt__(other) → Constraint[source]

Return self>value.

__ne__(other)[source]

Return self!=value.

class Constraint(expr: Expression, sense: str)[source]

Bases: object

A restriction on Expression objects, written lhs sense rhs.

Built by comparing expressions (==, <=, >=, <, >) and added to a model with qubo += constraint. To set a penalty weight or a name, add a tuple, qubo += constraint, 10.0, "name", or call QUBO.add.

The constant part of the comparison is moved to the right-hand side, so x + 1 <= y becomes x - y <= -1.

Note

A constraint has no truth value: if x == y: raises TypeError.

lhs: Expression

Left-hand side, without a constant term.

sense: str

"==", "<=" or ">=".

rhs: float

Right-hand side constant.

class QUBO(num_qubits: int = 0)[source]

Bases: object

A QUBO problem with constraints, compiled to a Hamiltonian.

The problem is built on placeholder qubits (ObsQubits), so it does not depend on a process. Create variables with binary_var, binary_vars, int_var or one_hot_var; they are Expression objects, so the model is written with plain operators:

  • qubo += expr adds expr to the objective (minimized) and qubo -= expr subtracts it (to maximize).

  • qubo += expr <= bound (or ==, >=, <, >) adds a constraint. Add a tuple to set a penalty weight and/or a name, qubo += (expr <= bound, 10.0, "capacity"), or call add.

  • qubo += [c1, c2, ...] adds every item of a list.

The methods minimize, maximize, equal, less_equal, greater_equal, exactly_one, at_most_one and add_penalty do the same with explicit calls, and also accept raw qubits from alloc. Inequalities get their slack qubits allocated automatically.

hamiltonian compiles the problem into

\[H = \text{objective} + \sum_c A_c \, P_c\]

where \(P_c \ge 0\) is the penalty of constraint \(c\) (zero only when it holds) and \(A_c\) its weight. The result is an unbound Hamiltonian. Calling the QUBO, qubo(qubits), binds it, so a QUBO can be passed anywhere a Callable[[Quant], Hamiltonian] is expected, such as exact_solver or energy.

If a constraint has no weight, it gets \(\Delta + 1\), where \(\Delta\) is an upper bound on the objective range (max minus min). For integer-valued constraints, any violation costs at least 1, so every infeasible state has higher energy than every feasible one.

Example

from ket import *
from ket.qulib.qubo import QUBO

# Assign 3 tasks to 2 machines, each task to exactly one machine,
# and machine 0 takes at most 1 task.
cost = [[1, 3], [2, 1], [4, 2]]

qubo = QUBO()
x = [qubo.binary_vars(2) for _ in range(3)]    # x[t][m]
qubo += sum(cost[t][m] * x[t][m] for t in range(3) for m in range(2))
qubo += [(sum(x[t]) == 1, f"task {t}") for t in range(3)]
qubo += sum(x[t][0] for t in range(3)) <= 1, "machine 0"

p = Process()
q = p.alloc(qubo.num_qubits)
ev = exp_value(qubo(q))
Parameters:

num_qubits – Number of decision qubits to allocate at once; they are available from qubits.

qubits: ObsQubits

Decision qubits allocated by the constructor.

property num_qubits: int

Total number of qubits, including slack qubits.

property objective: Expression

The objective, without penalties.

property constraints: list[tuple[str, Hamiltonian, float | None]]

(name, penalty, weight) of each constraint. weight is None when it is chosen automatically.

alloc(num_qubits: int = 1) → ObsQubits[source]

Allocate new placeholder qubits for decision variables.

Parameters:

num_qubits – Number of qubits.

Returns:

The new qubits.

binary_var() → Expression[source]

Allocate one binary (0/1) variable.

binary_vars(num_vars: int) → list[Expression][source]

Allocate num_vars binary (0/1) variables.

int_var(
max_value: int,
encoding: Literal['binary', 'one_hot'] = 'binary',
penalty: float | None = None,
name: str | None = None,
) → Expression[source]

Allocate an integer variable in [0, max_value].

With encoding="binary" it uses binary: few qubits and no constraint, since every bit assignment is a valid value. With encoding="one_hot" it is one_hot_var over 0, 1, ..., max_value.

Parameters:
  • max_value – Largest value, at least 1.

  • encoding – "binary" or "one_hot".

  • penalty – Weight of the one-hot constraint (one-hot only).

  • name – Name of the one-hot constraint (one-hot only).

one_hot_var(
values: int | Iterable[float],
penalty: float | None = None,
name: str | None = None,
) → Expression[source]

Allocate a variable in one-hot encoding and add its exactly_one constraint.

Parameters:
  • values – The values the variable can take, or an integer n for 0, 1, ..., n - 1.

  • penalty – Weight of the one-hot constraint.

  • name – Name of the one-hot constraint.

minimize(
expr: Hamiltonian | Pauli | Number,
) → QUBO[source]

Add expr to the objective. Can be called more than once.

maximize(
expr: Hamiltonian | Pauli | Number,
) → QUBO[source]

Add -expr to the objective. Can be called more than once.

add_penalty(
penalty: Hamiltonian | Pauli | Number,
weight: float | None = None,
name: str | None = None,
) → QUBO[source]

Add a custom constraint given as a penalty Hamiltonian.

Parameters:
  • penalty – Diagonal observable that is zero on feasible states and positive (at least 1, for the automatic weight) otherwise.

  • weight – Penalty weight. If None, it is chosen at compile time.

  • name – Name used by violations.

exactly_one(
qubits: Quant | ObsQubits,
penalty: float | None = None,
name: str | None = None,
) → QUBO[source]

Restrict qubits to one-hot: exactly one is set. See exactly_one.

at_most_one(
qubits: Quant | ObsQubits,
penalty: float | None = None,
name: str | None = None,
) → QUBO[source]

Restrict qubits so at most one is set. See at_most_one.

equal(
expr: Hamiltonian | Pauli | Number,
value: float,
penalty: float | None = None,
name: str | None = None,
) → QUBO[source]

Restrict expr == value. See equal.

less_equal(
expr: Hamiltonian | Pauli | Number,
bound: float,
penalty: float | None = None,
name: str | None = None,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → QUBO[source]

Restrict expr <= bound, allocating slack qubits as needed.

The slack covers exactly [0, bound - min(expr)], using a lower bound of expr. No qubit is allocated when the restriction always holds. See less_equal.

Parameters:
  • expr – Diagonal observable on the QUBO qubits, integer-valued.

  • bound – Upper bound.

  • penalty – Constraint weight. If None, chosen at compile time.

  • name – Name used by violations.

  • encoding – Slack encoding, "binary" (fewer qubits) or "one_hot".

greater_equal(
expr: Hamiltonian | Pauli | Number,
bound: float,
penalty: float | None = None,
name: str | None = None,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → QUBO[source]

Restrict expr >= bound, allocating slack qubits as needed.

Same as less_equal; the slack covers [0, max(expr) - bound].

add(
constraint: Constraint,
penalty: float | None = None,
name: str | None = None,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → QUBO[source]

Add a Constraint built with ==, <=, >=, < or >.

qubo += constraint is a shorthand for this method.

Parameters:
  • constraint – The constraint, e.g. x + y <= 1.

  • penalty – Constraint weight. If None, chosen at compile time.

  • name – Name used by violations.

  • encoding – Slack encoding for inequalities, "binary" or "one_hot".

default_penalty() → float[source]

Weight given to constraints without an explicit one.

hamiltonian() → Hamiltonian[source]

Compile the objective and penalties into an unbound Hamiltonian.

bind(qubits: Quant) → Hamiltonian[source]

Compile and bind the Hamiltonian to process qubits.

qubo(qubits) is a shorthand for this method.

Parameters:

qubits – At least num_qubits qubits from a process.

__call__(qubits: Quant) → Hamiltonian

Compile and bind the Hamiltonian to process qubits.

qubo(qubits) is a shorthand for this method.

Parameters:

qubits – At least num_qubits qubits from a process.

evaluate(
state: int | str | Iterable[int],
expr: Hamiltonian | Pauli | Number | None = None,
) → float[source]

Classical value of an expression on a basis state.

Use it to read the objective of a solution or decode a variable, e.g. qubo.evaluate(state, n) for n = qubo.int_var(5).

Parameters:
  • state – Basis state as an integer (qubit 0 is the most significant bit, as in energy), a bit string, or a list of bits.

  • expr – Expression to evaluate. Defaults to the objective.

energy(state: int | str | Iterable[int]) → float[source]

Value of the compiled Hamiltonian (objective plus penalties) on a basis state.

violations(state: int | str | Iterable[int]) → list[str][source]

Names of the constraints a basis state breaks.

A broken inequality may only mean its slack qubits are not set to the matching value.

is_feasible(state: int | str | Iterable[int]) → bool[source]

True if the basis state satisfies every constraint.

Functions

binary(
qubits: Quant | ObsQubits,
max_value: int | None = None,
) → Hamiltonian[source]

Integer variable in bounded binary encoding.

Qubit \(k\) has weight \(2^k\), except the last one, whose weight completes exactly max_value. The variable then takes every value from 0 to max_value and none above. For example, max_value=5 uses 3 qubits with weights 1, 2 and 2.

\[v = \sum_{k=0}^{n-2} 2^k x_k + \left(m - 2^{n-1} + 1\right) x_{n-1}\]

Example

from ket import *
from ket.qulib.qubo import binary

with obs(3) as q:
    v = binary(q, max_value=5)    # 1*B(q0) + 2*B(q1) + 2*B(q2)
Parameters:
  • qubits – Qubits holding the variable. Must have exactly slack_size(max_value) qubits.

  • max_value – Largest value of the variable. If None, it is \(2^n - 1\) (plain binary).

Returns:

Observable whose eigenvalue is the encoded integer.

one_hot(
qubits: Quant | ObsQubits,
values: Iterable[float] | None = None,
) → Hamiltonian[source]

Variable in one-hot encoding.

\[v = \sum_k v_k x_k\]

The variable equals values[k] when only qubit k is set. This observable alone does not force a single qubit to be set: add the exactly_one penalty for that (QUBO.one_hot_var does it for you).

Parameters:
  • qubits – Qubits holding the variable, one per value.

  • values – Value of each qubit. Defaults to 0, 1, ..., n - 1.

Returns:

Observable whose eigenvalue is the encoded value.

slack_size(
max_value: int,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → int[source]

Number of qubits needed to encode an integer in [0, max_value].

Parameters:
  • max_value – Largest value the variable must reach.

  • encoding – "binary" needs max_value.bit_length() qubits; "one_hot" needs max_value + 1 qubits.

exactly_one(
qubits: Quant | ObsQubits,
) → Hamiltonian[source]

Penalty for the one-hot restriction: exactly one qubit is set.

\[\left(\sum_k x_k - 1\right)^2\]

Zero when exactly one qubit is \(\left|1\right>\), at least 1 otherwise.

at_most_one(
qubits: Quant | ObsQubits,
) → Hamiltonian[source]

Penalty for the restriction: at most one qubit is set.

\[\sum_{i < j} x_i x_j\]

Zero when no more than one qubit is \(\left|1\right>\), at least 1 otherwise.

equal(
expr: Hamiltonian | Pauli | Number,
value: float,
) → Hamiltonian[source]

Penalty for the restriction expr == value.

\[\left(\text{expr} - \text{value}\right)^2\]
Parameters:
  • expr – Diagonal observable, usually a weighted sum of B.

  • value – Target value.

less_equal(
expr: Hamiltonian | Pauli | Number,
bound: float,
slack: Quant | ObsQubits,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → Hamiltonian[source]

Penalty for the restriction expr <= bound.

Adds an integer slack variable \(s \ge 0\) stored in slack:

\[\left(\text{expr} + s - \text{bound}\right)^2\]

With encoding="one_hot" the exactly_one penalty on the slack qubits is added too. The slack must reach bound - min(expr) for every feasible point to have zero penalty; use slack_size to size it. Extra slack range is harmless. The restriction is exact for integer-valued expr and bound.

Parameters:
  • expr – Diagonal observable.

  • bound – Upper bound.

  • slack – Qubits for the slack variable (not used anywhere else).

  • encoding – Slack encoding, "binary" or "one_hot".

greater_equal(
expr: Hamiltonian | Pauli | Number,
bound: float,
slack: Quant | ObsQubits,
encoding: Literal['binary', 'one_hot'] = 'binary',
) → Hamiltonian[source]

Penalty for the restriction expr >= bound.

Same as less_equal, with

\[\left(\text{expr} - s - \text{bound}\right)^2\]

The slack must reach max(expr) - bound.