Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

qamomile.circuit

Compiler core of Qamomile and its public user-facing API surface.

Design center

The central abstraction is the qkernel decorator (frontend/): users write quantum programs as plain Python functions, the frontend traces them into an IR Block (ir/), the transpiler pipeline (transpiler/) rewrites the IR through staged, BlockKind-gated passes, and a backend package emits an executable program. This module re-exports everything a user program needs to be written: the decorator, the handle types (Qubit, Vector, Float, ...), gate / measurement / control-flow builders, meta-operations (control / inverse), stdlib and algorithm kernels (QFT, QPE, Grover, Shor, modular arithmetic), scheme-specific descriptors returned by circuit factories, symbolic resource estimation (estimator/), and the job / result types returned by ExecutableProgram.sample / run.

Dependency direction (hard constraint)

qamomile.circuit is the design center of the whole project: every other qamomile module depends on it, never the reverse — optimization → circuit ← backends (qiskit / quri_parts / cudaq / ...). Nothing under this package may import a backend package or SDK. Backend-specific concretization (native gate sets, per-qubit instruction encoding, runtime control-flow lowering) belongs in each backend’s emit pass / GateEmitter; this package owns only the abstract IR, the backend-agnostic pass pipeline, and the shared decomposition recipes that backends may fall back on.

Module-local constraints

Overview

FunctionDescription
bitCreate a Bit handle from a boolean/int literal or declare a named Bit parameter.
bit_arrayCreate a fixed-length classical bit vector initialized to zero.
castCast a quantum value to a different type without allocating new qubits.
ccxToffoli (CCX) gate: flips target when both controls are |1>.
composite_gateDefine a named composite using the normal qkernel programming model.
controlCreate a controlled version of a quantum gate.
cpApply a controlled phase gate.
cxCNOT (Controlled-X) gate.
czCZ (Controlled-Z) gate.
ekera_hastad_factoringCreate the quantum short-DLP stage for Ekerå–Håstad factoring.
expvalCompute the expectation value of an observable on a quantum state.
float_Create a Float handle from a float literal or declare a named Float parameter.
for_itemsCreate a traced for-items loop in the Qamomile frontend.
global_phaseApply a qkernel call followed by exp(i * phase).
hHadamard gate.
inverseCreate an inverse operation wrapper.
itemsIterate over dictionary key-value pairs.
measureMeasure a qubit or QFixed in the computational basis.
measure_resetMeasure a qubit in the Z basis and reset it to |0>.
opaqueCreate an opaque callable for top-down circuit design.
pPhase gate: P(theta)|1> = e^{i*theta}|1>.
pauli_evolveApply exp(-i * gamma * H) to a qubit register.
project_xProject a qubit in the X basis and keep the projected state.
project_yProject a qubit in the Y basis and keep the projected state.
project_zProject a qubit in the Z basis and keep the projected state.
qkernelDecorator to define a Qamomile quantum kernel.
qubitCreate a new qubit and emit a QInitOperation.
qubit_arrayCreate a new 1-D qubit register and emit its QInitOperation.
rangeSymbolic range for use in qkernel for-loops.
resetReset a qubit to the |0> state.
rxRotation around X-axis: RX(angle) = exp(-i * angle/2 * X).
ryRotation around Y-axis: RY(angle) = exp(-i * angle/2 * Y).
rzRotation around Z-axis: RZ(angle) = exp(-i * angle/2 * Z).
rzzRZZ gate: exp(-i * angle/2 * Z ⊗ Z).
sS gate (square root of Z).
sdgS-dagger gate (inverse of S gate).
selectCreate a quantum multiplexer (SELECT) over a list of unitaries.
shor_order_findingCreate an executable order-finding qkernel for base mod modulus.
swapSWAP gate: exchanges two qubits.
tT gate (fourth root of Z).
tdgT-dagger gate (inverse of T gate).
uintCreate a UInt handle from an integer literal or a named parameter.
xPauli-X gate (NOT gate).
yPauli-Y gate.
zPauli-Z gate.
ClassDescription
CallableSignatureDescribe frontend input and output handle types for an opaque callable.
ExpvalJobJob for expectation value computation.
JobAbstract base class for quantum execution jobs.
JobStatusStatus of a quantum job.
KernelEffectDescribe non-unitary behavior reachable from a kernel body.
OracleRepresent an opaque oracle callable.
QKernelDecorator class for Qamomile quantum kernels.
RunJobJob for single execution.
SampleJobJob for sampling execution (multiple shots).
SampleResultResult of a sample() execution.

Functions

bit [source]

def bit(arg: bool | str | int) -> Bit

Create a Bit handle from a boolean/int literal or declare a named Bit parameter.


bit_array [source]

def bit_array(shape: UInt | int | tuple[UInt | int, ...], name: str = 'bits') -> Vector[Bit]

Create a fixed-length classical bit vector initialized to zero.

The vector is represented as an initialized IR constant array, so it can receive measured Bit values through ordinary element assignment and can be returned from a qkernel. Its length must be known while tracing; the emitted classical initializer materializes contents, not a dynamic array shape.

