ket.expv

Expected value calculation utilities.

This module provides Pauli, Hamiltonian, ExpValue, and the commutator helper for constructing quantum observables and computing their expectation values.

The preferred workflow is to use the obs context manager together with gate functions (X, Y, Z) to build Hamiltonians in a symbolic, Dirac-like notation. The exp_value function then wraps the resulting Hamiltonian into an ExpValue handle.

Example

from ket import *
p = Process()
q = p.alloc(2)
CNOT(H(q[0]), q[1])     # prepare Bell state
with obs():
    # Heisenberg XX + YY + ZZ Hamiltonian
    h = X(q[0])*X(q[1]) + Y(q[0])*Y(q[1]) + Z(q[0])*Z(q[1])
ev = exp_value(h)
print(ev.get())          # 1.0 for the Bell state |Φ+⟩

Hamiltonians can also be built without a process. with obs(n) as q: yields n placeholder qubits (ObsQubits). The result is an unbound Hamiltonian that you bind to real qubits later, either with bind (or the call shorthand h(qubits)) or by passing the qubits to exp_value or evolve:

from ket import *
with obs(2) as q:
    h = X(q[0])*X(q[1]) + Y(q[0])*Y(q[1]) + Z(q[0])*Z(q[1])

p = Process()
r = p.alloc(2)
CNOT(H(r[0]), r[1])
print(exp_value(h, r).get())   # same as exp_value(h(r))

Summary

Classes

ObsQubits

Placeholder qubits for building Hamiltonians without a process.

Pauli

Pauli operator for Hamiltonian creation.

Hamiltonian

A sum of weighted Pauli operator products representing a quantum observable.

ExpValue

A deferred handle for the expectation value of a Hamiltonian.

Functions

commutator

Calculate the commutator of two Hamiltonians.

Classes

class ObsQubits(num_qubits: int = 0, *, _qubits: list[int] | None = None)[source]

Bases: object

Placeholder qubits for building Hamiltonians without a process.

Placeholder qubits are numbered 0 to n - 1. A Hamiltonian built on them is unbound: it supports all the usual algebra, but it must be bound to qubits from a Process before computing an expectation value or evolving a state. Binding maps placeholder i to the i-th qubit of the given register.

Note

You usually get these from with obs(n) as q: rather than by instantiating this class directly.

Example

from ket import *
with obs(3) as q:
    h = sum(Z(q[i]) * Z(q[i + 1]) for i in range(2))

p = Process()
r = p.alloc(3)
ev = exp_value(h, r)
Parameters:

num_qubits – Number of placeholder qubits.

property ket_process: None

placeholder qubits do not belong to a process.

Type:

Always None

at(index: list[int]) → ObsQubits[source]

Return the placeholder qubits at the given positions.

class Pauli(
pauli: Literal['X', 'Y', 'Z', 'I'] | None,
qubits: Quant | ObsQubits | None,
*,
_process: Process | None = None,
_map: dict[int, str] | None = None,
_coef: float | complex | None = None,
)[source]

Bases:

Pauli operator for Hamiltonian creation.

Tip

The preferred way to create a Hamiltonian is by using the obs context manager, which allows you to define a Hamiltonian using a more intuitive syntax. However, you can also create Hamiltonians directly by instantiating this class.

This class represents a Pauli operator for Hamiltonian creation. The primary usage of this class is to prepare a Hamiltonian by adding and multiplying Pauli operators and scalars for calculating the expected value of a quantum state.

Parameters:
  • pauli – Pauli operator type.

  • qubits – Qubits to apply the Pauli operator to. Either qubits from a Process or placeholder ObsQubits; the latter creates an unbound operator (see bind).

  • process – For internal usage. Quantum process, default is the process of the given qubits.

  • pauli_list – For internal usage. List of Pauli operators.

  • qubits_list – For internal usage. List of Qubit.

  • coef – For internal usage. Coefficient for the Pauli operator, default is 1.0.

property is_bound: bool

True if the operator acts on qubits from a process.

property num_qubits: int

Number of qubits needed to bind the operator.

For an unbound operator this is the highest placeholder index plus one. For a bound operator it is the number of qubits it acts on.

bind(qubits: Quant) → Pauli[source]

Bind an unbound operator to qubits from a process.

Placeholder qubit i becomes qubits[i]. Calling the operator, pauli(qubits), is a shorthand for this method.

Parameters:

qubits – Qubits allocated from a Process. Must have at least num_qubits qubits.

Returns:

A new operator bound to the process of qubits.

Raises:

ValueError – If the operator is already bound or qubits is too short.

__call__(qubits: Quant) → Pauli

Bind an unbound operator to qubits from a process.

Placeholder qubit i becomes qubits[i]. Calling the operator, pauli(qubits), is a shorthand for this method.

Parameters:

qubits – Qubits allocated from a Process. Must have at least num_qubits qubits.

Returns:

A new operator bound to the process of qubits.

Raises:

ValueError – If the operator is already bound or qubits is too short.

static x(qubits: Quant | ObsQubits) → Pauli[source]

Pauli X operator.

Parameters:

qubits – Qubits to apply the Pauli operator to.

static y(qubits: Quant | ObsQubits) → Pauli[source]

Pauli Y operator.

Parameters:

qubits – Qubits to apply the Pauli operator to.

static z(qubits: Quant | ObsQubits) → Pauli[source]

Pauli Z operator.

Parameters:

qubits – Qubits to apply the Pauli operator to.

