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.qiskit.runtime

Execute Qiskit circuits on IBM Quantum through Runtime V2 primitives.

Overview

FunctionDescription
hamiltonian_to_sparse_pauli_opConvert qamomile.observable.Hamiltonian to Qiskit SparsePauliOp.
ClassDescription
CircuitInvocationKeep an emitted circuit and runtime parameter values together.
CompletedExecutionHandleWrap an already available result for synchronous executors.
EstimateRequestDescribe one Hamiltonian expectation execution.
ExecutionCapabilitiesDeclare the execution features implemented by one executor.
ExecutionHandleExpose an engine execution without forcing immediate result retrieval.
ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
ParameterMetadataDescribe every scalar slot and runtime array in a compiled segment.
QuantumExecutorAbstract base class for quantum backend execution.
RuntimeExecutionHandleExpose one Runtime primitive job without blocking its submission.
SampleRequestDescribe one sampling execution.
TargetPrecisionRequest an expectation value at a provider target precision.

Functions

hamiltonian_to_sparse_pauli_op [source]

def hamiltonian_to_sparse_pauli_op(hamiltonian: qm_o.Hamiltonian) -> 'SparsePauliOp'

Convert qamomile.observable.Hamiltonian to Qiskit SparsePauliOp.

Parameters:

NameTypeDescription
hamiltonianqm_o.HamiltonianThe qamomile.observable.Hamiltonian to convert

Returns:

'SparsePauliOp' — Qiskit SparsePauliOp representation

Example:

import qamomile.observable as qm_o
from qamomile.qiskit.observable import hamiltonian_to_sparse_pauli_op

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

# Convert to Qiskit
sparse_pauli_op = hamiltonian_to_sparse_pauli_op(H)

Classes

CircuitInvocation [source]

class CircuitInvocation(Generic[CircuitT])

Keep an emitted circuit and runtime parameter values together.

Engines may bind the values into a new circuit or submit them through a native parameter-input API. Keeping both forms available preserves native parameter sweeps and provider-side compilation caches.

Parameters:

NameTypeDescription
circuitCircuitTEmitted engine circuit or kernel artifact.
bindingsMapping[str, Any]Flattened Qamomile runtime bindings.
parameter_metadataParameterMetadataMapping from public parameter names to engine parameter objects.

Constructor

def __init__(
    self,
    circuit: CircuitT,
    bindings: Mapping[str, Any],
    parameter_metadata: ParameterMetadata,
) -> None

Attributes


CompletedExecutionHandle [source]

class CompletedExecutionHandle(ExecutionHandle[ResultT])

Wrap an already available result for synchronous executors.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Constructor

def __init__(self, value: ResultT) -> None

Initialize an immediately completed execution.

Parameters:

NameTypeDescription
valueResultTCompleted execution value.

Methods

result
def result(self, timeout: float | None = None) -> ResultT

Return the completed value without waiting.

Parameters:

NameTypeDescription
timeoutfloat | NoneIgnored compatibility timeout.

Returns:

ResultT — Stored execution value.

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture the already available raw result without waiting.

Returns:

ExecutionSnapshot — Owned, type-preserving local value.

Raises:

status
def status(self) -> JobStatus

Return the completed status.

Returns:

JobStatus — Always :attr:JobStatus.COMPLETED.


EstimateRequest [source]

class EstimateRequest(Generic[CircuitT])

Describe one Hamiltonian expectation execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
hamiltonianqm_o.HamiltonianObservable to evaluate.
accuracyEstimationAccuracy | NoneExplicit accuracy policy. None uses the executor’s configured default.

Constructor

def __init__(
    self,
    invocation: CircuitInvocation[CircuitT],
    hamiltonian: qm_o.Hamiltonian,
    accuracy: EstimationAccuracy | None = None,
) -> None

Attributes


ExecutionCapabilities [source]

class ExecutionCapabilities

Declare the execution features implemented by one executor.

Parameters:

NameTypeDescription
supports_async_samplingboolWhether sampling submission returns before provider execution completes. Defaults to False.
supports_async_estimationboolWhether expectation submission returns before provider execution completes. Defaults to False.
supports_estimationboolWhether expectation-value execution is implemented. Defaults to False.
supports_cancellationboolWhether provider-backed handles can request cancellation. Defaults to False.
supports_restorationboolWhether execution references can recreate provider-backed handles. Defaults to False.
supports_native_batchboolWhether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False.
supports_native_parameter_inputsboolWhether runtime values remain separate from emitted circuits during provider submission. Defaults to False.
estimation_accuracyfrozenset[EstimationPolicyType]Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available.

Raises:

Constructor