Parameters:

NameTypeDescription
shapeUInt | int | tuple[UInt | int, ...]Number of bits in the vector, given either as a scalar or a one-element tuple. A UInt must resolve to a compile-time constant.
namestrDisplay name for the underlying array value. Defaults to "bits".

Returns:

Vector[Bit] — Vector[Bit]: A fixed-length vector whose elements are initialized to False.

Raises:

Example:

>>> import qamomile.circuit as qmc
>>>
>>> @qmc.qkernel
... def readout() -> qmc.Vector[qmc.Bit]:
...     qubits = qmc.qubit_array(2, "qubits")
...     measured = qmc.measure(qubits)
...     bits = qmc.bit_array(2)
...     bits[0] = measured[0]
...     bits[1] = measured[1]
...     return bits

cast [source]

def cast(source: Vector[Qubit], target_type: type, *, int_bits: int = 0) -> QFixed

Cast a quantum value to a different type without allocating new qubits.

The cast performs a move: the source handle is consumed and cannot be reused after the cast. The returned handle references the same physical qubits.

Parameters:

NameTypeDescription
sourceVector[Qubit]The value to cast (currently supports Vector[Qubit])
target_typetypeThe target type class (currently supports QFixed)
int_bitsintFor QFixed, number of integer bits (default: 0 = all fractional)

Returns:

QFixed — A new handle of the target type referencing the same qubits.

Example:

@qmc.qkernel
def my_circuit():
    phase_register = qmc.qubit_array(5, name="phase")
    # ... apply some operations ...

    # Cast the qubit array to QFixed for measurement
    phase_qfixed = qmc.cast(phase_register, qmc.QFixed, int_bits=0)
    phase_value = qmc.measure(phase_qfixed)
    return phase_value

Raises:


ccx [source]

def ccx(control1: Qubit, control2: Qubit, target: Qubit) -> tuple[Qubit, Qubit, Qubit]

Toffoli (CCX) gate: flips target when both controls are |1>.

Parameters:

NameTypeDescription
control1QubitFirst control qubit.
control2QubitSecond control qubit.
targetQubitTarget qubit.

Returns:

tuple[Qubit, Qubit, Qubit] — Tuple of (control1_out, control2_out, target_out) after CCX.


composite_gate [source]

def composite_gate(
    func: Callable[..., Any] | None = None,
    *,
    name: str = '',
    implementations: Sequence[CallableImplementation] | None = None,
) -> QKernel[..., Any] | Callable[[Callable[..., Any]], QKernel[..., Any]]

Define a named composite using the normal qkernel programming model.

The decorated object is a QKernel. Calls keep their named box in the IR, while build(), draw(), estimate_resources(), control(), and inverse() use the same interface as every other qkernel.

Parameters:

NameTypeDescription
funcCallable[..., Any] | NoneFunction or qkernel to decorate. Defaults to None for decorator-with-arguments use.
namestrPublic callable name. Defaults to the function name.
implementationsSequence[CallableImplementation] | NoneOptional compiler implementation candidates.

Returns:

QKernel[..., Any] | Callable[[Callable[..., Any]], QKernel[..., Any]] — QKernel[..., Any] | Callable[[Callable[..., Any]], QKernel[..., Any]]: Configured qkernel or decorator.

Raises:

Example:

>>> import qamomile.circuit as qmc
>>> @qmc.composite_gate(name="bell_pair")
... def bell_pair(
...     a: qmc.Qubit, b: qmc.Qubit
... ) -> tuple[qmc.Qubit, qmc.Qubit]:
...     a = qmc.h(a)
...     return qmc.cx(a, b)

control [source]

def control(
    qkernel: Oracle | QKernelLike | Callable[..., Any],
    num_controls: int | UInt = 1,
    *,
    control_value: int | None = None,
) -> ControlledGate | _ControlledOracle

Create a controlled version of a quantum gate.

Accepts a @qmc.qkernel-decorated function, a qkernel-backed composite gate callable created by the decorator, an opaque Oracle, or a plain built-in gate callable (qmc.rx, qmc.h, qmc.cp, ...). When given a plain callable, a thin @qkernel wrapper is synthesized automatically by inspecting the callable’s signature, so users no longer need to write a one-line wrapper just to control a primitive gate.

When a wrapped scalar Qubit parameter receives a Vector[Qubit] or VectorView[Qubit], the complete scalar unitary is applied independently to every element. This is the tensor-product operation produced by an explicit per-element loop, so a scalar body’s global phase accumulates once per element. To attach one phase to the whole register instead, wrap a qkernel whose parameter itself is Vector[Qubit].

Parameters:

NameTypeDescription
qkernelOracle | QKernelLike | Callable[..., Any]A qkernel-like object defining the gate to control, an Oracle, or a built-in gate callable whose parameters are annotated with Qubit, Float / float, or UInt / int (possibly inside a Union such as Union[Qubit, Vector[Qubit]]).
num_controlsint | UIntNumber of control qubits (default: 1). Can be int (concrete) or UInt (symbolic).
control_valueint | NoneComputational-basis value that activates the controlled unitary. Controls are flattened in call order, with Vector / VectorView elements taken from index zero upward; the first flattened control is bit zero. None preserves the ordinary all-ones behavior. Only concrete num_controls is supported. Defaults to None.