static i(qubits: Quant | ObsQubits) → Pauli[source]

Pauli I operator.

Parameters:

qubits – Qubits to apply the Pauli I operator to.

class Hamiltonian(
terms: list[Pauli],
process: Process,
*,
_index: dict[tuple, int] | None = None,
)[source]

Bases:

A sum of weighted Pauli operator products representing a quantum observable.

A Hamiltonian is a linear combination of Pauli terms:

\[H = \sum_k c_k \, P_k\]

where each \(P_k\) is a tensor product of single-qubit Pauli operators (\(X\), \(Y\), \(Z\), or \(I\)) and \(c_k\) is a real or complex scalar coefficient.

Note

Do not instantiate this class directly. Create Hamiltonians by adding Pauli objects together, or by using the obs context manager:

from ket import *
p = Process()
q = p.alloc(3)
with obs():
    # TFIM Hamiltonian: -J Σ Z_i Z_{i+1} - h Σ X_i
    J, h = 1.0, 0.5
    zz = sum(-J * Z(q[i]) * Z(q[i+1]) for i in range(2))
    xx = sum(-h * X(q[i]) for i in range(3))
    H = zz + xx

To build a Hamiltonian before allocating qubits, use with obs(n) as q:. The result is unbound; bind it with bind, the call shorthand H(qubits), or by passing the qubits to exp_value or evolve:

with obs(3) as q:
    H = sum(-Z(q[i]) * Z(q[i+1]) for i in range(2))

p = Process()
r = p.alloc(3)
exp_value(H, r)      # same as exp_value(H(r))

Supported arithmetic operators:

  • Addition (+): Combine two Hamiltonians or add a scalar constant.

  • Subtraction (-): Subtract a Hamiltonian or scalar.

  • Multiplication (*): Scale by a scalar, or form the operator product with another Hamiltonian/Pauli.

  • Matrix multiplication (@): Full Pauli-algebra operator product.

  • Power (**): Repeated operator product (\(H^n\)).

  • Division (/): Scale by the reciprocal of a scalar.

  • Negation (-H): Negate all coefficients.

property is_bound: bool

True if the Hamiltonian acts on qubits from a process.

property num_qubits: int

Number of qubits needed to bind the Hamiltonian.

For an unbound Hamiltonian this is the highest placeholder index plus one. For a bound Hamiltonian it is the number of qubits it acts on.

bind(qubits: Quant) → Hamiltonian[source]

Bind an unbound Hamiltonian to qubits from a process.

Placeholder qubit i becomes qubits[i]. Calling the Hamiltonian, h(qubits), is a shorthand for this method, so an unbound Hamiltonian can be passed anywhere a Callable[[Quant], Hamiltonian] is expected.

Parameters:

qubits – Qubits allocated from a Process. Must have at least num_qubits qubits.

Returns:

A new Hamiltonian bound to the process of qubits.

Raises:

ValueError – If the Hamiltonian is already bound or qubits is too short.

__call__(qubits: Quant) → Hamiltonian

Bind an unbound Hamiltonian to qubits from a process.

Placeholder qubit i becomes qubits[i]. Calling the Hamiltonian, h(qubits), is a shorthand for this method, so an unbound Hamiltonian can be passed anywhere a Callable[[Quant], Hamiltonian] is expected.

Parameters:

qubits – Qubits allocated from a Process. Must have at least num_qubits qubits.

Returns:

A new Hamiltonian bound to the process of qubits.

Raises:

ValueError – If the Hamiltonian is already bound or qubits is too short.

class ExpValue(
hamiltonian: Hamiltonian | Pauli | Callable[[Quant], Hamiltonian | Pauli],
qubits: Quant | None = None,
)[source]

Bases:

A deferred handle for the expectation value of a Hamiltonian.

Registering an expectation value does not immediately compute it, in live execution mode, the value is computed right away; in batch execution mode it is deferred and becomes available only after get (or a measurement) triggers process execution.

Note

Do not instantiate this class directly. Use exp_value instead.

Example

from ket import *
p = Process()
q = p.alloc(2)
CNOT(H(q[0]), q[1])    # Bell state |Φ+⟩
with obs():
    observable = X(q[0]) * X(q[1]) - Y(q[0]) * Y(q[1])
ev = exp_value(observable)
print(ev.get())        # 2.0 for the Bell state
property value: float | None

The expectation value if available, otherwise None.

In live execution mode this is populated immediately after ExpValue is created. In batch mode it is None until the process executes.

Returns:

The computed expectation value, or None if the process has not yet executed.

get() → float[source]

Retrieve the expectation value, executing the process if necessary.

Blocks until the expectation value is available. In batch execution mode this call triggers process execution.

Returns:

The computed expectation value.

Functions

commutator(a: Hamiltonian, b: Hamiltonian) → Hamiltonian[source]

Calculate the commutator of two Hamiltonians.

Computes \([A, B] = AB - BA\) using the Hamiltonian matrix-multiplication operator (@).

The commutator is zero if and only if the two operators share a common eigenbasis, i.e., they can be measured simultaneously. A non-zero commutator implies Heisenberg uncertainty between the corresponding observables.

Example

from ket import *
p = Process()
q = p.alloc()
with obs():
    x = X(q)
    z = Z(q)
xz_comm = commutator(x, z)    # [X, Z] = -2iY
print(xz_comm)                # displays the Pauli Y term
Parameters:
  • a – Left-hand operator.

  • b – Right-hand operator.

Returns:

The commutator \([A, B]\).