Backends API Reference¶
Unverified examples
This page predates the current release and parts of it describe planned or older API. Only 4 of 13 code snippets on this page run as-is today. For verified, runnable code see the Quick Start, the Showcase and the Backends guide.
SuperQuantX provides a unified interface to multiple quantum computing backends, enabling seamless switching between simulators and real quantum hardware from different providers.
Base Classes¶
Base Backend¶
superquantx.backends.BaseBackend ¶
Bases: ABC
Abstract base class for quantum computing backends.
This class defines the interface that all quantum backends must implement to provide quantum circuit execution, measurement, and algorithm-specific operations for SuperQuantX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | None
|
Device or simulator to use |
None
|
shots
|
int
|
Default number of measurement shots |
1024
|
**kwargs
|
Backend-specific configuration |
{}
|
Source code in src/superquantx/backends/base_backend.py
Functions¶
create_circuit
abstractmethod
¶
add_gate
abstractmethod
¶
add_measurement
abstractmethod
¶
execute_circuit
abstractmethod
¶
get_statevector
abstractmethod
¶
counts_big_endian ¶
Return counts re-keyed so that character i is the value of qubit i.
Source code in src/superquantx/backends/base_backend.py
statevector_big_endian ¶
Statevector of circuit with qubit 0 as the most significant bit.
Source code in src/superquantx/backends/base_backend.py
create_feature_map ¶
create_feature_map(n_features: int, feature_map: str = 'ZZFeatureMap', reps: int = 2) -> FeatureMapSpec
Return a feature-map specification used by :meth:compute_kernel_matrix.
Supported maps: ZZFeatureMap (Havlicek et al. 2019, linear
entanglement), ZFeatureMap (the same without entanglement),
PauliFeatureMap (RX/RY/RZ plus CNOT chain) and
AngleEncoding (one RY per feature).
Source code in src/superquantx/backends/base_backend.py
build_feature_map_circuit ¶
Build the backend-native circuit that encodes x with spec.
Source code in src/superquantx/backends/base_backend.py
compute_kernel_matrix ¶
compute_kernel_matrix(X1: ndarray, X2: ndarray, feature_map: Any = None, shots: int | None = None) -> np.ndarray
Fidelity quantum kernel K[i, j] = |
Each data point is encoded with the feature map and simulated on this
backend; the kernel is computed exactly from the resulting statevectors
(shots is accepted for API compatibility and ignored). This is a
real quantum-circuit kernel, but it is classically simulated, so it says
nothing about quantum advantage.
Source code in src/superquantx/backends/base_backend.py
ansatz_param_count ¶
Number of parameters used by :meth:create_ansatz.
Source code in src/superquantx/backends/base_backend.py
create_ansatz ¶
create_ansatz(ansatz_type: str, n_qubits: int, params: ndarray, include_custom_gates: bool = False, reps: int | None = None) -> Any
Build a hardware-efficient ansatz with this backend's own gates.
RealAmplitudes/TwoLocal: reps layers of RY on every qubit
followed by a linear CNOT chain, plus a final RY layer.
EfficientSU2: the same structure with RY and RZ rotations.
Source code in src/superquantx/backends/base_backend.py
compute_expectation ¶
Exact expectation value
hamiltonian may be a dense matrix (qubit 0 most significant), a
superquantx.gates.Hamiltonian, a dict like {"ZI": -0.4}, a list
of (coeff, "ZI") pairs, or a PennyLane / Qiskit operator.
shots is accepted for API compatibility and ignored.
Source code in src/superquantx/backends/base_backend.py
create_qaoa_circuit ¶
create_qaoa_circuit(n_qubits: int, gammas: ndarray, betas: ndarray, problem_hamiltonian: Any, mixer_hamiltonian: Any, initial_state: Any, problem_instance: Any) -> Any
QAOA circuit for weighted MaxCut given an adjacency matrix.
Cost layer: exp(-i gamma w_ij Z_i Z_j / 2) per edge (CNOT, RZ, CNOT); mixer layer: RX(2 beta) on every qubit; initial state |+>^n.
Source code in src/superquantx/backends/base_backend.py
execute_qaoa ¶
execute_qaoa(circuit: Any, problem_hamiltonian: Any, problem_instance: Any, shots: int | None = None) -> float
Expected MaxCut value of the QAOA state (exact, from the statevector).
Source code in src/superquantx/backends/base_backend.py
sample_circuit ¶
Sample bitstrings; row k column i is the measured value of qubit i.
Source code in src/superquantx/backends/base_backend.py
encode_data_point ¶
Encode classical data into quantum state.
Source code in src/superquantx/backends/base_backend.py
compute_quantum_distance ¶
compute_quantum_distance(x1: ndarray, x2: ndarray, metric: str, encoding: str, n_qubits: int, shots: int) -> float
Distance between two data points.
Only metric='fidelity' uses quantum states: it angle-encodes both
points and returns sqrt(1 - |'euclidean' and 'manhattan' are plain classical distances.
Source code in src/superquantx/backends/base_backend.py
execute_qnn ¶
execute_qnn(input_data: ndarray, weights: ndarray, quantum_layers: list[dict], classical_layers: list[dict], encoding: str, measurement: str, shots: int) -> np.ndarray
Execute quantum neural network.
Source code in src/superquantx/backends/base_backend.py
get_version_info ¶
Get backend version information.
Source code in src/superquantx/backends/base_backend.py
get_device_info ¶
Get information about the quantum device.
Source code in src/superquantx/backends/base_backend.py
Simulator Backends¶
Python Simulator Backend¶
superquantx.backends.SimulatorBackend ¶
Bases: BaseBackend
Pure Python quantum simulator backend.
This backend provides a simple quantum simulator implementation that doesn't require external libraries. Useful for testing, development, and as a fallback when other backends are unavailable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
Device name (always 'simulator') |
'simulator'
|
max_qubits
|
int
|
Maximum number of qubits to simulate |
10
|
shots
|
int
|
Default number of measurement shots |
1024
|
**kwargs
|
Additional parameters |
{}
|
Source code in src/superquantx/backends/simulator_backend.py
Functions¶
create_circuit ¶
Create a quantum circuit with n qubits.
Source code in src/superquantx/backends/simulator_backend.py
add_gate ¶
add_gate(circuit: QuantumState, gate: str, qubits: int | list[int], params: list[float] | None = None) -> QuantumState
Apply a quantum gate to the circuit state.
Raises:
| Type | Description |
|---|---|
ValueError
|
for unknown gates or invalid qubits. |
Source code in src/superquantx/backends/simulator_backend.py
add_measurement ¶
Add measurement operations (no-op in this implementation).
Source code in src/superquantx/backends/simulator_backend.py
execute_circuit ¶
Sample all qubits. Bitstrings are little-endian (qubit 0 rightmost), like Qiskit.
Source code in src/superquantx/backends/simulator_backend.py
get_statevector ¶
get_version_info ¶
Get simulator version information.
Source code in src/superquantx/backends/simulator_backend.py
get_backend_info ¶
Get backend information.
Source code in src/superquantx/backends/simulator_backend.py
run ¶
Run a quantum circuit and return results.
Hardware Backends¶
IBM Qiskit Backend¶
superquantx.backends.QiskitBackend ¶
QiskitBackend(device: str = 'aer_simulator', provider: dict | None = None, shots: int = 1024, **kwargs)
Bases: BaseBackend
Qiskit backend (Aer simulator locally, IBM Quantum via qiskit-ibm-runtime).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
|
'aer_simulator'
|
provider
|
dict | None
|
Optional dict of |
None
|
shots
|
int
|
Number of measurement shots. |
1024
|
Source code in src/superquantx/backends/qiskit_backend.py
Functions¶
execute_circuit ¶
Run the circuit and return counts (little-endian: qubit 0 is the rightmost bit).
If the circuit has no measurements, all qubits are measured on a copy.
Source code in src/superquantx/backends/qiskit_backend.py
get_statevector ¶
Exact statevector (little-endian), computed with qiskit.quantum_info.
Source code in src/superquantx/backends/qiskit_backend.py
PennyLane Backend¶
superquantx.backends.PennyLaneBackend ¶
Bases: BaseBackend
PennyLane backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
PennyLane device name ( |
'default.qubit'
|
wires
|
int
|
Maximum number of wires a circuit may use. |
16
|
shots
|
int
|
Default number of shots for sampled execution. |
1024
|
**kwargs
|
Extra keyword arguments passed to |
{}
|
Source code in src/superquantx/backends/pennylane_backend.py
Functions¶
execute_circuit ¶
Sample the circuit and return counts (big-endian: wire 0 is the leftmost bit).
A plain quantum function (legacy API) is also accepted; it is run as a
QNode and its return value is passed back under 'result'.
Source code in src/superquantx/backends/pennylane_backend.py
get_statevector ¶
Exact statevector (big-endian, wire 0 most significant).
Source code in src/superquantx/backends/pennylane_backend.py
Google Cirq Backend¶
superquantx.backends.CirqBackend ¶
CirqBackend(device: str = 'simulator', processor_id: str | None = None, shots: int = 1024, **kwargs)
Bases: BaseBackend
Cirq backend.
Circuits are (cirq.Circuit, [LineQubit, ...]) tuples. Counts and
statevectors are big-endian (qubit 0 is the leftmost bit).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
|
'simulator'
|
processor_id
|
str | None
|
Google Quantum AI processor id (hardware, untested). |
None
|
shots
|
int
|
Number of measurement shots. |
1024
|
Source code in src/superquantx/backends/cirq_backend.py
Functions¶
execute_circuit ¶
Sample the circuit; unmeasured circuits get all qubits measured on a copy.
Source code in src/superquantx/backends/cirq_backend.py
Amazon Braket Backend¶
superquantx.backends.BraketBackend ¶
BraketBackend(device: str = 'local:braket/braket_sv', shots: int = 1024, aws_session=None, s3_folder: tuple[str, str] | None = None, **kwargs)
Bases: BaseBackend
AWS Braket backend for quantum computing operations.
This backend provides access to AWS Braket's quantum devices including local simulators, managed simulators, and QPU hardware from IonQ, Rigetti, and other providers available on AWS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
Device name or ARN (e.g., 'local:braket/braket_sv', 'arn:aws:braket::device/qpu/ionq/ionQdevice') |
'local:braket/braket_sv'
|
shots
|
int
|
Number of measurement shots |
1024
|
aws_session
|
Optional AWS session for authentication |
None
|
|
s3_folder
|
tuple[str, str] | None
|
S3 bucket folder for results (required for hardware) |
None
|
**kwargs
|
Additional device configuration |
{}
|
Example
Local simulator¶
backend = BraketBackend(device='local:braket/braket_sv')
AWS hardware (requires authentication)¶
backend = BraketBackend( ... device='arn:aws:braket::device/qpu/ionq/ionQdevice', ... s3_folder=('my-bucket', 'quantum-results') ... )
Source code in src/superquantx/backends/braket_backend.py
Functions¶
create_circuit ¶
Create a Braket circuit on n_qubits qubits.
Braket circuits only know about qubits that carry an instruction, so an identity is placed on every qubit to fix the register size.
Source code in src/superquantx/backends/braket_backend.py
add_gate ¶
add_gate(circuit: Circuit, gate: str, qubits: int | list[int], params: list[float] | None = None) -> BraketCircuit
Add a quantum gate to the circuit.
Source code in src/superquantx/backends/braket_backend.py
add_measurement ¶
Record which qubits to measure (all qubits when qubits is None).
Source code in src/superquantx/backends/braket_backend.py
execute_circuit ¶
Sample the circuit. Counts are big-endian (qubit 0 is the leftmost bit).
Source code in src/superquantx/backends/braket_backend.py
create_parameterized_circuit ¶
Create a parameterized quantum circuit for variational algorithms.
Source code in src/superquantx/backends/braket_backend.py
get_backend_info ¶
Get information about the Braket backend.
Source code in src/superquantx/backends/braket_backend.py
get_version_info ¶
Get version information for Braket dependencies.
Source code in src/superquantx/backends/braket_backend.py
is_available ¶
get_circuit_info ¶
Get information about circuit execution capabilities.
Source code in src/superquantx/backends/braket_backend.py
get_statevector ¶
Exact statevector (big-endian) from Braket's local state-vector simulator.
Source code in src/superquantx/backends/braket_backend.py
TKET/Quantinuum Backend¶
superquantx.backends.TKETBackend ¶
TKETBackend(device: str = 'aer_simulator', shots: int = 1024, machine: str | None = None, api_key: str | None = None, **kwargs)
Bases: BaseBackend
TKET (Quantum Toolkit) backend for quantum computing operations.
This backend provides access to TKET's quantum circuit compilation, optimization, and execution capabilities, including Quantinuum hardware.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
Device name (e.g., 'aer_simulator', 'H1-1E', 'H1-2E', 'simulator') |
'aer_simulator'
|
shots
|
int
|
Number of measurement shots |
1024
|
machine
|
str | None
|
Specific Quantinuum machine for hardware execution |
None
|
api_key
|
str | None
|
Quantinuum API key (required for hardware) |
None
|
**kwargs
|
Additional backend configuration |
{}
|
Example
Local simulator¶
backend = TKETBackend(device='aer_simulator')
Quantinuum hardware (requires API key)¶
backend = TKETBackend( ... device='H1-1E', ... api_key='your-quantinuum-api-key' ... )
Source code in src/superquantx/backends/tket_backend.py
Functions¶
create_circuit ¶
Create a TKET quantum circuit.
Source code in src/superquantx/backends/tket_backend.py
add_gate ¶
add_gate(circuit: Circuit, gate: str, qubits: int | list[int], params: list[float] | None = None) -> Circuit
Add a gate. Angles are given in radians (converted to TKET half-turns).
Source code in src/superquantx/backends/tket_backend.py
add_measurement ¶
Measure qubits (all qubits by default) into classical bits 0..k-1.
Source code in src/superquantx/backends/tket_backend.py
execute_circuit ¶
Compile and run the circuit. Counts are big-endian (bit 0 is the leftmost character).
Unmeasured circuits get all qubits measured on a copy.
Source code in src/superquantx/backends/tket_backend.py
optimize_circuit ¶
Optimize quantum circuit using TKET compiler passes.
Source code in src/superquantx/backends/tket_backend.py
get_backend_info ¶
Get information about the TKET backend.
Source code in src/superquantx/backends/tket_backend.py
get_version_info ¶
Get version information for TKET dependencies.
Source code in src/superquantx/backends/tket_backend.py
is_available ¶
get_circuit_info ¶
Get information about circuit execution capabilities.
Source code in src/superquantx/backends/tket_backend.py
get_statevector ¶
Exact statevector (big-endian) computed by pytket, ignoring measurements.
Source code in src/superquantx/backends/tket_backend.py
D-Wave Ocean Backend¶
superquantx.backends.OceanBackend ¶
OceanBackend(device: str = 'simulator', solver: str | None = None, token: str | None = None, endpoint: str | None = None, shots: int = 1000, **kwargs)
Bases: BaseBackend
D-Wave Ocean backend for quantum annealing operations.
This backend provides access to D-Wave's quantum annealing systems for solving optimization problems formulated as QUBO or Ising models.
Note: Unlike gate-model quantum computers, D-Wave systems solve optimization problems rather than running quantum circuits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
Sampler type ('DWave', 'hybrid', 'simulator', 'advantage') |
'simulator'
|
solver
|
str | None
|
Specific solver name (optional) |
None
|
token
|
str | None
|
D-Wave API token (required for hardware) |
None
|
endpoint
|
str | None
|
D-Wave API endpoint |
None
|
shots
|
int
|
Number of samples (reads) |
1000
|
**kwargs
|
Additional sampler configuration |
{}
|
Example
Simulated annealing (no hardware required)¶
backend = OceanBackend(device='simulator')
D-Wave hardware (requires API token)¶
backend = OceanBackend( ... device='advantage', ... token='your-dwave-token' ... )
Source code in src/superquantx/backends/ocean_backend.py
Functions¶
solve_qubo ¶
Solve a Quadratic Unconstrained Binary Optimization (QUBO) problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Q
|
dict[tuple[int, int], float]
|
QUBO dictionary where keys are (i, j) variable pairs and values are coefficients |
required |
**kwargs
|
Additional solving parameters |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Solution results with energies and samples |
Source code in src/superquantx/backends/ocean_backend.py
solve_ising ¶
Solve an Ising model problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
dict[int, float]
|
Linear coefficients (bias terms) for each variable |
required |
J
|
dict[tuple[int, int], float]
|
Quadratic coefficients (coupling terms) between variables |
required |
**kwargs
|
Additional solving parameters |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Solution results with energies and samples |
Source code in src/superquantx/backends/ocean_backend.py
solve_optimization_problem ¶
Generic optimization problem solver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
dict | Any
|
Problem specification (QUBO dict, Ising model, or BQM) |
required |
problem_type
|
str
|
Type of problem ('qubo', 'ising', 'bqm', 'auto') |
'auto'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Solution results |
Source code in src/superquantx/backends/ocean_backend.py
create_circuit ¶
add_gate ¶
add_gate(circuit: dict, gate: str, qubits: int | list[int], params: list[float] | None = None) -> dict
Not supported: annealers do not run gate-model circuits.
add_measurement ¶
Not supported: annealers do not run gate-model circuits.
execute_circuit ¶
Not supported: annealers do not run gate-model circuits.
get_backend_info ¶
Get information about the D-Wave Ocean backend.
Source code in src/superquantx/backends/ocean_backend.py
get_version_info ¶
Get version information for Ocean dependencies.
Source code in src/superquantx/backends/ocean_backend.py
is_available ¶
get_circuit_info ¶
Get circuit capabilities (limited for annealing backend).
Source code in src/superquantx/backends/ocean_backend.py
get_statevector ¶
solve_max_cut ¶
Solve Maximum Cut problem on a graph.
Source code in src/superquantx/backends/ocean_backend.py
solve_tsp ¶
Not implemented: a correct TSP QUBO needs one-hot constraints (planned).
Source code in src/superquantx/backends/ocean_backend.py
Utility Functions¶
Backend Management¶
superquantx.backends.get_backend ¶
Get a quantum backend instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | BaseBackend
|
Backend name or instance |
required |
**kwargs
|
Backend configuration parameters |
{}
|
Returns:
| Type | Description |
|---|---|
BaseBackend
|
Backend instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If backend is not supported |
ImportError
|
If backend dependencies are missing |
Example
backend = get_backend('pennylane', device='default.qubit') backend = get_backend('qiskit', provider='IBMQ')
Source code in src/superquantx/backends/__init__.py
superquantx.backends.list_available_backends ¶
List all available backends and their status.
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
Dictionary with backend information |
Source code in src/superquantx/backends/__init__.py
superquantx.backends.check_backend_compatibility ¶
Check compatibility and requirements for a specific backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend_name
|
str
|
Name of the backend to check |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Compatibility information |
Source code in src/superquantx/backends/__init__.py
Backend Selection Guide¶
By Use Case¶
Development & Prototyping
# Fast local simulation
backend = sqx.get_backend('simulator', max_qubits=10)
# Cross-platform testing
backend = sqx.get_backend('pennylane', device='default.qubit')
Production & Research
# IBM Quantum hardware
backend = sqx.get_backend('qiskit', device='ibmq_manila', token='your-token')
# Google Quantum AI
backend = sqx.get_backend('cirq', processor_id='rainbow', project_id='your-project')
# AWS Braket cloud
backend = sqx.get_backend('braket', device_arn='arn:aws:braket:us-east-1::device/qpu/ionq/ionQdevice')
Specialized Applications
# Quantum chemistry (TKET optimization)
backend = sqx.get_backend('tket', device='H1-1E', api_key='quantinuum-key')
# Optimization problems (D-Wave annealing)
backend = sqx.get_backend('ocean', device='advantage', token='dwave-token')
By Performance Requirements¶
High Accuracy (Large Shot Counts)
backends_high_accuracy = {
'simulator': sqx.get_backend('simulator', shots=100000),
'ibm_hardware': sqx.get_backend('qiskit', device='ibmq_montreal', shots=8192),
'aws_sv1': sqx.get_backend('braket', device='sv1', shots=100000)
}
Fast Iteration (Low Latency)
backends_fast = {
'local_sim': sqx.get_backend('simulator', shots=1000),
'pennylane': sqx.get_backend('pennylane', device='lightning.qubit'),
'braket_local': sqx.get_backend('braket', device='braket_sv')
}
Cost Optimization
# Free tier resources
free_backends = {
'simulator': sqx.get_backend('simulator'),
'ibm_free': sqx.get_backend('qiskit', device='ibmq_qasm_simulator'),
'aws_sim': sqx.get_backend('braket', device='braket_sv') # First 1 hour free
}
Integration Examples¶
Multi-Backend Algorithm Testing¶
import superquantx as sqx
def test_algorithm_across_backends(algorithm_func, backends, *args, **kwargs):
"""Test quantum algorithm across multiple backends."""
results = {}
for backend_name, backend in backends.items():
try:
print(f"Testing on {backend_name}...")
# Run algorithm
result = algorithm_func(backend, *args, **kwargs)
results[backend_name] = result
print(f" ✓ Success: {result}")
except Exception as e:
print(f" ✗ Failed: {e}")
results[backend_name] = None
return results
# Define test backends
test_backends = {
'simulator': sqx.get_backend('simulator'),
'pennylane': sqx.get_backend('pennylane', device='default.qubit'),
}
# Example quantum algorithm
def simple_bell_state(backend):
circuit = backend.create_circuit(2)
circuit = backend.add_gate(circuit, 'h', 0)
circuit = backend.add_gate(circuit, 'cx', [0, 1])
return backend.execute_circuit(circuit)
# Test across backends
results = test_algorithm_across_backends(simple_bell_state, test_backends)
Backend Fallback Strategy¶
def get_backend_with_fallback(preferences, **kwargs):
"""Get backend with fallback strategy."""
for backend_name in preferences:
try:
backend = sqx.get_backend(backend_name, **kwargs)
if backend.is_available():
print(f"Using backend: {backend_name}")
return backend
except Exception as e:
print(f"Backend {backend_name} failed: {e}")
continue
raise RuntimeError("No backends available")
# Usage
backend = get_backend_with_fallback([
'qiskit', # Try IBM first
'pennylane', # Fallback to PennyLane
'simulator' # Final fallback
], shots=1024)
Performance Benchmarking¶
import time
import numpy as np
def benchmark_backends(backends, circuit_sizes=[2, 4, 6, 8]):
"""Benchmark quantum backends across different circuit sizes."""
results = {}
for backend_name, backend in backends.items():
print(f"\nBenchmarking {backend_name}:")
results[backend_name] = {}
for n_qubits in circuit_sizes:
if n_qubits > backend.get_backend_info().get('capabilities', {}).get('max_qubits', 32):
continue
# Create test circuit
circuit = backend.create_circuit(n_qubits)
# Add random gates
for _ in range(n_qubits * 2):
qubit = np.random.randint(0, n_qubits)
circuit = backend.add_gate(circuit, 'h', qubit)
for _ in range(n_qubits - 1):
q1, q2 = np.random.choice(n_qubits, 2, replace=False)
circuit = backend.add_gate(circuit, 'cx', [q1, q2])
# Benchmark execution
start_time = time.time()
try:
result = backend.execute_circuit(circuit, shots=1000)
execution_time = time.time() - start_time
results[backend_name][n_qubits] = {
'time': execution_time,
'success': result.get('success', True),
'total_counts': sum(result.get('counts', {}).values())
}
print(f" {n_qubits} qubits: {execution_time:.3f}s")
except Exception as e:
print(f" {n_qubits} qubits: Failed - {e}")
results[backend_name][n_qubits] = {'error': str(e)}
return results
# Run benchmark
benchmark_backends({
'simulator': sqx.get_backend('simulator'),
'pennylane': sqx.get_backend('pennylane'),
})
Backend Configuration¶
Environment Setup¶
import os
import superquantx as sqx
# Configure backends via environment variables
os.environ['QISKIT_IBMQ_TOKEN'] = 'your-ibm-token'
os.environ['BRAKET_AWS_REGION'] = 'us-east-1'
os.environ['DWAVE_API_TOKEN'] = 'your-dwave-token'
# Test configurations
def validate_backend_config():
"""Validate backend configurations."""
configs = {
'qiskit': {
'required_env': ['QISKIT_IBMQ_TOKEN'],
'test_device': 'ibmq_qasm_simulator'
},
'braket': {
'required_env': ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'],
'test_device': 'braket_sv'
},
'ocean': {
'required_env': ['DWAVE_API_TOKEN'],
'test_device': 'simulator'
}
}
for backend_name, config in configs.items():
print(f"Validating {backend_name}:")
# Check environment variables
missing_env = [env for env in config['required_env']
if not os.getenv(env)]
if missing_env:
print(f" ✗ Missing environment variables: {missing_env}")
continue
# Test backend creation
try:
backend = sqx.get_backend(backend_name, device=config['test_device'])
if backend.is_available():
print(f" ✓ Backend available")
else:
print(f" ✗ Backend not available")
except Exception as e:
print(f" ✗ Configuration error: {e}")
validate_backend_config()
Custom Backend Configuration¶
# Advanced backend configuration
backend_configs = {
'qiskit_optimized': {
'backend_type': 'qiskit',
'device': 'ibmq_montreal',
'shots': 4096,
'optimization_level': 3,
'error_mitigation': True,
'noise_model': 'device_noise'
},
'pennylane_gpu': {
'backend_type': 'pennylane',
'device': 'lightning.gpu',
'shots': 100000,
'batch_size': 1024
},
'braket_cost_optimized': {
'backend_type': 'braket',
'device': 'sv1', # Simulator for cost optimization
'shots': 1000,
'max_parallel_tasks': 5
}
}
def create_configured_backend(config_name):
"""Create backend from configuration."""
config = backend_configs[config_name]
backend_type = config.pop('backend_type')
return sqx.get_backend(backend_type, **config)
Error Handling¶
Backend-Specific Error Handling¶
from superquantx.exceptions import (
QuantumBackendError,
DeviceOfflineError,
AuthenticationError,
ResourceExhaustedError
)
def robust_backend_execution(backend, circuit, max_retries=3):
"""Execute circuit with comprehensive error handling."""
for attempt in range(max_retries):
try:
result = backend.execute_circuit(circuit)
return result
except AuthenticationError:
print("Authentication failed - check API tokens")
raise # Don't retry auth errors
except DeviceOfflineError as e:
print(f"Device offline: {e}")
if attempt < max_retries - 1:
print("Waiting 30s before retry...")
time.sleep(30)
except ResourceExhaustedError as e:
print(f"Resources exhausted: {e}")
# Reduce shots and retry
circuit.shots = max(circuit.shots // 2, 100)
except QuantumBackendError as e:
print(f"Backend error on attempt {attempt + 1}: {e}")
if attempt == max_retries - 1:
raise
raise RuntimeError("All execution attempts failed")
# Usage with error handling
try:
backend = sqx.get_backend('qiskit', device='ibmq_manila')
result = robust_backend_execution(backend, circuit)
except Exception as e:
print(f"Execution failed: {e}")
# Fallback to simulator
fallback_backend = sqx.get_backend('simulator')
result = fallback_backend.execute_circuit(circuit)
Best Practices¶
Backend Selection Strategy¶
- Development Phase: Use
simulatororpennylanefor rapid iteration - Testing Phase: Use cloud simulators (
braket_sv,qiskit_aer) for validation - Production Phase: Use real hardware with appropriate error mitigation
- Cost Optimization: Use free simulators when possible, batch hardware jobs
Performance Optimization¶
# Optimize circuit for specific backend
def optimize_for_backend(circuit, backend):
"""Optimize circuit for specific backend capabilities."""
backend_info = backend.get_backend_info()
if 'qiskit' in backend_info.get('backend_name', ''):
# Use Qiskit-specific optimizations
return backend.transpile_circuit(circuit, optimization_level=2)
elif 'tket' in backend_info.get('backend_name', ''):
# Use TKET optimizations
return backend.optimize_circuit(circuit, optimization_level=3)
elif 'ocean' in backend_info.get('backend_name', ''):
# Ocean backends use different problem formulations
return backend.convert_to_qubo(circuit)
else:
# Generic optimization
return circuit
# Batch processing for hardware backends
def batch_execute_circuits(backend, circuits, max_batch_size=10):
"""Execute circuits in batches for efficiency."""
results = []
for i in range(0, len(circuits), max_batch_size):
batch = circuits[i:i + max_batch_size]
if hasattr(backend, 'execute_batch'):
# Use native batch execution if available
batch_results = backend.execute_batch(batch)
else:
# Sequential execution fallback
batch_results = [backend.execute_circuit(c) for c in batch]
results.extend(batch_results)
return results
For detailed backend integration guides, see: - Qiskit Integration - PennyLane Integration - Cirq Integration - Braket Integration - TKET Integration - Ocean Integration - Simulator Backend