Returns:

ControlledGate | _ControlledOracle — For a qkernel or gate callable, a ControlledGate that can be called ControlledGate | _ControlledOracle — with (*controls, *targets, power=..., global_phase=..., **params). ControlledGate | _ControlledOracle — The call-site phase has semantics ControlledGate | _ControlledOraclecontrol((exp(i * global_phase) * U) ** power) and therefore becomes ControlledGate | _ControlledOracle — relative phase on the all-active control subspace. power, ControlledGate | _ControlledOracleglobal_phase, and control_indices are reserved keyword names; ControlledGate | _ControlledOracle — a same-named target parameter can still be supplied positionally. For ControlledGate | _ControlledOracle — an Oracle, an opaque qubit-only controlled wrapper is returned; ControlledGate | _ControlledOracle — these call-site modifiers are not supported by that wrapper.

Raises:

Example:

Built-in gates can be controlled directly, with no wrapper::

    crx = qmc.control(qmc.rx)
    ctrl_out, tgt_out = crx(ctrl, target, angle=0.5)

    # Target-global phase becomes observable after control.
    ctrl_out, tgt_out = crx(
        ctrl, target, angle=0.5, global_phase=theta
    )

    cch = qmc.control(qmc.h, num_controls=2)
    c0, c1, tgt = cch(ctrl0, ctrl1, target)

    # Fire only when (ctrl0, ctrl1) represents integer 2. The first
    # control is bit zero, so the required pattern is (0, 1).
    on_two = qmc.control(qmc.x, num_controls=2, control_value=2)
    ctrl0, ctrl1, target = on_two(ctrl0, ctrl1, target)

``@qmc.qkernel`` arguments are still supported for cases that need
custom logic::

    @qmc.qkernel
    def rx_then_h(q: Qubit, theta: float) -> Qubit:
        q = qmc.rx(q, theta)
        q = qmc.h(q)
        return q

    ctrl_out, tgt_out = qmc.control(rx_then_h)(ctrl, target, theta=0.5)

Qkernel-backed composite gate callables can also be controlled directly::

    controlled_gate = qmc.control(my_composite_gate)
    ctrl_out, tgt0_out, tgt1_out = controlled_gate(ctrl, tgt0, tgt1)

cp [source]

def cp(
    control: Qubit,
    target: Qubit,
    theta: float | Float | UInt,
) -> tuple[Qubit, Qubit]

Apply a controlled phase gate.

Parameters:

NameTypeDescription
controlQubitControl input qubit.
targetQubitTarget input qubit.
thetafloat | Float | UIntPhase angle in radians.

Returns:

tuple[Qubit, Qubit] — tuple[Qubit, Qubit]: Fresh control and target handles.

Raises:


cx [source]

def cx(control: Qubit, target: Qubit) -> tuple[Qubit, Qubit]

CNOT (Controlled-X) gate.


cz [source]

def cz(control: Qubit, target: Qubit) -> tuple[Qubit, Qubit]

CZ (Controlled-Z) gate.


ekera_hastad_factoring [source]

def ekera_hastad_factoring(
    generator: int,
    modulus: int,
    *,
    window_size: int = 2,
) -> QKernel[..., qmc.Vector[qmc.Bit]]

Create the quantum short-DLP stage for Ekerå–Håstad factoring.

For a balanced semiprime N = p*q, this measures the two modular phase schedules associated with g and y**-1, where y = g**(N + 1) mod N. Their precisions are 2m and m for m = ceil(n / 2) + 1. Both schedules recycle the same phase qubit and arithmetic workspace; classical lattice post-processing remains outside this qkernel.

Parameters:

NameTypeDescription
generatorintGroup element g coprime to modulus.
modulusintBalanced semiprime to factor.
window_sizeintLookup width for modular multiplication. Defaults to 2.

Returns:

QKernel[..., qmc.Vector[qmc.Bit]] — QKernel[..., qmc.Vector[qmc.Bit]]: Argument-free kernel returning the 2m long-schedule bits followed by the m short-schedule bits. Each group is little-endian.

Raises:


expval [source]

def expval(
    qubits: Qubit | Vector[Qubit] | tuple[Qubit, ...],
    hamiltonian: Observable,
) -> Float

Compute the expectation value of an observable on a quantum state.

This function computes <psi|H|psi> where psi is the quantum state represented by qubits and H is the Hamiltonian observable.

The quantum state is consumed by this operation: expval classifies as :attr:ConsumeMode.DESTRUCTIVE, the same category as measure / cast. Conceptually an Estimator runs many shots of the state to estimate the expectation, so the qubits cannot be reused afterwards. Any attempt to access the same qubits / view slots after expval is rejected as use-after-destroy, both at trace time and post-fold in the IR.

Parameters:

