qBraid execution integration for Qamomile (executor-only, no transpiler).
Design intent: unlike the other engine packages, qBraid provides no
emit pass or GateEmitter of its own. QBraidExecutor
(executor.py) implements circuit’s QuantumExecutor[QuantumCircuit]
protocol over circuits already emitted by the Qiskit engine, routing
them to qBraid-accessible devices through the qBraid runtime. Compile
with QiskitTranspiler, execute with QBraidExecutor.
Constraints:
Depends only on
qamomile.circuit(plus the optionalqbraidandqiskitSDKs); never imported by circuit or other engines.Execution requires qBraid credentials (API key /
QbraidProvider), so this integration is out of scope for the mandatory cross-engine test matrix; tests must gate on credentials and skip otherwise.estimate()is counts-based and rejects circuits with pre-existing classical bits rather than risk silently wrong results.
Overview¶
| Class | Description |
|---|---|
QBraidExecutor | Quantum executor that runs Qiskit circuits on qBraid-supported devices. |
Classes¶
QBraidExecutor [source]¶
class QBraidExecutor(QuantumExecutor['QuantumCircuit'])Quantum executor that runs Qiskit circuits on qBraid-supported devices.
This executor implements the QuantumExecutor[QuantumCircuit] contract,
allowing ExecutableProgram.sample(), measured run(), and
expectation-value run() to work with any qBraid-accessible backend.
The estimate() method uses a counts-based measurement approach. It
only supports circuits with num_clbits == 0 (no pre-existing classical
bits). Circuits with existing classical bits are rejected with an
ExecutionError to prevent silent wrong results caused by qBraid’s
counts normalization removing register separators.
Endian convention:
execute() returns canonical Qiskit-style bitstring keys after
normalization. Keys are big-endian classical-bit strings: the
leftmost character is the highest classical-bit index and the
rightmost character is classical bit 0. QBraidExecutor never
reverses or permutes the bit order; normalization only removes spaces
and zero-pads under-width keys.
estimate() uses the same bitstring convention when reconstructing
expectation values from counts. Since it applies measure_all() to a
circuit with no pre-existing classical bits, classical bit i
measures qubit i. Therefore, in estimate() the rightmost count
character corresponds to qubit 0 and the leftmost character to the
highest qubit index.
Parameters:
| Name | Type | Description |
|---|---|---|
device | Any | None | A pre-configured qBraid QuantumDevice. Mutually exclusive with device_id, provider, and api_key. |
device_id | str | None | qBraid device identifier (e.g., "qbraid_qir_simulator"). |
provider | Any | None | A QbraidProvider instance for device lookup. |
api_key | str | None | qBraid API key, used to create a QbraidProvider when provider is not given. |
expval_shots | int | Number of shots for each basis-rotation circuit in estimate(). Defaults to 4096. |
timeout | int | None | Timeout in seconds for wait_for_final_state(). None means wait indefinitely. |
poll_interval | int | Polling interval in seconds for wait_for_final_state(). Defaults to 5. |
run_kwargs | dict[str, Any] | None | Extra keyword arguments forwarded to device.run(). Must not contain "shots" — use the shots parameter of execute() instead. |
Raises:
ValueError— If constructor arguments are inconsistent (e.g.,devicecombined withdevice_id).
Example (device_id + api_key)::
executor = QBraidExecutor(
device_id="qbraid_qir_simulator",
api_key="your-api-key",
)Example (pre-configured device)::
from qbraid import QbraidProvider
provider = QbraidProvider(api_key="...")
device = provider.get_device("qbraid_qir_simulator")
executor = QBraidExecutor(device=device)Constructor¶
def __init__(
self,
device: Any | None = None,
*,
device_id: str | None = None,
provider: Any | None = None,
api_key: str | None = None,
expval_shots: int = 4096,
timeout: int | None = None,
poll_interval: int = 5,
run_kwargs: dict[str, Any] | None = None,
) -> NoneInitialize qBraid device access and execution policy.
Parameters:
| Name | Type | Description |
|---|---|---|
device | Any | None | Pre-configured qBraid device. Mutually exclusive with identifier and credential arguments. |
device_id | str | None | qBraid device identifier. Defaults to None. |
provider | Any | None | Provider used to resolve device_id. Defaults to None. |
api_key | str | None | API key used when constructing a provider. Defaults to None. |
expval_shots | int | Positive shots per expectation basis group. Defaults to 4096. |
timeout | int | None | Default result wait timeout in seconds. Defaults to no timeout. |
poll_interval | int | Positive provider polling interval in seconds. Defaults to five. |
run_kwargs | dict[str, Any] | None | Additional qBraid submission options. Defaults to None. |
Raises:
ValueError— If device arguments conflict, required identifiers are missing, numeric wait options are invalid, orrun_kwargscontains an executor-owned key.
Attributes¶
capabilities: ExecutionCapabilities Describe qBraid features implemented by this executor.deviceexpval_shotspoll_intervalrun_kwargstimeout
Methods¶
bind_parameters¶
def bind_parameters(
self,
circuit: 'QuantumCircuit',
bindings: dict[str, Any],
parameter_metadata: ParameterMetadata,
) -> 'QuantumCircuit'Bind parameter values to the Qiskit circuit.
Uses the same indexed-binding semantics as QiskitExecutor.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The parameterized circuit. |
bindings | dict[str, Any] | Dict mapping parameter names to values. |
parameter_metadata | ParameterMetadata | Metadata about circuit parameters. |
Returns:
'QuantumCircuit' — New circuit with parameters bound.
estimate¶
def estimate(
self,
circuit: 'QuantumCircuit',
hamiltonian: 'qm_o.Hamiltonian',
params: Sequence[float] | None = None,
) -> floatEstimate the expectation value of a Hamiltonian using counts.
This method decomposes the Hamiltonian into Pauli terms, groups them by measurement basis, applies basis-rotation gates, and reconstructs the expectation value from measurement counts.
Only circuits with num_clbits == 0 are supported. Circuits with
pre-existing classical bits are rejected because qBraid’s counts
normalization removes register separators, making it impossible to
reliably identify which measured bits correspond to which qubits.
Count bitstrings are interpreted using the same big-endian convention
as Qiskit counts: the leftmost character is the highest measured qubit
index and the rightmost character is qubit 0. This follows directly
from calling measure_all() on a circuit whose classical-bit indices
match its qubit indices.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The state-preparation circuit (no measurements). |
hamiltonian | 'qm_o.Hamiltonian' | The Hamiltonian whose expectation value is computed. |
params | Sequence[float] | None | Optional parameter values for parametric circuits. Values are bound positionally in Qiskit circuit parameter order. If None, the circuit must already have all parameters bound. |
Returns:
float — The estimated real-valued expectation value.
Raises:
ExecutionError— If the circuit has existing classical bits, if the Hamiltonian references qubit indices outside the circuit width, if the circuit has unbound parameters after binding, or if the result has a non-negligible imaginary part.
execute¶
def execute(self, circuit: 'QuantumCircuit', shots: int) -> dict[str, int]Execute circuit and return bitstring counts.
If the circuit has no classical bits, measure_all() is added
automatically (on a copy).
Returned keys use canonical Qiskit-style big-endian classical-bit
order: the leftmost character is the highest classical-bit index and
the rightmost character is classical bit 0. execute() does not
reinterpret those keys as qubit-ordered strings.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The quantum circuit to execute. |
shots | int | Number of measurement shots. |
Returns:
dict[str, int] — Dictionary mapping canonical big-endian classical-bit strings
dict[str, int] — to counts.
submit_estimate¶
def submit_estimate(self, request: EstimateRequest['QuantumCircuit']) -> ExecutionHandle[float]Submit counts-based expectation tasks without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
request | EstimateRequest[QuantumCircuit] | Circuit invocation, Hamiltonian, and optional shot policy. |
Returns:
ExecutionHandle[float] — ExecutionHandle[float]: Lazy aggregate expectation handle.
Raises:
ValueError— If exact or target-precision estimation is requested.ExecutionError— If the circuit or Hamiltonian cannot be estimated safely through normalized counts.
submit_sample¶
def submit_sample(
self,
request: SampleRequest['QuantumCircuit'],
) -> ExecutionHandle[dict[str, int]]Submit qBraid sampling without waiting for the remote result.
Parameters:
| Name | Type | Description |
|---|---|---|
request | SampleRequest[QuantumCircuit] | Circuit invocation and requested shot count. |
Returns:
ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Lazy qBraid sampling handle.
Raises:
ValueError— If runtime bindings are incomplete or run options contain a reserved key.Exception— Any qBraid submission failure.
qamomile.qbraid.execution¶
Adapt qBraid quantum jobs to Qamomile execution handles.
Overview¶
| Class | Description |
|---|---|
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
ExecutionReference | Store secret-free identifiers needed to restore remote execution. |
JobStatus | Describe a provider-independent execution state. |
QBraidExecutionHandle | Expose one qBraid sampling job through the shared lifecycle API. |
Classes¶
ExecutionHandle [source]¶
class ExecutionHandle(ABC, Generic[ResultT])Expose an engine execution without forcing immediate result retrieval.
Attributes¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
ExecutionReference [source]¶
class ExecutionReferenceStore secret-free identifiers needed to restore remote execution.
Parameters:
| Name | Type | Description |
|---|---|---|
provider | str | Stable provider or adapter name. |
job_ids | tuple[str, ...] | One or more provider job identifiers. |
target | str | None | Provider target or device identifier. Defaults to None. |
group_id | str | None | Session, batch, program, or parent identifier. Defaults to None. |
context | Mapping[str, str] | Additional non-secret identifiers needed to restore the job. Defaults to an empty mapping. |
Raises:
ValueError— If the provider name or any job identifier is empty.TypeError— If identifiers or context have incompatible types.
Constructor¶
def __init__(
self,
provider: str,
job_ids: tuple[str, ...],
target: str | None = None,
group_id: str | None = None,
context: Mapping[str, str] = dict(),
) -> NoneAttributes¶
context: Mapping[str, str]group_id: str | Nonejob_ids: tuple[str, ...]provider: strtarget: str | None
Methods¶
from_dict¶
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ExecutionReferenceReconstruct a provider reference from JSON-compatible data.
Parameters:
| Name | Type | Description |
|---|---|---|
data | Mapping[str, Any] | Mapping produced by :meth:to_dict. |
Returns:
ExecutionReference — Validated provider execution reference.
Raises:
KeyError— If a required provider or job identifier field is absent.TypeError— If a field has an incompatible type.ValueError— If provider or job identifiers are empty.
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.
JobStatus [source]¶
class JobStatus(Enum)Describe a provider-independent execution state.
The numeric values of the original four states remain stable for serialization compatibility.
Attributes¶
CANCELLEDCANCELLINGCOMPLETEDFAILEDPARTIALPENDINGQUEUEDRUNNINGUNKNOWN
QBraidExecutionHandle [source]¶
class QBraidExecutionHandle(ExecutionHandle[dict[str, int]])Expose one qBraid sampling job through the shared lifecycle API.
Parameters:
| Name | Type | Description |
|---|---|---|
job | Any | qBraid QuantumJob or compatible object. |
decoder | Callable[[Any], dict[str, int]] | Function converting the native result to normalized bitstring counts. |
target | str | None | qBraid device identifier. Defaults to None. |
timeout | float | None | Default provider wait timeout in seconds. Defaults to None. |
poll_interval | float | Provider polling interval in seconds. |
Raises:
ValueError— Ifpoll_intervalis not positive.
Constructor¶
def __init__(
self,
job: Any,
decoder: Callable[[Any], dict[str, int]],
*,
target: str | None,
timeout: float | None,
poll_interval: float,
) -> NoneInitialize a lazy qBraid execution handle.
Parameters:
| Name | Type | Description |
|---|---|---|
job | Any | Native qBraid job. |
decoder | Callable[[Any], dict[str, int]] | Native result decoder. |
target | str | None | qBraid device identifier. |
timeout | float | None | Default provider wait timeout in seconds. |
poll_interval | float | Positive provider polling interval. |
Raises:
ValueError— Ifpoll_intervalis not positive.
Attributes¶
native: object | None Return the wrapped qBraid job.
Methods¶
cancel¶
def cancel(self) -> NoneRequest best-effort cancellation from qBraid.
metadata¶
def metadata(self) -> Mapping[str, Any]Return native qBraid job metadata when available.
Returns:
Mapping[str, Any] — Mapping[str, Any]: Provider metadata, or an empty mapping.
raw_status¶
def raw_status(self) -> objectReturn the native qBraid status value.
Returns:
object — Provider status enum or string.
references¶
def references(self) -> tuple[ExecutionReference, ...]Return the qBraid job identifier when the SDK exposes one.
Returns:
tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: One qBraid reference, or an empty
tuple for jobs without a stable identifier.
result¶
def result(self, timeout: float | None = None) -> dict[str, int]Wait for and decode the qBraid result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum wait in seconds. None uses the executor-configured timeout. |
Returns:
dict[str, int] — dict[str, int]: Normalized big-endian bitstring counts.
Raises:
TimeoutError— If the provider does not complete within the timeout.Exception— Any qBraid wait, retrieval, or decoding failure.
status¶
def status(self) -> JobStatusReturn the normalized qBraid job status.
Returns:
JobStatus — Current provider-independent state.
qamomile.qbraid.executor¶
qBraid executor integration for Qamomile.
This module provides QBraidExecutor, which bridges Qamomile’s compiled Qiskit circuits to qBraid-supported quantum devices via the qBraid runtime.
Example:
from qamomile.qbraid import QBraidExecutor
executor = QBraidExecutor(device_id="qbraid_qir_simulator")
counts = executor.execute(circuit, shots=1000)Overview¶
| Class | Description |
|---|---|
CircuitInvocation | Keep an emitted circuit and runtime parameter values together. |
CompletedExecutionHandle | Wrap an already available result for synchronous executors. |
CompositeExecutionHandle | Aggregate several independently submitted executions. |
EstimateRequest | Describe one Hamiltonian expectation execution. |
Exact | Request an analytic expectation value without shot noise. |
ExecutionCapabilities | Declare the execution features implemented by one executor. |
ExecutionError | Error during program execution. |
ExecutionHandle | Expose an engine execution without forcing immediate result retrieval. |
MappedExecutionHandle | Lazily transform another execution handle’s result. |
QBraidExecutionHandle | Expose one qBraid sampling job through the shared lifecycle API. |
QBraidExecutor | Quantum executor that runs Qiskit circuits on qBraid-supported devices. |
SampleRequest | Describe one sampling execution. |
ShotBased | Request a shot-based expectation value. |
TargetPrecision | Request an expectation value at a provider target precision. |
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:
| Name | Type | Description |
|---|---|---|
circuit | CircuitT | Emitted engine circuit or kernel artifact. |
bindings | Mapping[str, Any] | Flattened Qamomile runtime bindings. |
parameter_metadata | ParameterMetadata | Mapping from public parameter names to engine parameter objects. |
Constructor¶
def __init__(
self,
circuit: CircuitT,
bindings: Mapping[str, Any],
parameter_metadata: ParameterMetadata,
) -> NoneAttributes¶
bindings: Mapping[str, Any]circuit: CircuitTparameter_metadata: ParameterMetadata
CompletedExecutionHandle [source]¶
class CompletedExecutionHandle(ExecutionHandle[ResultT])Wrap an already available result for synchronous executors.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Constructor¶
def __init__(self, value: ResultT) -> NoneInitialize an immediately completed execution.
Parameters:
| Name | Type | Description |
|---|---|---|
value | ResultT | Completed execution value. |
Methods¶
result¶
def result(self, timeout: float | None = None) -> ResultTReturn the completed value without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Ignored compatibility timeout. |
Returns:
ResultT — Stored execution value.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture the already available raw result without waiting.
Returns:
ExecutionSnapshot — Owned, type-preserving local value.
Raises:
TypeError— If the value contains unsupported result objects.ValueError— If the value is nonfinite or cyclic.
status¶
def status(self) -> JobStatusReturn the completed status.
Returns:
JobStatus — Always :attr:JobStatus.COMPLETED.
CompositeExecutionHandle [source]¶
class CompositeExecutionHandle(ExecutionHandle[tuple[ResultT, ...]])Aggregate several independently submitted executions.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions in stable result order. |
Constructor¶
def __init__(self, handles: Sequence[ExecutionHandle[ResultT]]) -> NoneInitialize an ordered execution aggregate.
Parameters:
| Name | Type | Description |
|---|---|---|
handles | Sequence[ExecutionHandle[ResultT]] | Child executions. |
Attributes¶
native: object | None Return every child provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneAttempt cancellation of every child not known to be terminal.
A status lookup failure leaves the child’s state unknown, so cancellation is still attempted. Failures are reported together after all children have been visited, retaining the original exceptions and tracebacks.
Raises:
ExceptionGroup— If any child status lookup or cancellation fails.
metadata¶
def metadata(self) -> Mapping[str, Any]Return metadata grouped by child index.
Returns:
Mapping[str, Any] — Mapping[str, Any]: Child metadata sequence.
raw_status¶
def raw_status(self) -> objectReturn every child provider status.
Returns:
object — Tuple of child raw statuses.
references¶
def references(self) -> tuple[ExecutionReference, ...]Return the legacy one-reference-per-child view.
This flat view cannot preserve child boundaries when a child exposes
zero or multiple references. Use :meth:snapshot to retain local
results and nested groups in their original positions.
Returns:
tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Ordered child references, or an
empty tuple when any child does not expose exactly one.
result¶
def result(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results in submission order.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
result_async¶
def result_async(self, timeout: float | None = None) -> tuple[ResultT, ...]Return all child results asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Total local wait budget in seconds. |
Returns:
tuple[ResultT, ...] — tuple[ResultT, ...]: Ordered child results.
Raises:
TimeoutError— If the total wait budget expires.Exception— Any child execution failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture all children with their original tuple boundaries.
Returns:
ExecutionSnapshot — Ordered nested execution structure.
Raises:
ValueError— If a child has no supported reconstruction contract.TypeError— If a local child contains unsupported result objects.
status¶
def status(self) -> JobStatusAggregate child statuses without hiding partial completion.
Returns:
JobStatus — Aggregate execution status.
EstimateRequest [source]¶
class EstimateRequest(Generic[CircuitT])Describe one Hamiltonian expectation execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
hamiltonian | qm_o.Hamiltonian | Observable to evaluate. |
accuracy | EstimationAccuracy | None | Explicit accuracy policy. None uses the executor’s configured default. |
Constructor¶
def __init__(
self,
invocation: CircuitInvocation[CircuitT],
hamiltonian: qm_o.Hamiltonian,
accuracy: EstimationAccuracy | None = None,
) -> NoneAttributes¶
accuracy: EstimationAccuracy | Nonehamiltonian: qm_o.Hamiltonianinvocation: CircuitInvocation[CircuitT]
Exact [source]¶
class ExactRequest an analytic expectation value without shot noise.
Constructor¶
def __init__(self) -> NoneExecutionCapabilities [source]¶
class ExecutionCapabilitiesDeclare the execution features implemented by one executor.
Parameters:
| Name | Type | Description |
|---|---|---|
supports_async_sampling | bool | Whether sampling submission returns before provider execution completes. Defaults to False. |
supports_async_estimation | bool | Whether expectation submission returns before provider execution completes. Defaults to False. |
supports_estimation | bool | Whether expectation-value execution is implemented. Defaults to False. |
supports_cancellation | bool | Whether provider-backed handles can request cancellation. Defaults to False. |
supports_restoration | bool | Whether execution references can recreate provider-backed handles. Defaults to False. |
supports_native_batch | bool | Whether multiple logical requests can be submitted through one provider-native batch or job. Defaults to False. |
supports_native_parameter_inputs | bool | Whether runtime values remain separate from emitted circuits during provider submission. Defaults to False. |
estimation_accuracy | frozenset[EstimationPolicyType] | Explicit per-request accuracy policies accepted by the executor. An empty set means only executor-configured estimation behavior is available. |
Raises:
ValueError— If an unknown estimation policy type is declared or estimation features are declared without estimation support.
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(),
) -> NoneAttributes¶
estimation_accuracy: frozenset[EstimationPolicyType]supports_async_estimation: boolsupports_async_sampling: boolsupports_cancellation: boolsupports_estimation: boolsupports_native_batch: boolsupports_native_parameter_inputs: boolsupports_restoration: bool
ExecutionError [source]¶
class ExecutionError(QamomileCompileError)Error during program execution.
ExecutionHandle [source]¶
class ExecutionHandle(ABC, Generic[ResultT])Expose an engine execution without forcing immediate result retrieval.
Attributes¶
native: object | None Return the wrapped provider-native task when available.
Methods¶
cancel¶
def cancel(self) -> NoneRequest 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) -> objectReturn 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) -> ResultTWait for and return the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. None delegates the wait policy to the provider. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
result_async¶
def result_async(self, timeout: float | None = None) -> ResultTWait asynchronously for the engine-neutral raw result.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. Defaults to provider behavior when None. |
Returns:
ResultT — Raw result normalized by the engine executor.
Raises:
TimeoutError— If the local wait expires before completion.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture 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:
ValueError— If references are absent or their grouping is unknown.
status¶
def status(self) -> JobStatusReturn the current provider-independent execution status.
Returns:
JobStatus — Current normalized status.
MappedExecutionHandle [source]¶
class MappedExecutionHandle(ExecutionHandle[MappedT], Generic[ResultT, MappedT])Lazily transform another execution handle’s result.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Whether the owning executable reconstructs this transformation when restoring the source. Defaults to False. |
Constructor¶
def __init__(
self,
source: ExecutionHandle[ResultT],
transform: Callable[[ResultT], MappedT],
*,
snapshot_source: bool = False,
) -> NoneInitialize a lazy mapped execution.
Parameters:
| Name | Type | Description |
|---|---|---|
source | ExecutionHandle[ResultT] | Underlying execution handle. |
transform | Callable[[ResultT], MappedT] | Result transformation. |
snapshot_source | bool | Allow source snapshots only when the owner rebuilds the transformation on restore. Defaults to False. |
Attributes¶
native: object | None Return the source provider-native task.
Methods¶
cancel¶
def cancel(self) -> NoneForward a cancellation request to the source execution.
metadata¶
def metadata(self) -> Mapping[str, Any]Return source execution metadata.
Returns:
Mapping[str, Any] — Mapping[str, Any]: Source metadata.
raw_status¶
def raw_status(self) -> objectReturn the source provider status.
Returns:
object — Provider-specific source status.
references¶
def references(self) -> tuple[ExecutionReference, ...]Return source execution references.
Returns:
tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: Source references.
result¶
def result(self, timeout: float | None = None) -> MappedTRetrieve and transform the source result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
result_async¶
def result_async(self, timeout: float | None = None) -> MappedTRetrieve and transform the source result asynchronously.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum local wait in seconds. |
Returns:
MappedT — Cached transformed result.
Raises:
Exception— Any source or transformation failure.
snapshot¶
def snapshot(self) -> ExecutionSnapshotCapture a source whose mapping is rebuilt by its owning executable.
Python callables are never serialized. Arbitrary mappings must supply an adapter-specific restoration recipe instead of losing conversion.
Returns:
ExecutionSnapshot — Source reconstruction structure.
Raises:
ValueError— If the mapping has no declared restoration contract.TypeError— If a local source value cannot be saved.
status¶
def status(self) -> JobStatusReturn the source execution status.
Returns:
JobStatus — Current mapped execution status.
QBraidExecutionHandle [source]¶
class QBraidExecutionHandle(ExecutionHandle[dict[str, int]])Expose one qBraid sampling job through the shared lifecycle API.
Parameters:
| Name | Type | Description |
|---|---|---|
job | Any | qBraid QuantumJob or compatible object. |
decoder | Callable[[Any], dict[str, int]] | Function converting the native result to normalized bitstring counts. |
target | str | None | qBraid device identifier. Defaults to None. |
timeout | float | None | Default provider wait timeout in seconds. Defaults to None. |
poll_interval | float | Provider polling interval in seconds. |
Raises:
ValueError— Ifpoll_intervalis not positive.
Constructor¶
def __init__(
self,
job: Any,
decoder: Callable[[Any], dict[str, int]],
*,
target: str | None,
timeout: float | None,
poll_interval: float,
) -> NoneInitialize a lazy qBraid execution handle.
Parameters:
| Name | Type | Description |
|---|---|---|
job | Any | Native qBraid job. |
decoder | Callable[[Any], dict[str, int]] | Native result decoder. |
target | str | None | qBraid device identifier. |
timeout | float | None | Default provider wait timeout in seconds. |
poll_interval | float | Positive provider polling interval. |
Raises:
ValueError— Ifpoll_intervalis not positive.
Attributes¶
native: object | None Return the wrapped qBraid job.
Methods¶
cancel¶
def cancel(self) -> NoneRequest best-effort cancellation from qBraid.
metadata¶
def metadata(self) -> Mapping[str, Any]Return native qBraid job metadata when available.
Returns:
Mapping[str, Any] — Mapping[str, Any]: Provider metadata, or an empty mapping.
raw_status¶
def raw_status(self) -> objectReturn the native qBraid status value.
Returns:
object — Provider status enum or string.
references¶
def references(self) -> tuple[ExecutionReference, ...]Return the qBraid job identifier when the SDK exposes one.
Returns:
tuple[ExecutionReference, ...] — tuple[ExecutionReference, ...]: One qBraid reference, or an empty
tuple for jobs without a stable identifier.
result¶
def result(self, timeout: float | None = None) -> dict[str, int]Wait for and decode the qBraid result once.
Parameters:
| Name | Type | Description |
|---|---|---|
timeout | float | None | Maximum wait in seconds. None uses the executor-configured timeout. |
Returns:
dict[str, int] — dict[str, int]: Normalized big-endian bitstring counts.
Raises:
TimeoutError— If the provider does not complete within the timeout.Exception— Any qBraid wait, retrieval, or decoding failure.
status¶
def status(self) -> JobStatusReturn the normalized qBraid job status.
Returns:
JobStatus — Current provider-independent state.
QBraidExecutor [source]¶
class QBraidExecutor(QuantumExecutor['QuantumCircuit'])Quantum executor that runs Qiskit circuits on qBraid-supported devices.
This executor implements the QuantumExecutor[QuantumCircuit] contract,
allowing ExecutableProgram.sample(), measured run(), and
expectation-value run() to work with any qBraid-accessible backend.
The estimate() method uses a counts-based measurement approach. It
only supports circuits with num_clbits == 0 (no pre-existing classical
bits). Circuits with existing classical bits are rejected with an
ExecutionError to prevent silent wrong results caused by qBraid’s
counts normalization removing register separators.
Endian convention:
execute() returns canonical Qiskit-style bitstring keys after
normalization. Keys are big-endian classical-bit strings: the
leftmost character is the highest classical-bit index and the
rightmost character is classical bit 0. QBraidExecutor never
reverses or permutes the bit order; normalization only removes spaces
and zero-pads under-width keys.
estimate() uses the same bitstring convention when reconstructing
expectation values from counts. Since it applies measure_all() to a
circuit with no pre-existing classical bits, classical bit i
measures qubit i. Therefore, in estimate() the rightmost count
character corresponds to qubit 0 and the leftmost character to the
highest qubit index.
Parameters:
| Name | Type | Description |
|---|---|---|
device | Any | None | A pre-configured qBraid QuantumDevice. Mutually exclusive with device_id, provider, and api_key. |
device_id | str | None | qBraid device identifier (e.g., "qbraid_qir_simulator"). |
provider | Any | None | A QbraidProvider instance for device lookup. |
api_key | str | None | qBraid API key, used to create a QbraidProvider when provider is not given. |
expval_shots | int | Number of shots for each basis-rotation circuit in estimate(). Defaults to 4096. |
timeout | int | None | Timeout in seconds for wait_for_final_state(). None means wait indefinitely. |
poll_interval | int | Polling interval in seconds for wait_for_final_state(). Defaults to 5. |
run_kwargs | dict[str, Any] | None | Extra keyword arguments forwarded to device.run(). Must not contain "shots" — use the shots parameter of execute() instead. |
Raises:
ValueError— If constructor arguments are inconsistent (e.g.,devicecombined withdevice_id).
Example (device_id + api_key)::
executor = QBraidExecutor(
device_id="qbraid_qir_simulator",
api_key="your-api-key",
)Example (pre-configured device)::
from qbraid import QbraidProvider
provider = QbraidProvider(api_key="...")
device = provider.get_device("qbraid_qir_simulator")
executor = QBraidExecutor(device=device)Constructor¶
def __init__(
self,
device: Any | None = None,
*,
device_id: str | None = None,
provider: Any | None = None,
api_key: str | None = None,
expval_shots: int = 4096,
timeout: int | None = None,
poll_interval: int = 5,
run_kwargs: dict[str, Any] | None = None,
) -> NoneInitialize qBraid device access and execution policy.
Parameters:
| Name | Type | Description |
|---|---|---|
device | Any | None | Pre-configured qBraid device. Mutually exclusive with identifier and credential arguments. |
device_id | str | None | qBraid device identifier. Defaults to None. |
provider | Any | None | Provider used to resolve device_id. Defaults to None. |
api_key | str | None | API key used when constructing a provider. Defaults to None. |
expval_shots | int | Positive shots per expectation basis group. Defaults to 4096. |
timeout | int | None | Default result wait timeout in seconds. Defaults to no timeout. |
poll_interval | int | Positive provider polling interval in seconds. Defaults to five. |
run_kwargs | dict[str, Any] | None | Additional qBraid submission options. Defaults to None. |
Raises:
ValueError— If device arguments conflict, required identifiers are missing, numeric wait options are invalid, orrun_kwargscontains an executor-owned key.
Attributes¶
capabilities: ExecutionCapabilities Describe qBraid features implemented by this executor.deviceexpval_shotspoll_intervalrun_kwargstimeout
Methods¶
bind_parameters¶
def bind_parameters(
self,
circuit: 'QuantumCircuit',
bindings: dict[str, Any],
parameter_metadata: ParameterMetadata,
) -> 'QuantumCircuit'Bind parameter values to the Qiskit circuit.
Uses the same indexed-binding semantics as QiskitExecutor.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The parameterized circuit. |
bindings | dict[str, Any] | Dict mapping parameter names to values. |
parameter_metadata | ParameterMetadata | Metadata about circuit parameters. |
Returns:
'QuantumCircuit' — New circuit with parameters bound.
estimate¶
def estimate(
self,
circuit: 'QuantumCircuit',
hamiltonian: 'qm_o.Hamiltonian',
params: Sequence[float] | None = None,
) -> floatEstimate the expectation value of a Hamiltonian using counts.
This method decomposes the Hamiltonian into Pauli terms, groups them by measurement basis, applies basis-rotation gates, and reconstructs the expectation value from measurement counts.
Only circuits with num_clbits == 0 are supported. Circuits with
pre-existing classical bits are rejected because qBraid’s counts
normalization removes register separators, making it impossible to
reliably identify which measured bits correspond to which qubits.
Count bitstrings are interpreted using the same big-endian convention
as Qiskit counts: the leftmost character is the highest measured qubit
index and the rightmost character is qubit 0. This follows directly
from calling measure_all() on a circuit whose classical-bit indices
match its qubit indices.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The state-preparation circuit (no measurements). |
hamiltonian | 'qm_o.Hamiltonian' | The Hamiltonian whose expectation value is computed. |
params | Sequence[float] | None | Optional parameter values for parametric circuits. Values are bound positionally in Qiskit circuit parameter order. If None, the circuit must already have all parameters bound. |
Returns:
float — The estimated real-valued expectation value.
Raises:
ExecutionError— If the circuit has existing classical bits, if the Hamiltonian references qubit indices outside the circuit width, if the circuit has unbound parameters after binding, or if the result has a non-negligible imaginary part.
execute¶
def execute(self, circuit: 'QuantumCircuit', shots: int) -> dict[str, int]Execute circuit and return bitstring counts.
If the circuit has no classical bits, measure_all() is added
automatically (on a copy).
Returned keys use canonical Qiskit-style big-endian classical-bit
order: the leftmost character is the highest classical-bit index and
the rightmost character is classical bit 0. execute() does not
reinterpret those keys as qubit-ordered strings.
Parameters:
| Name | Type | Description |
|---|---|---|
circuit | 'QuantumCircuit' | The quantum circuit to execute. |
shots | int | Number of measurement shots. |
Returns:
dict[str, int] — Dictionary mapping canonical big-endian classical-bit strings
dict[str, int] — to counts.
submit_estimate¶
def submit_estimate(self, request: EstimateRequest['QuantumCircuit']) -> ExecutionHandle[float]Submit counts-based expectation tasks without waiting.
Parameters:
| Name | Type | Description |
|---|---|---|
request | EstimateRequest[QuantumCircuit] | Circuit invocation, Hamiltonian, and optional shot policy. |
Returns:
ExecutionHandle[float] — ExecutionHandle[float]: Lazy aggregate expectation handle.
Raises:
ValueError— If exact or target-precision estimation is requested.ExecutionError— If the circuit or Hamiltonian cannot be estimated safely through normalized counts.
submit_sample¶
def submit_sample(
self,
request: SampleRequest['QuantumCircuit'],
) -> ExecutionHandle[dict[str, int]]Submit qBraid sampling without waiting for the remote result.
Parameters:
| Name | Type | Description |
|---|---|---|
request | SampleRequest[QuantumCircuit] | Circuit invocation and requested shot count. |
Returns:
ExecutionHandle[dict[str, int]] — ExecutionHandle[dict[str, int]]: Lazy qBraid sampling handle.
Raises:
ValueError— If runtime bindings are incomplete or run options contain a reserved key.Exception— Any qBraid submission failure.
SampleRequest [source]¶
class SampleRequest(Generic[CircuitT])Describe one sampling execution.
Parameters:
| Name | Type | Description |
|---|---|---|
invocation | CircuitInvocation[CircuitT] | Circuit and runtime inputs. |
shots | int | Number of requested samples. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, invocation: CircuitInvocation[CircuitT], shots: int) -> NoneAttributes¶
invocation: CircuitInvocation[CircuitT]shots: int
ShotBased [source]¶
class ShotBasedRequest a shot-based expectation value.
Parameters:
| Name | Type | Description |
|---|---|---|
shots | int | Positive number of measurement shots. |
Raises:
ValueError— Ifshotsis not positive.
Constructor¶
def __init__(self, shots: int) -> NoneAttributes¶
shots: int
TargetPrecision [source]¶
class TargetPrecisionRequest an expectation value at a provider target precision.
Parameters:
| Name | Type | Description |
|---|---|---|
precision | float | Positive absolute target precision. |
Raises:
ValueError— Ifprecisionis not positive.
Constructor¶
def __init__(self, precision: float) -> NoneAttributes¶
precision: float