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 fromwith obs(n) as q:, like any other Ket observable.The
QUBOmodel. Its variables areExpressionobjects: arithmetic builds new expressions and comparisons buildConstraintobjects.qubo += expradds to the objective andqubo += constraintadds a restriction. The model allocates slack qubits, picks penalty weights, and compiles everything into one unboundHamiltonian.
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
A diagonal expression over the binary variables of a |
|
A restriction on |
|
A QUBO problem with constraints, compiled to a Hamiltonian. |
Functions
Integer variable in bounded binary encoding. |
|
Variable in one-hot encoding. |
|
Number of qubits needed to encode an integer in |
|
Penalty for the one-hot restriction: exactly one qubit is set. |
|
Penalty for the restriction: at most one qubit is set. |
|
Penalty for the restriction |
|
Penalty for the restriction |
|
Penalty for the restriction |
Classes¶
- class Expression(
- expr: Hamiltonian | Pauli | Number = 0,
- qubits: ObsQubits | None = None,
Bases:
HamiltonianA diagonal expression over the binary variables of a
QUBO.Expressions come from
QUBO.binary_var,QUBO.binary_vars,QUBO.int_varandQUBO.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 aConstraintto add to the model withqubo += constraint. Strict comparisons assume integer values:e < bise <= 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 toexp_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
Nonefor 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.
- class Constraint(expr: Expression, sense: str)[source]¶
Bases:
objectA restriction on
Expressionobjects, writtenlhs sense rhs.Built by comparing expressions (
==,<=,>=,<,>) and added to a model withqubo += constraint. To set a penalty weight or a name, add a tuple,qubo += constraint, 10.0, "name", or callQUBO.add.The constant part of the comparison is moved to the right-hand side, so
x + 1 <= ybecomesx - y <= -1.Note
A constraint has no truth value:
if x == y:raisesTypeError.- lhs: Expression¶
Left-hand side, without a constant term.
- class QUBO(num_qubits: int = 0)[source]¶
Bases:
objectA 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 withbinary_var,binary_vars,int_varorone_hot_var; they areExpressionobjects, so the model is written with plain operators:qubo += expraddsexprto the objective (minimized) andqubo -= exprsubtracts 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 calladd.qubo += [c1, c2, ...]adds every item of a list.
The methods
minimize,maximize,equal,less_equal,greater_equal,exactly_one,at_most_oneandadd_penaltydo the same with explicit calls, and also accept raw qubits fromalloc. Inequalities get their slack qubits allocated automatically.hamiltoniancompiles 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 aQUBOcan be passed anywhere aCallable[[Quant], Hamiltonian]is expected, such asexact_solverorenergy.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.
- property objective: Expression¶
The objective, without penalties.
- property constraints: list[tuple[str, Hamiltonian, float | None]]¶
(name, penalty, weight)of each constraint.weightisNonewhen 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_varsbinary (0/1) variables.
- int_var(
- max_value: int,
- encoding: Literal['binary', 'one_hot'] = 'binary',
- penalty: float | None = None,
- name: str | None = None,
Allocate an integer variable in
[0, max_value].With
encoding="binary"it usesbinary: few qubits and no constraint, since every bit assignment is a valid value. Withencoding="one_hot"it isone_hot_varover0, 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( ) Expression[source]¶
Allocate a variable in one-hot encoding and add its
exactly_oneconstraint.- Parameters:
values – The values the variable can take, or an integer
nfor0, 1, ..., n - 1.penalty – Weight of the one-hot constraint.
name – Name of the one-hot constraint.
- minimize(
- expr: Hamiltonian | Pauli | Number,
Add
exprto the objective. Can be called more than once.
- maximize(
- expr: Hamiltonian | Pauli | Number,
Add
-exprto the objective. Can be called more than once.
- add_penalty( ) 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( ) QUBO[source]¶
Restrict
qubitsto one-hot: exactly one is set. Seeexactly_one.
- at_most_one( ) QUBO[source]¶
Restrict
qubitsso at most one is set. Seeat_most_one.
- equal(
- expr: Hamiltonian | Pauli | Number,
- value: float,
- penalty: float | None = None,
- name: str | None = None,
Restrict
expr == value. Seeequal.
- less_equal(
- expr: Hamiltonian | Pauli | Number,
- bound: float,
- penalty: float | None = None,
- name: str | None = None,
- encoding: Literal['binary', 'one_hot'] = 'binary',
Restrict
expr <= bound, allocating slack qubits as needed.The slack covers exactly
[0, bound - min(expr)], using a lower bound ofexpr. No qubit is allocated when the restriction always holds. Seeless_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',
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',
Add a
Constraintbuilt with==,<=,>=,<or>.qubo += constraintis 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".
- 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_qubitsqubits 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_qubitsqubits from a process.
- evaluate( ) 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)forn = 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.
Functions¶
- binary( ) 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 from0tomax_valueand none above. For example,max_value=5uses 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( ) Hamiltonian[source]¶
Variable in one-hot encoding.
\[v = \sum_k v_k x_k\]The variable equals
values[k]when only qubitkis set. This observable alone does not force a single qubit to be set: add theexactly_onepenalty for that (QUBO.one_hot_vardoes 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( ) 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"needsmax_value.bit_length()qubits;"one_hot"needsmax_value + 1qubits.
- exactly_one( ) 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( ) 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,
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',
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"theexactly_onepenalty on the slack qubits is added too. The slack must reachbound - min(expr)for every feasible point to have zero penalty; useslack_sizeto size it. Extra slack range is harmless. The restriction is exact for integer-valuedexprandbound.- 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',
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.