NameTypeDescription
qubitsQubit | Vector[Qubit] | tuple[Qubit, ...]The quantum register holding the prepared state. A single Qubit handle is accepted for 1-qubit observables. When a Vector is passed all previously-borrowed elements must have been returned (the strict-return policy is enforced by consume here). When a slice view (VectorView) is passed its covered parent slots become consumed-slot markers so the parent cannot reuse them later.
hamiltonianObservableThe Observable parameter representing the Hamiltonian. The actual qamomile.observable.Hamiltonian is provided via transpile(..., bindings={...}).

Returns:

Float — A scalar handle holding the expectation value, suitable for use as the kernel return value or as an operand to further classical operations.

Raises:

Example:

import qamomile.circuit as qm
import qamomile.observable as qm_o

# Build Hamiltonian in Python
H = qm_o.Z(0) * qm_o.Z(1) + 0.5 * (qm_o.X(0) + qm_o.X(1))

@qm.qkernel
def vqe_step(q: qm.Vector[qm.Qubit], H: qm.Observable) -> qm.Float:
    # Ansatz
    q[0] = qm.ry(q[0], theta)
    q[0], q[1] = qm.cx(q[0], q[1])

    # Expectation value -> Float (q is consumed here)
    return qm.expval(q, H)

# Pass Hamiltonian via bindings
executable = transpiler.transpile(vqe_step, bindings={"H": H})

float_ [source]

def float_(arg: float | str) -> Float

Create a Float handle from a float literal or declare a named Float parameter.


for_items [source]

def for_items(
    d: Dict,
    key_var_names: list[str],
    value_var_name: str,
) -> Generator[tuple[Any, Any], None, None]

Create a traced for-items loop in the Qamomile frontend.

This context manager creates a ForItemsOperation that iterates over dictionary (key, value) pairs. The operation is always unrolled at transpile time since quantum backends cannot natively iterate over classical data structures.

Parameters:

NameTypeDescription
dDictDict handle whose compile-time-known entries are iterated.
key_var_nameslist[str]Names of key-unpacking variables, for example ["i", "j"] for tuple keys.
value_var_namestrDisplay name of the item-value variable.

Yields:

tuple[typing.Any, typing.Any] — tuple[typing.Any, typing.Any]: Key handle(s) and the typed scalar value handle used while tracing the loop body.

Raises:

Example:

@qkernel
def ising_cost(
    q: Vector[Qubit],
    ising: Dict[Tuple[UInt, UInt], Float],
    gamma: Float,
) -> Vector[Qubit]:
    for (i, j), Jij in qmc.items(ising):
        q[i], q[j] = qmc.rzz(q[i], q[j], gamma * Jij)
    return q

global_phase [source]

def global_phase(target: QKernel | Callable[..., Any], phase: PhaseValue) -> GlobalPhaseGate

Apply a qkernel call followed by exp(i * phase).

The phase is represented as a zero-qubit operation and is retained even when it is not observable in the surrounding program. A reversible qkernel containing the operation acquires an observable relative phase when it is coherently controlled. Measurement, reset, allocation, classical outputs, and classical-only qkernels remain valid for ordinary standalone use.

Parameters:

NameTypeDescription
targetQKernel | Callable[..., Any]QKernel or gate-like callable whose call is followed by the global phase.
phasefloat | int | FloatPhase angle in radians, supplied as a Qamomile Float handle or Python numeric literal.

Returns:

GlobalPhaseGate — Callable wrapper with the target’s call interface.

Raises:

Example:

>>> import qamomile.circuit as qmc
>>> @qmc.qkernel
... def step(q: qmc.Qubit) -> qmc.Qubit:
...     return qmc.x(q)
>>> @qmc.qkernel
... def phased_step(q: qmc.Qubit) -> qmc.Qubit:
...     return qmc.global_phase(step, 0.7)(q)

h [source]

def h(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

Hadamard gate.

Applied to a single Qubit it returns the transformed qubit. Applied to a Vector[Qubit] it broadcasts the gate over every element via a transpile-time loop, equivalent to for i in qmc.range(n): qs[i] = h(qs[i]).

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit] to apply H to.

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


inverse [source]

def inverse(target: QKernelLike | Callable[..., Any]) -> Any

Create an inverse operation wrapper.

Native Qamomile gate functions are first synthesized into tiny QKernel objects, then inverted with the same block walker used for user-defined kernels. Qkernel-like composite gate callables created by qmc.composite_gate reuse their wrapped qkernel body. Known QFT/IQFT functions map directly to their counterpart so backend-native composite emission remains available.

Parameters:

NameTypeDescription
targetQKernelLike | Callable[..., Any]Native gate function, qkernel-like object, or supported stdlib function to invert.

Returns:

Any — A callable inverse wrapper, or the opposite QFT/IQFT function.

Raises:

Example:

>>> import qamomile.circuit as qmc
>>> @qmc.qkernel
... def layer(q: qmc.Qubit, angle: qmc.Float) -> qmc.Qubit:
...     q = qmc.h(q)
...     q = qmc.rz(q, angle)
...     return q
>>> @qmc.qkernel
... def circuit(angle: qmc.Float) -> qmc.Qubit:
...     q = qmc.qubit("q")
...     q = layer(q, angle)
...     q = qmc.inverse(layer)(q, angle)
...     return q