def __init__(
    self,
    supports_async_sampling: bool = False,
    supports_async_estimation: bool = False,
    supports_estimation: bool = False,
    supports_cancellation: bool = False,
    supports_restoration: bool = False,
    supports_native_batch: bool = False,
    supports_native_parameter_inputs: bool = False,
    estimation_accuracy: frozenset[EstimationPolicyType] = frozenset(),
) -> None

Attributes


ExecutionHandle [source]

class ExecutionHandle(ABC, Generic[ResultT])

Expose an engine execution without forcing immediate result retrieval.

Attributes

Methods

cancel
def cancel(self) -> None

Request best-effort cancellation.

Cancellation is intentionally not reported as a boolean because providers may accept a request after execution has already started. Call :meth:status to observe the eventual state.

metadata
def metadata(self) -> Mapping[str, Any]

Return optional provider execution metadata.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metadata such as timestamps or usage.

raw_status
def raw_status(self) -> object

Return provider-specific status information.

Returns:

object — Provider status value, or the normalized status when no richer value exists.

references
def references(self) -> tuple[ExecutionReference, ...]

Return serializable remote execution references.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Secret-free provider references.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for and return the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. None delegates the wait policy to the provider.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

result_async
def result_async(self, timeout: float | None = None) -> ResultT

Wait asynchronously for the engine-neutral raw result.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds. Defaults to provider behavior when None.

Returns:

ResultT — Raw result normalized by the engine executor.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture one remote execution without fetching its result.

Adapters exposing several logical references must override this method with an explicit reconstruction structure. A provider reference may itself contain multiple physical job IDs.

Returns:

ExecutionSnapshot — One opaque provider execution.

Raises:

status
def status(self) -> JobStatus

Return the current provider-independent execution status.

Returns:

JobStatus — Current normalized status.


ExecutionReference [source]

class ExecutionReference

Store secret-free identifiers needed to restore remote execution.

Parameters:

NameTypeDescription
providerstrStable provider or adapter name.
job_idstuple[str, ...]One or more provider job identifiers.
targetstr | NoneProvider target or device identifier. Defaults to None.
group_idstr | NoneSession, batch, program, or parent identifier. Defaults to None.
contextMapping[str, str]Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping.

Raises:

Constructor

def __init__(
    self,
    provider: str,
    job_ids: tuple[str, ...],
    target: str | None = None,
    group_id: str | None = None,
    context: Mapping[str, str] = dict(),
) -> None

Attributes

Methods

from_dict
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReference

Reconstruct a provider reference from JSON-compatible data.

Parameters:

NameTypeDescription
dataMapping[str, Any]Mapping produced by :meth:to_dict.

Returns:

ExecutionReference — Validated provider execution reference.

Raises:

to_dict
def to_dict(self) -> dict[str, Any]

Convert the provider reference to JSON-compatible data.

Returns:

dict[str, Any] — dict[str, Any]: Provider identifiers and decoding context without credentials or SDK objects.


ParameterMetadata [source]

class ParameterMetadata

Describe every scalar slot and runtime array in a compiled segment.

Parameters:

NameTypeDescription
parameterslist[ParameterInfo]Ordered scalar engine slots. Defaults to an empty list.
arraysdict[str, ParameterArrayInfo]Explicit runtime-array ABI descriptors keyed by root name. Defaults to descriptors derived from parameters for backward compatibility.

Constructor

def __init__(
    self,
    parameters: list[ParameterInfo] = list(),
    arrays: dict[str, ParameterArrayInfo] = dict(),
) -> None

Attributes

Methods

get_array_names
def get_array_names(self) -> set[str]

Return unique scalar and array root names.

Returns:

set[str] — set[str]: Root name for every emitted parameter.

get_ordered_params
def get_ordered_params(self) -> list[Any]

Return engine parameter objects in ABI definition order.

Returns:

list[Any] — list[Any]: Engine-specific parameter objects.

get_param_by_name
def get_param_by_name(self, name: str) -> ParameterInfo | None

Find one scalar slot by its full emitted key.

Parameters:

NameTypeDescription
namestrFull engine parameter key.

Returns:

ParameterInfo | None — ParameterInfo | None: Matching slot, or None when absent.

merge
@classmethod
def merge(cls, metadata: Sequence[ParameterMetadata]) -> ParameterMetadata

Merge parameter manifests from multiple quantum segments.

Parameters:

NameTypeDescription
metadataSequence[ParameterMetadata]Segment manifests in execution order.

Returns:

ParameterMetadata — Combined manifest with first-seen scalar slot ordering and array descriptors derived across all segments.

to_binding_dict
def to_binding_dict(self, bindings: Mapping[str, Any]) -> dict[Any, Any]

Map indexed user bindings to engine parameter objects.

Parameters:

NameTypeDescription
bindingsMapping[str, Any]Scalar values keyed by full emitted parameter name.

Returns:

dict[Any, Any] — dict[Any, Any]: Engine parameter objects mapped to bound values.

