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¶
stdlib / algorithm kernels are imported after the frontend symbols because their implementation modules do
import qamomile.circuit as qmc— keep new kernel imports at the bottom of this file.Visualization (
MatplotlibDraweretc.) is lazy-loaded via module__getattr__so that importingqamomile.circuitdoes not pull in matplotlib.
Overview¶
| Function | Description |
|---|---|
bit | Create a Bit handle from a boolean/int literal or declare a named Bit parameter. |
bit_array | Create a fixed-length classical bit vector initialized to zero. |
cast | Cast a quantum value to a different type without allocating new qubits. |
ccx | Toffoli (CCX) gate: flips target when both controls are |1>. |
composite_gate | Define a named composite using the normal qkernel programming model. |
control | Create a controlled version of a quantum gate. |
cp | Apply a controlled phase gate. |
cx | CNOT (Controlled-X) gate. |
cz | CZ (Controlled-Z) gate. |
ekera_hastad_factoring | Create the quantum short-DLP stage for Ekerå–Håstad factoring. |
expval | Compute 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_items | Create a traced for-items loop in the Qamomile frontend. |
global_phase | Apply a qkernel call followed by exp(i * phase). |
h | Hadamard gate. |
inverse | Create an inverse operation wrapper. |
items | Iterate over dictionary key-value pairs. |
measure | Measure a qubit or QFixed in the computational basis. |
measure_reset | Measure a qubit in the Z basis and reset it to |0>. |
opaque | Create an opaque callable for top-down circuit design. |
p | Phase gate: P(theta)|1> = e^{i*theta}|1>. |
pauli_evolve | Apply exp(-i * gamma * H) to a qubit register. |
project_x | Project a qubit in the X basis and keep the projected state. |
project_y | Project a qubit in the Y basis and keep the projected state. |
project_z | Project a qubit in the Z basis and keep the projected state. |
qkernel | Decorator to define a Qamomile quantum kernel. |
qubit | Create a new qubit and emit a QInitOperation. |
qubit_array | Create a new 1-D qubit register and emit its QInitOperation. |
range | Symbolic range for use in qkernel for-loops. |
reset | Reset a qubit to the |0> state. |
rx | Rotation around X-axis: RX(angle) = exp(-i * angle/2 * X). |
ry | Rotation around Y-axis: RY(angle) = exp(-i * angle/2 * Y). |
rz | Rotation around Z-axis: RZ(angle) = exp(-i * angle/2 * Z). |
rzz | RZZ gate: exp(-i * angle/2 * Z ⊗ Z). |
s | S gate (square root of Z). |
sdg | S-dagger gate (inverse of S gate). |
select | Create a quantum multiplexer (SELECT) over a list of unitaries. |
shor_order_finding | Create an executable order-finding qkernel for base mod modulus. |
swap | SWAP gate: exchanges two qubits. |
t | T gate (fourth root of Z). |
tdg | T-dagger gate (inverse of T gate). |
uint | Create a UInt handle from an integer literal or a named parameter. |
x | Pauli-X gate (NOT gate). |
y | Pauli-Y gate. |
z | Pauli-Z gate. |
| Class | Description |
|---|---|
CallableSignature | Describe frontend input and output handle types for an opaque callable. |
ExpvalJob | Job for expectation value computation. |
Job | Abstract base class for quantum execution jobs. |
JobStatus | Status of a quantum job. |
KernelEffect | Describe non-unitary behavior reachable from a kernel body. |
Oracle | Represent an opaque oracle callable. |
QKernel | Decorator class for Qamomile quantum kernels. |
RunJob | Job for single execution. |
SampleJob | Job for sampling execution (multiple shots). |
SampleResult | Result of a sample() execution. |
Functions¶
bit [source]¶
def bit(arg: bool | str | int) -> BitCreate 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:
| Name | Type | Description |
|---|---|---|
shape | UInt | 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. |
name | str | Display 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:
TypeError— Ifshapeornamehas the wrong type.ValueError— If the shape is empty, negative, or not known at trace time.NotImplementedError— If a shape with more than one dimension is requested.
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 bitscast [source]¶
def cast(source: Vector[Qubit], target_type: type, *, int_bits: int = 0) -> QFixedCast 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:
| Name | Type | Description |
|---|---|---|
source | Vector[Qubit] | The value to cast (currently supports Vector[Qubit]) |
target_type | type | The target type class (currently supports QFixed) |
int_bits | int | For 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_valueRaises:
TypeError— If the source type or target type is not supportedValueError— If int_bits is negative or larger than the number of qubits
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:
| Name | Type | Description |
|---|---|---|
control1 | Qubit | First control qubit. |
control2 | Qubit | Second control qubit. |
target | Qubit | Target 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:
| Name | Type | Description |
|---|---|---|
func | Callable[..., Any] | None | Function or qkernel to decorate. Defaults to None for decorator-with-arguments use. |
name | str | Public callable name. Defaults to the function name. |
implementations | Sequence[CallableImplementation] | None | Optional compiler implementation candidates. |
Returns:
QKernel[..., Any] | Callable[[Callable[..., Any]], QKernel[..., Any]] — QKernel[..., Any] | Callable[[Callable[..., Any]], QKernel[..., Any]]:
Configured qkernel or decorator.
Raises:
TypeError— If the decorator target is not callable.
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 | _ControlledOracleCreate 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:
| Name | Type | Description |
|---|---|---|
qkernel | Oracle | 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_controls | int | UInt | Number of control qubits (default: 1). Can be int (concrete) or UInt (symbolic). |
control_value | int | None | Computational-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 | _ControlledOracle — control((exp(i * global_phase) * U) ** power) and therefore becomes
ControlledGate | _ControlledOracle — relative phase on the all-active control subspace. power,
ControlledGate | _ControlledOracle — global_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:
TypeError— Ifqkernelis a callable that cannot be auto-wrapped (missing annotations, unsupported types, or no qubit parameters),control_valueis not a PythonintorNone, or anOraclecontrol count is symbolic.ValueError— Ifnum_controlsis a concreteintless than one,control_valueis out of range, or a non-default value is used with symbolicnum_controls.
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:
| Name | Type | Description |
|---|---|---|
control | Qubit | Control input qubit. |
target | Qubit | Target input qubit. |
theta | float | Float | UInt | Phase angle in radians. |
Returns:
tuple[Qubit, Qubit] — tuple[Qubit, Qubit]: Fresh control and target handles.
Raises:
QubitAliasError— If control and target are the same logical qubit.QubitConsumedError— If either input was already consumed.RuntimeError— If no tracer is active.
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:
| Name | Type | Description |
|---|---|---|
generator | int | Group element g coprime to modulus. |
modulus | int | Balanced semiprime to factor. |
window_size | int | Lookup 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:
ValueError— If the modular map or lookup width is invalid.
expval [source]¶
def expval(
qubits: Qubit | Vector[Qubit] | tuple[Qubit, ...],
hamiltonian: Observable,
) -> FloatCompute 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:
| Name | Type | Description |
|---|---|---|
qubits | Qubit | 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. |
hamiltonian | Observable | The 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:
RuntimeError— If no qkernel tracer is active.QubitConsumedError— Ifqubitswas already consumed (e.g. measured / cast earlier in the kernel), or if any covered slot of a passed view was destroyed by a prior destructive view operation.UnreturnedBorrowError— Ifqubitsis aVectorwith outstanding element or slice-view borrows that have not been returned.
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) -> FloatCreate 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:
| Name | Type | Description |
|---|---|---|
d | Dict | Dict handle whose compile-time-known entries are iterated. |
key_var_names | list[str] | Names of key-unpacking variables, for example ["i", "j"] for tuple keys. |
value_var_name | str | Display 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:
TypeError— Ifdis a runtime-parameter Dict (declared viaparameters=[...]without bound data), or its key annotation cannot be represented by the loop target. A runtime Dict’s key structure is unknown at compile time, so an items() loop cannot be unrolled; only constant-key subscript lookups (d[key]) are supported for runtime-parameter dicts.NotImplementedError— If the Dict value annotation is a container or another type without a scalar frontend handle.ValueError— If the constructed loop has inconsistent region-result metadata.
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 qglobal_phase [source]¶
def global_phase(target: QKernel | Callable[..., Any], phase: PhaseValue) -> GlobalPhaseGateApply 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:
| Name | Type | Description |
|---|---|---|
target | QKernel | Callable[..., Any] | QKernel or gate-like callable whose call is followed by the global phase. |
phase | float | int | Float | Phase angle in radians, supplied as a Qamomile Float handle or Python numeric literal. |
Returns:
GlobalPhaseGate — Callable wrapper with the target’s call interface.
Raises:
TypeError— Iftargetcannot be interpreted as a gate-like callable.
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
inverse [source]¶
def inverse(target: QKernelLike | Callable[..., Any]) -> AnyCreate 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:
| Name | Type | Description |
|---|---|---|
target | QKernelLike | 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:
TypeError— Iftargetcannot be interpreted as a gate-like callable, or if a body-free class-based composite instance is passed directly.NotImplementedError— If an inverted kernel uses unsupported operations such asif/while/for itemscontrol flow,QInit, or aForOperationwhose bounds are not compile-time constants when the inverse wrapper is traced. Loop-carried classical values are supported for UInt carries with a constant additive recurrence and for unchanged Float carries. Nonzero Float recurrences, non-additive recurrences, and coupled carries are rejected uniformly before backend emission.
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 qitems [source]¶
def items(d: Dict) -> DictItemsIteratorIterate 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:
| Name | Type | Description |
|---|---|---|
d | Dict | A 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:
| Name | Type | Description |
|---|---|---|
target | Qubit | 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:
TypeError— Iftargetis not a supported quantum handle.QubitConsumedError— If the quantum resource was already consumed.RuntimeError— If no tracer is active.
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:
| Name | Type | Description |
|---|---|---|
qubit | Qubit | Qubit to measure and reset. |
Returns:
tuple[Qubit, Bit] — tuple[Qubit, Bit]: Reset qubit handle and measurement bit.
Raises:
QubitConsumedError— Ifqubitwas already consumed.RuntimeError— If no tracer is active.
opaque [source]¶
def opaque(
name: str,
num_qubits: int | None = None,
*,
num_control_qubits: int = 0,
signature: CallableSignature | None = None,
cost: Any | None = None,
) -> OracleCreate an opaque callable for top-down circuit design.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Human-readable callable name. |
num_qubits | int | None | Number of target qubits consumed and returned by the callable. Defaults to None when signature carries the shape contract. |
num_control_qubits | int | Number of explicit scalar control qubits required by scalar calls. Defaults to 0. |
signature | CallableSignature | None | Optional frontend signature. Defaults to None. |
cost | Any | None | Optional 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:
| Name | Type | Description |
|---|---|---|
target | Union[Qubit, Vector[Qubit]] | A single Qubit or a Vector[Qubit] to apply the phase to. |
theta | float | Float | UInt | Phase angle in radians. |
Returns:
Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.
Raises:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
Qiskit: PauliEvolutionGate
QuriParts: PauliRotation gates
Others: fallback decomposition (basis change + CNOT ladder + RZ)
Parameters:
| Name | Type | Description |
|---|---|---|
q | Vector[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. |
hamiltonian | Observable | Observable 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. |
gamma | Float | Evolution 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:
| Name | Type | Description |
|---|---|---|
qubit | Qubit | Qubit to project. The input handle is consumed. |
Returns:
tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.
Raises:
QubitConsumedError— Ifqubitwas already consumed.RuntimeError— If no tracer is active.
project_y [source]¶
def project_y(qubit: Qubit) -> tuple[Qubit, Bit]Project a qubit in the Y basis and keep the projected state.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Qubit | Qubit to project. The input handle is consumed. |
Returns:
tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.
Raises:
QubitConsumedError— Ifqubitwas already consumed.RuntimeError— If no tracer is active.
project_z [source]¶
def project_z(qubit: Qubit) -> tuple[Qubit, Bit]Project a qubit in the Z basis and keep the projected state.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Qubit | Qubit to project. The input handle is consumed. |
Returns:
tuple[Qubit, Bit] — tuple[Qubit, Bit]: Projected qubit handle and measurement bit.
Raises:
QubitConsumedError— Ifqubitwas already consumed.RuntimeError— If no tracer is active.
qkernel [source]¶
def qkernel(func: Callable[P, R]) -> QKernel[P, R]Decorator to define a Qamomile quantum kernel.
Parameters:
| Name | Type | Description |
|---|---|---|
func | Callable[P, R] | The function to decorate. |
Returns:
QKernel[P, R] — An instance of QKernel wrapping the function.
qubit [source]¶
def qubit(name: str) -> QubitCreate 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:
| Name | Type | Description |
|---|---|---|
shape | UInt | 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). |
name | str | Name for the underlying ArrayValue. |
Returns:
Vector[Qubit] — Vector[Qubit]: A 1-D quantum register handle of the requested
size.
Raises:
TypeError— Ifshapeornamehas the wrong type.ValueError— Ifshapeis an empty tuple.NotImplementedError— Ifshapehas more than one dimension. The quantum addressing path is rank-1, so a higher-rank register would silently alias distinct elements onto the same physical qubit. Allocate a 1-DVector[Qubit]of the total size and compute flat indices explicitly instead (e.g.q[i * ncols + j]).
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) -> QubitReset a qubit to the |0> state.
Parameters:
| Name | Type | Description |
|---|---|---|
qubit | Qubit | Qubit to reset. The input handle is consumed. |
Returns:
Qubit — Fresh handle for the reset qubit.
Raises:
QubitConsumedError— Ifqubitwas already consumed.RuntimeError— If no tracer is active.
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:
| Name | Type | Description |
|---|---|---|
target | Union[Qubit, Vector[Qubit]] | A single Qubit or a Vector[Qubit]. |
angle | float | Float | UInt | Rotation angle in radians. |
Returns:
Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.
Raises:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[Qubit, Vector[Qubit]] | A single Qubit or a Vector[Qubit]. |
angle | float | Float | UInt | Rotation angle in radians. |
Returns:
Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.
Raises:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[Qubit, Vector[Qubit]] | A single Qubit or a Vector[Qubit]. |
angle | float | Float | UInt | Rotation angle in radians. |
Returns:
Union[Qubit, Vector[Qubit]] — A Qubit for scalar input, a Vector[Qubit] for array input.
Raises:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
qubit_0 | Qubit | First input qubit. |
qubit_1 | Qubit | Second input qubit. |
angle | float | Float | UInt | Rotation angle in radians. |
Returns:
tuple[Qubit, Qubit] — tuple[Qubit, Qubit]: Fresh handles after the RZZ operation.
Raises:
QubitAliasError— If both inputs are the same logical qubit.QubitConsumedError— If either input was already consumed.RuntimeError— If no tracer is active.
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
select [source]¶
def select(
cases: Sequence['QKernel | Callable[..., Any]'],
num_index_qubits: int | UInt | None = None,
) -> SelectGateCreate 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:
| Name | Type | Description |
|---|---|---|
cases | Sequence[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_qubits | int | UInt | None | Number 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:
ValueError— If fewer than two cases are supplied, a concrete width is too small, or the cases do not share an identical parameter signature. Case-body footprint and unitarity are validated when the returned gate is called.TypeError— If the width has an unsupported type or a case cannot be wrapped into a qkernel.
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:
| Name | Type | Description |
|---|---|---|
base | int | Integer whose multiplicative order should be found. |
modulus | int | Composite modulus greater than two. |
window_size | int | Lookup width for modular multiplication. Defaults to 2. |
precision | int | None | Number 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:
ValueError— If the inputs do not define a reversible modular map.
Example:
>>> order_finding = shor_order_finding(base=2, modulus=15)
>>> estimate = order_finding.estimate_resources()
>>> estimate.qubits
21swap [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:
| Name | Type | Description |
|---|---|---|
qubit_0 | Qubit | First qubit. |
qubit_1 | Qubit | Second 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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
uint [source]¶
def uint(arg: int | str) -> UIntCreate a UInt handle from an integer literal or a named parameter.
Parameters:
| Name | Type | Description |
|---|---|---|
arg | int | str | An 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:
TypeError— Ifargis neither a plainintnor astr(in particular, if it is abool).
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
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:
| Name | Type | Description |
|---|---|---|
target | Union[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:
TypeError— Iftargetis neither aQubitnor aVector[Qubit].
Classes¶
CallableSignature [source]¶
class CallableSignatureDescribe 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:
| Name | Type | Description |
|---|---|---|
inputs | list[Any] | Frontend handle annotations accepted by the callable. |
outputs | list[Any] | Frontend handle annotations produced by the callable. |
Constructor¶
def __init__(self, inputs: list[Any], outputs: list[Any]) -> NoneAttributes¶
inputs: list[Any]outputs: list[Any]
Methods¶
accepts_single_qubit_vector¶
def accepts_single_qubit_vector(self) -> boolReturn whether this signature is a one-vector quantum callable.
Returns:
bool — True when both input and output are exactly one
bool — Vector[Qubit]-style annotation.
scalar_qubit_input_count¶
def scalar_qubit_input_count(self) -> int | NoneReturn 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) -> SignatureConvert the frontend signature into an IR operation signature.
Returns:
Signature — Best-effort IR signature using operation parameter
Signature — hints.
Raises:
TypeError— If a frontend type cannot map to an IR value type.
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:
| Name | Type | Description |
|---|---|---|
exp_val | float | The computed expectation value |
Methods¶
result¶
def result(self) -> floatReturn the expectation value.
status¶
def status(self) -> JobStatusReturn 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) -> TWait for and return the result.
Blocks until the job completes.
Returns:
T — The execution result with the appropriate type.
Raises:
ExecutionError— If the job failed.
status¶
def status(self) -> JobStatusReturn the current job status.
JobStatus [source]¶
class JobStatus(Enum)Status of a quantum job.
Attributes¶
COMPLETEDFAILEDPENDINGRUNNING
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¶
FEED_FORWARDMEASUREMENTNONERESETis_unitary: bool Return whether this is the empty effect set.
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 OracleRepresent an opaque oracle callable.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Human-readable oracle name. |
num_qubits | int | None | Number of target qubits consumed and returned by the oracle. None means the arity is provided by signature and may be vector-shaped. |
num_control_qubits | int | Number of explicit control qubits required by scalar calls. Defaults to 0. |
signature | CallableSignature | None | Optional frontend signature. When omitted, a fixed-width scalar/vector-compatible oracle is created from num_qubits. |
cost | Any | None | Optional 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,
) -> NoneInitialize an opaque oracle callable.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Human-readable oracle name. |
num_qubits | int | None | Fixed scalar/vector width. Defaults to None when signature describes the callable. |
num_control_qubits | int | Number of explicit scalar controls. Defaults to 0. |
signature | CallableSignature | None | Optional frontend signature. Defaults to None. |
cost | Any | None | Optional fixed or context-dependent opaque cost. Defaults to None. |
Raises:
ValueError— If neithernum_qubitsnorsignaturesupplies enough arity information.
Attributes¶
cost: Any | Nonename: strnum_control_qubits: intnum_qubits: int | Nonesignature: CallableSignature | None
QKernel [source]¶
class QKernel(QKernelBuildMixin, QKernelVisualizationMixin, Generic[P, R])Decorator class for Qamomile quantum kernels.
Constructor¶
def __init__(self, func: Callable[P, R]) -> NoneAttributes¶
block: Block Compile the function to a hierarchical Block if not already compiled.effects: KernelEffect Return cached semantic effects of this qkernel.funcnameraw_funcsignature
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:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | Bitstring counts from executor (should have single entry) |
result_converter | Callable[[str], T] | Function to convert bitstring to typed result |
Methods¶
result¶
def result(self) -> TReturn the single result.
status¶
def status(self) -> JobStatusReturn 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:
| Name | Type | Description |
|---|---|---|
raw_counts | dict[str, int] | Bitstring counts from executor (e.g., {“00”: 512, “11”: 512}) |
result_converter | Callable[[dict[str, int]], list[tuple[T, int]]] | Function to convert raw counts to typed results |
shots | int | Number of shots executed |
Methods¶
result¶
def result(self) -> SampleResult[T]Return the sample result.
status¶
def status(self) -> JobStatusReturn 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) -> NoneAttributes¶
results: list[tuple[T, int]] List of (value, count) tuples.shots: int Total number of shots executed.
Methods¶
most_common¶
def most_common(self, n: int = 1) -> list[tuple[T, int]]Return the n most common results.
Parameters:
| Name | Type | Description |
|---|---|---|
n | int | Number 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.