items [source]

def items(d: Dict) -> DictItemsIterator

Iterate over dictionary key-value pairs.

This function returns an iterator over (key, value) pairs from a Dict. Used for iterating over Ising coefficients and similar data structures.

Example:

for (i, j), Jij in qmc.items(ising):
    q[i], q[j] = qmc.rzz(q[i], q[j], gamma * Jij)

Parameters:

NameTypeDescription
dDictA Dict handle to iterate over

Returns:

DictItemsIterator — DictItemsIterator yielding (key, value) pairs


measure [source]

def measure(target: Union[Qubit, QFixed, Vector[Qubit]]) -> Union[Bit, Float, Vector[Bit]]

Measure a qubit or QFixed in the computational basis.

Performs a projective measurement in the Z-basis. The quantum resource is consumed by this operation and cannot be used afterwards.

Parameters:

NameTypeDescription
targetQubit | QFixed | Vector[Qubit]Quantum resource to measure. - Qubit: Returns a classical Bit - QFixed: Returns a Float (decoded from measured bits)

Returns:

Union[Bit, Float, Vector[Bit]] — Bit | Float | Vector[Bit]: Classical result matching the input shape.

Raises:

Example:

@qkernel
def measure_qubit(q: Qubit) -> Bit:
    q = h(q)
    return measure(q)

@qkernel
def measure_qfixed(qf: QFixed) -> Float:
    # After QPE, qf holds phase bits
    return measure(qf)

measure_reset [source]

def measure_reset(qubit: Qubit) -> tuple[Qubit, Bit]

Measure a qubit in the Z basis and reset it to |0>.

Parameters:

NameTypeDescription
qubitQubitQubit to measure and reset.

Returns:

tuple[Qubit, Bit] — tuple[Qubit, Bit]: Reset qubit handle and measurement bit.

Raises:


opaque [source]

def opaque(
    name: str,
    num_qubits: int | None = None,
    *,
    num_control_qubits: int = 0,
    signature: CallableSignature | None = None,
    cost: Any | None = None,
) -> Oracle

Create an opaque callable for top-down circuit design.

Parameters:

NameTypeDescription
namestrHuman-readable callable name.
num_qubitsint | NoneNumber of target qubits consumed and returned by the callable. Defaults to None when signature carries the shape contract.
num_control_qubitsintNumber of explicit scalar control qubits required by scalar calls. Defaults to 0.
signatureCallableSignature | NoneOptional frontend signature. Defaults to None.
costAny | NoneOptional ResourceEstimate or callable accepting an OpaqueCallContext. Defaults to None.

Returns:

Oracle — Opaque callable backed by InvokeOperation with no body.


p [source]

def p(
    target: Union[Qubit, Vector[Qubit]],
    theta: float | Float | UInt,
) -> Union[Qubit, Vector[Qubit]]

Phase gate: P(theta)|1> = e^{i*theta}|1>.

Broadcasts the same theta over every qubit when called with a Vector[Qubit].

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit] to apply the phase to.
thetafloat | Float | UIntPhase angle in radians.

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


pauli_evolve [source]

def pauli_evolve(q: Vector[Qubit], hamiltonian: Observable, gamma: Float) -> Vector[Qubit]

Apply exp(-i * gamma * H) to a qubit register.

Implements Hamiltonian time evolution using the Pauli gadget technique. The actual Hamiltonian is provided via bindings at transpile time.

Each backend can use native implementations:

Parameters:

NameTypeDescription
qVector[Qubit] | VectorView[Qubit]The quantum register to evolve. It may have more qubits than the Hamiltonian acts on: each Pauli term addresses register elements positionally (PauliOperator.index i acts on q[i]), and qubits beyond hamiltonian.num_qubits evolve under the identity.
hamiltonianObservableObservable parameter referencing the Hamiltonian. The actual qamomile.observable.Hamiltonian is provided via bindings. A Hamiltonian acting on more qubits than q provides fails with EmitError at transpile time.
gammaFloatEvolution time / variational parameter.

Returns:

Vector[Qubit] — Vector[Qubit]: The evolved qubit register.

Example:

import qamomile.circuit as qmc
import qamomile.observable as qm_o

H = 0.5 * qm_o.X(0) * qm_o.Z(1) + qm_o.Z(0)

@qmc.qkernel
def cost_layer(
    q: qmc.Vector[qmc.Qubit],
    H: qmc.Observable,
    gamma: qmc.Float,
) -> qmc.Vector[qmc.Qubit]:
    q = qmc.pauli_evolve(q, H, gamma)
    return q

transpiler = QiskitTranspiler()
exe = transpiler.transpile(cost_layer, bindings={"H": H, "gamma": 0.5})

project_x [source]

def project_x(qubit: Qubit) -> tuple[Qubit, Bit]

Project a qubit in the X basis and keep the projected state.

Parameters:

