Core API Reference¶
The core API provides fundamental functionality for SuperQuantX, including backend management, configuration, and system information.
Package-Level Functions¶
Version Information¶
superquantx.get_version ¶
superquantx.get_backend_info ¶
Get information about available backends.
Source code in src/superquantx/__init__.py
superquantx.print_system_info ¶
Print system and backend information.
Source code in src/superquantx/__init__.py
Backend Management¶
superquantx.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.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.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
Configuration¶
superquantx.config ¶
Global configuration for SuperQuantX.
This module provides configuration management for the SuperQuantX package, including backend settings, default parameters, and runtime options.
Classes¶
Config ¶
Global configuration class for SuperQuantX.
Initialize configuration with defaults.
Source code in src/superquantx/config.py
Functions¶
get ¶
Get configuration value using dot notation.
Source code in src/superquantx/config.py
set ¶
Set configuration value using dot notation.
Source code in src/superquantx/config.py
update ¶
save ¶
Save current configuration to file.
Source code in src/superquantx/config.py
reset ¶
to_dict ¶
print_config ¶
ConfigContext ¶
ValidationResult ¶
ConfigValidationError ¶
Bases: Exception
Exception raised when configuration validation fails.
ExperimentContext ¶
ProfileContext ¶
Functions¶
configure ¶
configure(backend: str | None = None, shots: int | None = None, debug: bool | None = None, **kwargs) -> None
Configure SuperQuantX settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str | None
|
Default backend to use |
None
|
shots
|
int | None
|
Default number of shots for quantum circuits |
None
|
debug
|
bool | None
|
Enable debug mode |
None
|
**kwargs
|
Additional configuration parameters |
{}
|
Source code in src/superquantx/config.py
setup_logging ¶
Setup logging configuration.
Source code in src/superquantx/config.py
get_platform_config ¶
Get configuration for a specific platform.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
platform
|
str
|
Platform name (e.g., 'ibm', 'braket', 'azure') |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Platform configuration dictionary |
Source code in src/superquantx/config.py
create_default_config ¶
Generate default configuration file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
Path where to save the configuration file |
'./superquantx.json'
|
format
|
str
|
Format of the file ('json' or 'yaml') |
'json'
|
Source code in src/superquantx/config.py
configure_interactive ¶
Interactive configuration wizard.
Returns:
Type | Description |
---|---|
Configuration object that can be saved |
Source code in src/superquantx/config.py
load_config ¶
Load configuration from file(s).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config_path
|
Path to config file or list of paths. If None, uses default locations. |
None
|
Source code in src/superquantx/config.py
configure_logging ¶
configure_logging(level='INFO', file=None, console=True, format=None, max_file_size='10MB', backup_count=3) -> None
Configure logging settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
level
|
Logging level |
'INFO'
|
|
file
|
Log file path |
None
|
|
console
|
Whether to log to console |
True
|
|
format
|
Log format string |
None
|
|
max_file_size
|
Maximum log file size before rotation |
'10MB'
|
|
backup_count
|
Number of backup files to keep |
3
|
Source code in src/superquantx/config.py
configure_simulation ¶
Configure simulation settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_qubits
|
Maximum number of qubits to simulate |
None
|
|
default_shots
|
Default number of shots |
None
|
|
memory_limit
|
Memory limit for simulations |
None
|
Source code in src/superquantx/config.py
config_context ¶
Create a configuration context manager.
Usage
with config_context(backend="qiskit", shots=10000): # Code here uses the specified configuration pass
get_default_backend ¶
get_config ¶
Get configuration value(s).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Configuration key (dot notation). If None, returns all config. |
None
|
Returns:
Type | Description |
---|---|
Any
|
Configuration value or full config dict |
Source code in src/superquantx/config.py
get_config_search_paths ¶
Get list of configuration search paths.
Source code in src/superquantx/config.py
get_active_config_path ¶
Get path of currently active configuration file.
Source code in src/superquantx/config.py
validate_config ¶
Validate current configuration.
Returns:
Type | Description |
---|---|
ValidationResult
|
ValidationResult with validation status and errors |
Source code in src/superquantx/config.py
validate_config_schema ¶
Validate configuration file against schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config_path
|
str
|
Path to configuration file |
required |
Raises:
Type | Description |
---|---|
ConfigValidationError
|
If validation fails |
Source code in src/superquantx/config.py
configure_performance ¶
configure_performance(parallel_backends=None, thread_count=None, memory_limit=None, gpu_enabled=None, optimization_level=None) -> None
Configure performance settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parallel_backends
|
Number of backends to run in parallel |
None
|
|
thread_count
|
Number of threads per backend |
None
|
|
memory_limit
|
Memory limit for simulations |
None
|
|
gpu_enabled
|
Enable GPU acceleration |
None
|
|
optimization_level
|
Optimization level (0-3) |
None
|
Source code in src/superquantx/config.py
configure_experiments ¶
configure_experiments(experiment_dir='./experiments', auto_save_results=True, save_circuits=True, save_metadata=True, version_control=True) -> None
Configure experiment tracking.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
experiment_dir
|
Directory to save experiments |
'./experiments'
|
|
auto_save_results
|
Automatically save experiment results |
True
|
|
save_circuits
|
Save quantum circuits |
True
|
|
save_metadata
|
Save experiment metadata |
True
|
|
version_control
|
Enable version control for experiments |
True
|
Source code in src/superquantx/config.py
experiment ¶
Create an experiment context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the experiment |
required |
Returns:
Type | Description |
---|---|
ExperimentContext for tracking the experiment |
create_profile ¶
Create a configuration profile.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Profile name |
required |
config_dict
|
dict
|
Configuration dictionary |
required |
activate_profile ¶
Activate a configuration profile.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Profile name |
required |
Source code in src/superquantx/config.py
profile ¶
Create a profile context manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Profile name |
required |
Returns:
Type | Description |
---|---|
ProfileContext for temporary profile activation |
superquantx.configure ¶
configure(backend: str | None = None, shots: int | None = None, debug: bool | None = None, **kwargs) -> None
Configure SuperQuantX settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str | None
|
Default backend to use |
None
|
shots
|
int | None
|
Default number of shots for quantum circuits |
None
|
debug
|
bool | None
|
Enable debug mode |
None
|
**kwargs
|
Additional configuration parameters |
{}
|
Source code in src/superquantx/config.py
Backend 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
¶
create_feature_map ¶
Create quantum feature map for data encoding.
Source code in src/superquantx/backends/base_backend.py
compute_kernel_matrix ¶
compute_kernel_matrix(X1: ndarray, X2: ndarray, feature_map: Any, shots: int | None = None) -> np.ndarray
Compute quantum kernel matrix between data points.
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) -> Any
Create parameterized ansatz circuit.
Source code in src/superquantx/backends/base_backend.py
compute_expectation ¶
Compute expectation value of Hamiltonian.
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
Create QAOA circuit with given parameters.
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
Execute QAOA circuit and return expectation value.
Source code in src/superquantx/backends/base_backend.py
sample_circuit ¶
Sample bit strings from quantum circuit.
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
Compute quantum distance between two data points.
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
Auto Backend¶
superquantx.AutoBackend ¶
Auto backend selection (wrapper around get_backend).
Quick Start Examples¶
Basic Usage¶
import superquantx as sqx
# Get version information
print(f"SuperQuantX version: {sqx.get_version()}")
# Check available backends
backends = sqx.list_available_backends()
print(f"Available backends: {backends}")
# Get system information
sqx.print_system_info()
Backend Selection¶
import superquantx as sqx
# Automatic backend selection
backend = sqx.get_backend('auto')
# Specific backend with configuration
qiskit_backend = sqx.get_backend('qiskit',
device='ibmq_qasm_simulator',
shots=1000)
# Check backend compatibility
is_compatible = sqx.check_backend_compatibility('qiskit')
print(f"Qiskit compatible: {is_compatible}")
Configuration Management¶
import superquantx as sqx
# View current configuration
print("Current config:", sqx.config)
# Update configuration
sqx.configure({
'default_backend': 'simulator',
'default_shots': 1024,
'optimization_level': 2,
'visualization': {
'style': 'dark',
'dpi': 300
}
})
Available Backends¶
SuperQuantX supports multiple quantum computing backends:
Hardware Backends¶
- IBM Quantum (
qiskit
): Access to IBM Quantum devices - Google Quantum AI (
cirq
): Integration with Google's quantum hardware - Amazon Braket (
braket
): AWS quantum computing service - Quantinuum (
tket
): H-Series trapped-ion quantum computers - D-Wave (
ocean
): Quantum annealing systems
Simulator Backends¶
- Python Simulator (
simulator
): Pure Python quantum simulation - Local Simulators: High-performance local quantum simulators
- Classical Emulation: Classical algorithms for quantum-inspired computations
Example Backend Usage¶
import superquantx as sqx
# Initialize different backends
backends = {}
# Simulator for development
backends['sim'] = sqx.get_backend('simulator', max_qubits=10)
# IBM Quantum for real hardware
backends['ibm'] = sqx.get_backend('qiskit',
device='ibmq_manila',
token='your-ibm-token')
# Amazon Braket for cloud quantum computing
backends['aws'] = sqx.get_backend('braket',
device_arn='arn:aws:braket:::device/quantum-simulator/amazon/sv1',
s3_bucket='my-braket-bucket')
# D-Wave for optimization problems
backends['dwave'] = sqx.get_backend('ocean',
device='advantage',
token='your-dwave-token')
# Use backends
for name, backend in backends.items():
if backend.is_available():
info = backend.get_backend_info()
print(f"{name}: {info['provider']} - {info['device']}")
Error Handling¶
SuperQuantX provides comprehensive error handling for backend operations:
import superquantx as sqx
from superquantx.exceptions import QuantumBackendError
try:
# Attempt to initialize backend
backend = sqx.get_backend('qiskit', device='fake_device')
except QuantumBackendError as e:
print(f"Backend error: {e}")
# Fallback to simulator
backend = sqx.get_backend('simulator')
except ImportError as e:
print(f"Missing dependency: {e}")
print("Install with: pip install superquantx[qiskit]")
# Check backend availability
if backend.is_available():
print("Backend ready for use")
else:
print("Backend not available, check configuration")
Advanced Configuration¶
Environment Variables¶
SuperQuantX respects environment variables for configuration:
# Default backend selection
export SUPERQUANTX_BACKEND=qiskit
# IBM Quantum credentials
export QISKIT_IBMQ_TOKEN=your-token-here
# AWS credentials for Braket
export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
# D-Wave credentials
export DWAVE_API_TOKEN=your-dwave-token
# Quantinuum credentials
export QUANTINUUM_API_KEY=your-quantinuum-key
Configuration Files¶
Create ~/.superquantx/config.yaml
for persistent configuration:
default_backend: simulator
default_shots: 1024
optimization_level: 2
backends:
qiskit:
token: your-ibm-token
hub: ibm-q
group: open
project: main
braket:
s3_bucket: my-quantum-bucket
s3_prefix: experiments
ocean:
token: your-dwave-token
solver: Advantage_system4.1
logging:
level: INFO
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
visualization:
backend: matplotlib
style: seaborn
figsize: [10, 6]
dpi: 300
Programmatic Configuration¶
import superquantx as sqx
# Advanced configuration
config = {
'default_backend': 'qiskit',
'default_shots': 2048,
'optimization': {
'level': 3,
'passes': ['cx_cancellation', 'commutative_cancellation'],
'coupling_map': 'heavy_hex',
},
'error_mitigation': {
'enabled': True,
'method': 'zero_noise_extrapolation',
'noise_factors': [1, 3, 5],
},
'caching': {
'enabled': True,
'backend': 'file',
'ttl': 3600, # 1 hour
}
}
sqx.configure(config)
# Access nested configuration
print(f"Optimization level: {sqx.config.optimization.level}")
print(f"Error mitigation enabled: {sqx.config.error_mitigation.enabled}")
Package Information¶
Metadata¶
import superquantx as sqx
# Package metadata
print(f"Title: {sqx.__title__}")
print(f"Description: {sqx.__description__}")
print(f"Author: {sqx.__author__}")
print(f"License: {sqx.__license__}")
print(f"URL: {sqx.__url__}")
Version Compatibility¶
SuperQuantX maintains compatibility with major quantum computing frameworks:
Framework | Supported Versions | Backend Class |
---|---|---|
Qiskit | 0.45+ | QiskitBackend |
PennyLane | 0.32+ | PennyLaneBackend |
Cirq | 1.0+ | CirqBackend |
Amazon Braket | 1.50+ | BraketBackend |
TKET/Pytket | 1.20+ | TKETBackend |
D-Wave Ocean | 6.0+ | OceanBackend |
Checking Dependencies¶
import superquantx as sqx
# Get detailed backend information
backend_info = sqx.get_backend_info()
for backend_name, version in backend_info.items():
if version:
print(f"✓ {backend_name}: {version}")
else:
print(f"✗ {backend_name}: Not installed")
# Check specific backend availability
backends_to_check = ['qiskit', 'pennylane', 'cirq', 'braket']
for backend in backends_to_check:
try:
test_backend = sqx.get_backend(backend)
print(f"✓ {backend}: Available")
except Exception as e:
print(f"✗ {backend}: {e}")
Module Structure¶
The core SuperQuantX package is organized as follows:
superquantx/
├── __init__.py # Main package initialization
├── algorithms/ # Quantum algorithms and ML models
├── backends/ # Quantum backend implementations
├── datasets/ # Quantum datasets and data utilities
├── utils/ # Utility functions and tools
├── cli/ # Command-line interface
├── config.py # Configuration management
├── exceptions.py # Custom exception classes
├── logging_config.py # Logging configuration
└── version.py # Version information
Integration Examples¶
With Jupyter Notebooks¶
# Cell 1: Setup
import superquantx as sqx
import numpy as np
import matplotlib.pyplot as plt
# Configure for notebook use
sqx.configure({
'visualization': {
'inline': True,
'style': 'notebook'
}
})
# Cell 2: System information
sqx.print_system_info()
# Cell 3: Backend comparison
backends = ['simulator', 'qiskit']
for backend_name in backends:
try:
backend = sqx.get_backend(backend_name)
print(f"{backend_name}: {backend.get_backend_info()}")
except Exception as e:
print(f"{backend_name}: Not available - {e}")
With External Libraries¶
import superquantx as sqx
import pandas as pd
import plotly.graph_objects as go
# Create backend comparison dashboard
def create_backend_dashboard():
backend_data = []
for backend_name in ['simulator', 'qiskit', 'cirq', 'braket']:
try:
backend = sqx.get_backend(backend_name)
info = backend.get_backend_info()
backend_data.append({
'Backend': backend_name,
'Provider': info.get('provider', 'Unknown'),
'Available': backend.is_available(),
'Max Qubits': info.get('capabilities', {}).get('max_qubits', 'N/A')
})
except:
backend_data.append({
'Backend': backend_name,
'Provider': 'N/A',
'Available': False,
'Max Qubits': 'N/A'
})
df = pd.DataFrame(backend_data)
# Create interactive table
fig = go.Figure(data=[go.Table(
header=dict(values=list(df.columns)),
cells=dict(values=[df[col] for col in df.columns])
)])
fig.update_layout(title="SuperQuantX Backend Status")
return fig
# Display dashboard
dashboard = create_backend_dashboard()
dashboard.show()
Best Practices¶
Backend Selection¶
-
Use Auto Backend for Development:
-
Specify Backend for Production:
-
Check Availability Before Use:
Configuration Management¶
-
Use Environment Variables for Credentials:
-
Separate Development and Production Configs:
-
Validate Configuration:
For more detailed information about specific modules, see the dedicated API reference sections: - Algorithms API - Backends API - Circuits API - Utilities API