validate_array_shapes
def validate_array_shapes(self, bindings: Mapping[str, Any] | None) -> None

Validate user array rank and every concrete ABI dimension.

Parameters:

NameTypeDescription
bindingsMapping[str, Any] | NoneRaw public bindings before scalar flattening. None means no validation is needed.

Raises:

validate_required_bindings
def validate_required_bindings(self, indexed_bindings: Mapping[str, Any]) -> None

Reject missing scalar slots in an indexed binding map.

Parameters:

NameTypeDescription
indexed_bindingsMapping[str, Any]Flattened user bindings.

Raises:


QuantumExecutor [source]

class QuantumExecutor(ABC, Generic[T])

Abstract base class for quantum backend execution.

To implement a custom executor:

  1. execute() [Required] Execute circuit and return bitstring counts as dict[str, int]. Keys are bitstrings in big-endian format (e.g., “011” means q2=0, q1=1, q0=1).

  2. bind_parameters() [Optional] Bind parameter values to parametric circuits. Override if your executor supports parametric circuits (e.g., QAOA variational circuits). Use ParameterMetadata.to_binding_dict() for easy conversion.

  3. estimate() [Optional] Compute expectation values <psi|H|psi>. Override if your executor supports estimation primitives (e.g., Qiskit Estimator, QURI Parts).

Example (Minimal): class MyExecutor(QuantumExecutor[QuantumCircuit]): def init(self): from qiskit_aer import AerSimulator self.backend = AerSimulator()

    def execute(self, circuit, shots):
        from qiskit import transpile
        if circuit.num_clbits == 0:
            circuit = circuit.copy()
            circuit.measure_all()
        transpiled = transpile(circuit, self.backend)
        return self.backend.run(transpiled, shots=shots).result().get_counts()

Example (With Parameter Binding): def bind_parameters(self, circuit, bindings, metadata): # metadata.to_binding_dict() converts indexed names to engine params return circuit.assign_parameters(metadata.to_binding_dict(bindings))

Attributes

Methods

bind_invocation
def bind_invocation(self, invocation: CircuitInvocation[T]) -> T

Bind one invocation for a backend without native input submission.

Parameters:

NameTypeDescription
invocationCircuitInvocation[T]Circuit, flattened bindings, and engine parameter metadata.

Returns:

T — Bound circuit, or the original circuit when it has no runtime parameters.

bind_parameters
def bind_parameters(
    self,
    circuit: T,
    bindings: dict[str, Any],
    parameter_metadata: ParameterMetadata,
) -> T

Bind parameter values to the circuit.

Default implementation returns the circuit unchanged. Override for backends that support parametric circuits.

Parameters:

NameTypeDescription
circuitTThe parameterized circuit
bindingsdict[str, Any]Dict mapping parameter names (indexed format) to values. e.g., {“gammas[0]”: 0.1, “gammas[1]”: 0.2}
parameter_metadataParameterMetadataMetadata about circuit parameters

Returns:

T — New circuit with parameters bound

estimate
def estimate(
    self,
    circuit: T,
    hamiltonian: 'qm_o.Hamiltonian',
    params: Sequence[float] | None = None,
) -> float

Estimate the expectation value of a Hamiltonian.

This method computes <psi|H|psi> where psi is the quantum state prepared by the circuit and H is the Hamiltonian.

Backends can override this method to provide optimized implementations using their native estimator primitives.

Parameters:

NameTypeDescription
circuitTThe quantum circuit (state preparation ansatz)
hamiltonian'qm_o.Hamiltonian'The qamomile.observable.Hamiltonian to measure
paramsSequence[float] | NoneOptional parameter values for parametric circuits

Returns:

float — The estimated expectation value

Raises:

execute
def execute(self, circuit: T, shots: int) -> dict[str, int]

Execute the circuit and return bitstring counts.

Parameters:

NameTypeDescription
circuitTThe quantum circuit to execute
shotsintNumber of measurement shots

Returns:

dict[str, int] — Dictionary mapping bitstrings to counts. dict[str, int] — {“00”: 512, “11”: 512}

restore
def restore(self, reference: ExecutionReference) -> ExecutionHandle[Any]

Restore a remote execution from a secret-free reference.

Parameters:

NameTypeDescription
referenceExecutionReferenceProvider execution reference.

Returns:

ExecutionHandle[Any] — ExecutionHandle[Any]: Restored provider-backed handle.

Raises:

submit_estimate
def submit_estimate(self, request: EstimateRequest[T]) -> ExecutionHandle[float]

Submit an expectation request through the synchronous path.

Parameters:

NameTypeDescription
requestEstimateRequest[T]Circuit, Hamiltonian, and optional accuracy policy.

Returns:

ExecutionHandle[float] — ExecutionHandle[float]: Completed compatibility handle.