NameTypeDescription
qubitQubitQubit to project. The input handle is consumed.

Returns:

tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.

Raises:


project_y [source]

def project_y(qubit: Qubit) -> tuple[Qubit, Bit]

Project a qubit in the Y basis and keep the projected state.

Parameters:

NameTypeDescription
qubitQubitQubit to project. The input handle is consumed.

Returns:

tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.

Raises:


project_z [source]

def project_z(qubit: Qubit) -> tuple[Qubit, Bit]

Project a qubit in the Z basis and keep the projected state.

Parameters:

NameTypeDescription
qubitQubitQubit to project. The input handle is consumed.

Returns:

tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.

Raises:


qkernel [source]

def qkernel(func: Callable[P, R]) -> QKernel[P, R]

Decorator to define a Qamomile quantum kernel.

Parameters:

NameTypeDescription
funcCallable[P, R]The function to decorate.

Returns:

QKernel[P, R] — An instance of QKernel wrapping the function.


qubit [source]

def qubit(name: str) -> Qubit

Create a new qubit and emit a QInitOperation.


qubit_array [source]

def qubit_array(shape: UInt | int | tuple[UInt | int, ...], name: str) -> Vector[Qubit]

Create a new 1-D qubit register and emit its QInitOperation.

Parameters:

NameTypeDescription
shapeUInt | int | tuple[UInt | int, ...]Number of qubits in the register, given either as a scalar or as a 1-tuple. Tuples with more than one dimension are rejected (see Raises).
namestrName for the underlying ArrayValue.

Returns:

Vector[Qubit] — Vector[Qubit]: A 1-D quantum register handle of the requested size.

Raises:


range [source]

def range(
    stop_or_start: int | UInt,
    stop: int | UInt | None = None,
    step: int | UInt = 1,
) -> Iterator[UInt]

Symbolic range for use in qkernel for-loops.

This function accepts UInt (symbolic) values and is transformed by the AST transformer into for_loop() calls.

Example:

for i in qmc.range(n):          # 0 to n-1
for i in qmc.range(start, stop):  # start to stop-1
for i in qmc.range(start, stop, step):

reset [source]

def reset(qubit: Qubit) -> Qubit

Reset a qubit to the |0> state.

Parameters:

NameTypeDescription
qubitQubitQubit to reset. The input handle is consumed.

Returns:

Qubit — Fresh handle for the reset qubit.

Raises:


rx [source]

def rx(
    target: Union[Qubit, Vector[Qubit]],
    angle: float | Float | UInt,
) -> Union[Qubit, Vector[Qubit]]

Rotation around X-axis: RX(angle) = exp(-i * angle/2 * X).

Broadcasts the same angle over every qubit when called with a Vector[Qubit].

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].
anglefloat | Float | UIntRotation angle in radians.

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


ry [source]

def ry(
    target: Union[Qubit, Vector[Qubit]],
    angle: float | Float | UInt,
) -> Union[Qubit, Vector[Qubit]]

Rotation around Y-axis: RY(angle) = exp(-i * angle/2 * Y).

Broadcasts the same angle over every qubit when called with a Vector[Qubit].

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].
anglefloat | Float | UIntRotation angle in radians.

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


rz [source]

def rz(
    target: Union[Qubit, Vector[Qubit]],
    angle: float | Float | UInt,
) -> Union[Qubit, Vector[Qubit]]

Rotation around Z-axis: RZ(angle) = exp(-i * angle/2 * Z).

Broadcasts the same angle over every qubit when called with a Vector[Qubit].

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].
anglefloat | Float | UIntRotation angle in radians.

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


rzz [source]

def rzz(
    qubit_0: Qubit,
    qubit_1: Qubit,
    angle: float | Float | UInt,
) -> tuple[Qubit, Qubit]

RZZ gate: exp(-i * angle/2 * Z ⊗ Z).

The RZZ gate applies a rotation around the ZZ axis on two qubits.

Parameters:

NameTypeDescription
qubit_0QubitFirst input qubit.
qubit_1QubitSecond input qubit.
anglefloat | Float | UIntRotation angle in radians.

Returns:

tuple[Qubit, Qubit] — tuple[Qubit, Qubit]: Fresh handles after the RZZ operation.

Raises:


s [source]