Raises:

submit_estimates
def submit_estimates(
    self,
    requests: Sequence[EstimateRequest[T]],
) -> ExecutionHandle[tuple[float, ...]]

Submit an ordered collection of expectation requests.

Parameters:

NameTypeDescription
requestsSequence[EstimateRequest[T]]Expectation requests.

Returns:

ExecutionHandle[tuple[float, ...]] — ExecutionHandle[tuple[float, ...]]: Composite result handle in request order.

submit_sample
def submit_sample(self, request: SampleRequest[T]) -> ExecutionHandle[dict[str, int]]

Submit a sampling request through the synchronous compatibility path.

Remote executors should override this method and return immediately with a provider-backed handle. Existing synchronous executors inherit this implementation unchanged.

Parameters:

NameTypeDescription
requestSampleRequest[T]Circuit invocation and shot count.

Returns:

ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Completed compatibility handle.

submit_samples
def submit_samples(
    self,
    requests: Sequence[SampleRequest[T]],
) -> ExecutionHandle[tuple[dict[str, int], ...]]

Submit an ordered collection of sampling requests.

Backends with native batch or parameter-sweep support should override this method. The default preserves ordering with individual requests.

Parameters:

NameTypeDescription
requestsSequence[SampleRequest[T]]Sampling requests.

Returns:

ExecutionHandle[tuple[dict[str, int], ...]] — ExecutionHandle[tuple[dict[str, int], ...]]: Composite result handle preserving request order.


RuntimeExecutionHandle [source]

class RuntimeExecutionHandle(ExecutionHandle[ResultT], Generic[ResultT])

Expose one Runtime primitive job without blocking its submission.

Result retrieval runs once in a daemon thread so local wait limits also work with injected Qiskit primitive jobs whose result() method has no timeout argument. Expiring a wait neither cancels nor resubmits the job.

Parameters:

NameTypeDescription
jobAnyNative Runtime or compatible local primitive job.
decoderCallable[[Any], ResultT]Convert the primitive result into a backend-neutral value.
referenceExecutionReference | NoneSecret-free restoration reference. Defaults to none without a restoration service.

Constructor

def __init__(
    self,
    job: Any,
    decoder: Callable[[Any], ResultT],
    reference: ExecutionReference | None = None,
) -> None

Initialize lazy retrieval and provider lifecycle delegation.

Parameters:

NameTypeDescription
jobAnyNative primitive job.
decoderCallable[[Any], ResultT]Result conversion function.
referenceExecutionReference | NoneSerializable restoration reference. Defaults to none.

Attributes

Methods

cancel
def cancel(self) -> None

Request cancellation when the primitive job is unfinished.

Raises:

metadata
def metadata(self) -> Mapping[str, Any]

Return native Runtime job metrics when supported.

Returns:

Mapping[str, Any] — Mapping[str, Any]: Provider metrics or an empty mapping when the local job does not expose metrics.

Raises:

raw_status
def raw_status(self) -> object

Read the native string or Qiskit status enum.

Returns:

object — Unmodified provider status.

Raises:

references
def references(self) -> tuple[ExecutionReference, ...]

Return the job’s secret-free restoration reference when available.

Returns:

tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: One remote reference or an empty tuple when no restoration service was configured.

result
def result(self, timeout: float | None = None) -> ResultT

Wait for the decoded primitive result with a local wait limit.

Successful results and execution failures are cached. A provider-side result-wait timeout permits another retrieval attempt, while an expired local wait leaves the existing retrieval running.

Parameters:

NameTypeDescription
timeoutfloat | NoneMaximum local wait in seconds, including zero for an immediate check. None waits indefinitely.

Returns:

ResultT — Cached or newly decoded primitive result.

Raises:

snapshot
def snapshot(self) -> ExecutionSnapshot

Capture a Runtime reference or an already decoded result.

Restorable jobs retain their provider reference after result retrieval. Without a reference, result retrieval must have completed successfully before capturing its cached value. This method never starts retrieval, queries the provider, or waits for another result caller.

Returns:

ExecutionSnapshot — One remote reference or a detached local value.

Raises:

status
def status(self) -> JobStatus

Return the normalized provider or cached result status.

Returns:

JobStatus — Current provider-independent execution state.

Raises:


SampleRequest [source]

class SampleRequest(Generic[CircuitT])

Describe one sampling execution.

Parameters:

NameTypeDescription
invocationCircuitInvocation[CircuitT]Circuit and runtime inputs.
shotsintNumber of requested samples.

Raises:

Constructor

def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> None

Attributes


TargetPrecision [source]

class TargetPrecision

Request an expectation value at a provider target precision.

Parameters:

NameTypeDescription
precisionfloatPositive absolute target precision.

Raises:

Constructor

def __init__(self, precision: float) -> None

Attributes