def s(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

S gate (square root of Z).

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


sdg [source]

def sdg(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

S-dagger gate (inverse of S gate).

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


select [source]

def select(
    cases: Sequence['QKernel | Callable[..., Any]'],
    num_index_qubits: int | UInt | None = None,
) -> SelectGate

Create a quantum multiplexer (SELECT) over a list of unitaries.

The returned gate applies cases[i] to a shared target register when the index register reads the integer i with index qubit zero as the least-significant bit. len(cases) need not be a power of two; index values >= len(cases) apply no operation.

A scalar Qubit case called with a Vector[Qubit] or VectorView[Qubit] target is applied independently to every element. This is the same tensor-product unitary as an explicit per-element loop, including one copy of the scalar case’s global phase per element. A phase intended for the complete register belongs on a case whose parameter is itself Vector[Qubit].

Circuit-family lowering retains the abstract SELECT identity while its portable fallback invokes each case under the corresponding mixed 0/1 (anti-/normal) index pattern.

Parameters:

NameTypeDescription
casesSequence[QKernel | Callable[..., Any]]The case unitaries in ascending index order. Each may be a @qmc.qkernel function, a qkernel-backed composite gate, or a built-in gate callable. All cases must share the same parameter signature and act on the same target register.
num_index_qubitsint | UInt | NoneNumber of leading index qubits. None infers the minimal width from the case count. A wider concrete value leaves its unassigned index states as identity. UInt defers the width check to transpilation. Defaults to None.

Returns:

SelectGate — A callable applied as sel(index, *targets, **params).

Raises:

Example:

>>> import qamomile.circuit as qm
>>> @qm.qkernel
... def pick() -> qm.Vector[qm.Bit]:
...     idx = qm.qubit_array(2, name="idx")
...     idx = qm.h(idx)
...     t = qm.qubit(name="t")
...     idx, t = qm.select([qm.x, qm.y, qm.z, qm.h])(idx, t)
...     return qm.measure(idx)

shor_order_finding [source]

def shor_order_finding(
    base: int,
    modulus: int,
    *,
    window_size: int = 2,
    precision: int | None = None,
) -> QKernel[..., qmc.Vector[qmc.Bit]]

Create an executable order-finding qkernel for base mod modulus.

The modulus fixes the work-register width, so the returned kernel has no artificial n runtime argument. It uses one recycled phase qubit and measurement feed-forward instead of a coherent 2n counting register. With fixed window_size, the body therefore has 3n + O(1) peak width and O(n**3) gates at the default 2n phase precision.

Parameters:

NameTypeDescription
baseintInteger whose multiplicative order should be found.
modulusintComposite modulus greater than two.
window_sizeintLookup width for modular multiplication. Defaults to 2.
precisionint | NoneNumber of measured phase bits. Defaults to twice modulus.bit_length().

Returns:

QKernel[..., qmc.Vector[qmc.Bit]] — QKernel[..., qmc.Vector[qmc.Bit]]: Argument-free executable kernel returning little-endian phase bits.

Raises:

Example:

>>> order_finding = shor_order_finding(base=2, modulus=15)
>>> estimate = order_finding.estimate_resources()
>>> estimate.qubits
21

swap [source]

def swap(qubit_0: Qubit, qubit_1: Qubit) -> tuple[Qubit, Qubit]

SWAP gate: exchanges two qubits.

The SWAP gate swaps the states of two qubits.

Parameters:

NameTypeDescription
qubit_0QubitFirst qubit.
qubit_1QubitSecond qubit.

Returns:

tuple[Qubit, Qubit] — Tuple of (qubit_0_out, qubit_1_out) after SWAP.


t [source]

def t(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

T gate (fourth root of Z).

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


tdg [source]

def tdg(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

T-dagger gate (inverse of T gate).

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


uint [source]

def uint(arg: int | str) -> UInt

Create a UInt handle from an integer literal or a named parameter.

Parameters:

NameTypeDescription
argint | strAn integer literal to bake in as a compile-time constant, or a str naming a symbolic UInt parameter. A bool is rejected: True / False are not valid integer values here even though bool subclasses int. (Sign is not validated here -- a negative literal is accepted and baked in as-is.)

Returns:

UInt — A constant-valued handle for an int argument, or a named symbolic handle for a str argument.

Raises:


x [source]

def x(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

Pauli-X gate (NOT gate).

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


y [source]

def y(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

Pauli-Y gate.

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:


z [source]

def z(target: Union[Qubit, Vector[Qubit]]) -> Union[Qubit, Vector[Qubit]]

Pauli-Z gate.

Broadcasts over a Vector[Qubit] when applied to one.

Parameters:

NameTypeDescription
targetUnion[Qubit, Vector[Qubit]]A single Qubit or a Vector[Qubit].

Returns:

Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.

Raises:

Classes

CallableSignature [source]

class CallableSignature

Describe frontend input and output handle types for an opaque callable.

This class is intentionally a small frontend helper. It lets users write signature-shaped APIs such as opaque(name, signature=...) without exposing the compiler-facing CallableDef model.

Parameters:

NameTypeDescription
inputslist[Any]Frontend handle annotations accepted by the callable.
outputslist[Any]Frontend handle annotations produced by the callable.

Constructor

def __init__(self, inputs: list[Any], outputs: list[Any]) -> None

Attributes

Methods

accepts_single_qubit_vector
def accepts_single_qubit_vector(self) -> bool

Return whether this signature is a one-vector quantum callable.

Returns:

boolTrue when both input and output are exactly one boolVector[Qubit]-style annotation.

scalar_qubit_input_count
def scalar_qubit_input_count(self) -> int | None

Return scalar-qubit arity when the signature is scalar-only.

Returns:

int | None — int | None: Number of scalar Qubit inputs, or None when int | None — the signature contains a vector register.

to_ir_signature
def to_ir_signature(self) -> Signature

Convert the frontend signature into an IR operation signature.

Returns:

Signature — Best-effort IR signature using operation parameter Signature — hints.

Raises:


ExpvalJob [source]

class ExpvalJob(Job[float])

Job for expectation value computation.

Returns a single float representing <psi|H|psi>.

Constructor

def __init__(self, exp_val: float)

Initialize expval job.

Parameters:

NameTypeDescription
exp_valfloatThe computed expectation value

Methods

result
def result(self) -> float

Return the expectation value.

status
def status(self) -> JobStatus

Return job status.


Job [source]

class Job(ABC, Generic[T])

Abstract base class for quantum execution jobs.

A Job represents a quantum execution that can be awaited for results.

Methods

result
def result(self) -> T

Wait for and return the result.

Blocks until the job completes.

Returns:

T — The execution result with the appropriate type.

Raises:

status
def status(self) -> JobStatus

Return the current job status.


JobStatus [source]

class JobStatus(Enum)

Status of a quantum job.

Attributes


KernelEffect [source]

class KernelEffect(enum.Flag)

Describe non-unitary behavior reachable from a kernel body.

KernelEffect.NONE is the empty effect set and denotes unitary behavior. Flags compose with bitwise union so one kernel can expose measurement, reset, and measurement-backed feed-forward together.

Attributes

Methods

labels
def labels(self) -> tuple[str, ...]

Return stable effect names for diagnostics and serialization.

Returns:

tuple[str, ...] — tuple[str, ...]: Active flag names in declaration order.


Oracle [source]

class Oracle

Represent an opaque oracle callable.

Parameters:

NameTypeDescription
namestrHuman-readable oracle name.
num_qubitsint | NoneNumber of target qubits consumed and returned by the oracle. None means the arity is provided by signature and may be vector-shaped.
num_control_qubitsintNumber of explicit control qubits required by scalar calls. Defaults to 0.
signatureCallableSignature | NoneOptional frontend signature. When omitted, a fixed-width scalar/vector-compatible oracle is created from num_qubits.
costAny | NoneOptional explicit cost for this bodyless callable. Pass a ResourceEstimate or a callable accepting an OpaqueCallContext. Defaults to None.

Constructor

def __init__(
    self,
    name: str,
    num_qubits: int | None = None,
    *,
    num_control_qubits: int = 0,
    signature: CallableSignature | None = None,
    cost: Any | None = None,
) -> None

Initialize an opaque oracle callable.

Parameters:

NameTypeDescription
namestrHuman-readable oracle name.
num_qubitsint | NoneFixed scalar/vector width. Defaults to None when signature describes the callable.
num_control_qubitsintNumber of explicit scalar controls. Defaults to 0.
signatureCallableSignature | NoneOptional frontend signature. Defaults to None.
costAny | NoneOptional fixed or context-dependent opaque cost. Defaults to None.

Raises:

Attributes


QKernel [source]

class QKernel(QKernelBuildMixin, QKernelVisualizationMixin, Generic[P, R])

Decorator class for Qamomile quantum kernels.

Constructor

def __init__(self, func: Callable[P, R]) -> None

Attributes


RunJob [source]

class RunJob(Job[T], Generic[T])

Job for single execution.

Returns a single result value matching the kernel’s return type.

Constructor

def __init__(self, raw_counts: dict[str, int], result_converter: Callable[[str], T])

Initialize run job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (should have single entry)
result_converterCallable[[str], T]Function to convert bitstring to typed result

Methods

result
def result(self) -> T

Return the single result.

status
def status(self) -> JobStatus

Return job status.


SampleJob [source]

class SampleJob(Job[SampleResult[T]], Generic[T])

Job for sampling execution (multiple shots).

Returns a SampleResult containing counts for each unique result.

Constructor

def __init__(
    self,
    raw_counts: dict[str, int],
    result_converter: Callable[[dict[str, int]], list[tuple[T, int]]],
    shots: int,
)

Initialize sample job.

Parameters:

NameTypeDescription
raw_countsdict[str, int]Bitstring counts from executor (e.g., {“00”: 512, “11”: 512})
result_converterCallable[[dict[str, int]], list[tuple[T, int]]]Function to convert raw counts to typed results
shotsintNumber of shots executed

Methods

result
def result(self) -> SampleResult[T]

Return the sample result.

status
def status(self) -> JobStatus

Return job status.


SampleResult [source]

class SampleResult(Generic[T])

Result of a sample() execution.

Contains results as a list of (value, count) tuples.

Example:

result.results  # [(0.25, 500), (0.75, 500)]

Constructor

def __init__(self, results: list[tuple[T, int]], shots: int) -> None

Attributes

Methods

most_common
def most_common(self, n: int = 1) -> list[tuple[T, int]]

Return the n most common results.

Parameters:

NameTypeDescription
nintNumber of results to return.

Returns:

list[tuple[T, int]] — List of (result, count) tuples sorted by count descending.

probabilities
def probabilities(self) -> list[tuple[T, float]]

Return probability distribution over results.

Returns:

list[tuple[T, float]] — List of (value, probability) tuples.

Submodules