Algorithms API Reference¶
Unverified examples
This page predates the current release and parts of it describe planned or older API. Only 1 of 6 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 comprehensive collection of quantum algorithms for machine learning, optimization, cryptography, and simulation. All algorithms support multiple quantum backends and provide unified interfaces for easy integration.
Base Classes¶
Base Algorithm¶
superquantx.algorithms.BaseQuantumAlgorithm ¶
BaseQuantumAlgorithm(backend: str | Any, shots: int = 1024, seed: int | None = None, optimization_level: int = 1, **kwargs)
Bases: ABC
Abstract base class for all quantum machine learning algorithms.
This class defines the common interface that all quantum algorithms must implement, providing consistency across different algorithm types and backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend to use for computation |
required |
shots
|
int
|
Number of measurement shots (default: 1024) |
1024
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
optimization_level
|
int
|
Circuit optimization level (0-3) |
1
|
**kwargs
|
Additional algorithm-specific parameters |
{}
|
Initialize the quantum algorithm.
Source code in src/superquantx/algorithms/base_algorithm.py
Functions¶
fit
abstractmethod
¶
Train the quantum algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data features |
required |
y
|
ndarray | None
|
Training data labels (for supervised learning) |
None
|
**kwargs
|
Additional training parameters |
{}
|
Returns:
| Type | Description |
|---|---|
BaseQuantumAlgorithm
|
Self for method chaining |
Source code in src/superquantx/algorithms/base_algorithm.py
predict
abstractmethod
¶
Make predictions using the trained algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional prediction parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predictions array |
Source code in src/superquantx/algorithms/base_algorithm.py
score ¶
Compute the algorithm's score on the given test data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Test data features |
required |
y
|
ndarray
|
True test data labels |
required |
**kwargs
|
Additional scoring parameters |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Algorithm score (higher is better) |
Source code in src/superquantx/algorithms/base_algorithm.py
get_params ¶
Get algorithm parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deep
|
bool
|
Whether to return deep copy of parameters |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Parameter dictionary |
Source code in src/superquantx/algorithms/base_algorithm.py
set_params ¶
Set algorithm parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**params
|
Parameters to set |
{}
|
Returns:
| Type | Description |
|---|---|
BaseQuantumAlgorithm
|
Self for method chaining |
Source code in src/superquantx/algorithms/base_algorithm.py
save_model ¶
Save the trained model to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path where to save the model |
required |
Source code in src/superquantx/algorithms/base_algorithm.py
load_model
classmethod
¶
Load a trained model from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the saved model |
required |
Returns:
| Type | Description |
|---|---|
BaseQuantumAlgorithm
|
Loaded algorithm instance |
Source code in src/superquantx/algorithms/base_algorithm.py
benchmark ¶
Benchmark algorithm performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Test data |
required |
y
|
ndarray | None
|
Test labels (optional) |
None
|
runs
|
int
|
Number of benchmark runs |
5
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Benchmark results dictionary |
Source code in src/superquantx/algorithms/base_algorithm.py
get_circuit_info ¶
Get information about the quantum circuit.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Circuit information dictionary |
Source code in src/superquantx/algorithms/base_algorithm.py
reset ¶
Reset algorithm to untrained state.
Source code in src/superquantx/algorithms/base_algorithm.py
Quantum Result¶
superquantx.algorithms.QuantumResult
dataclass
¶
QuantumResult(result: Any, metadata: dict[str, Any], execution_time: float, backend_info: dict[str, Any], error: str | None = None, intermediate_results: dict[str, Any] | None = None)
Container for quantum algorithm results.
This class provides a standardized way to return results from quantum algorithms, including the main result, metadata, and performance metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
result |
Any
|
The main algorithm result |
metadata |
dict[str, Any]
|
Additional information about the computation |
execution_time |
float
|
Time taken to execute the algorithm (seconds) |
backend_info |
dict[str, Any]
|
Information about the backend used |
error |
str | None
|
Error information if computation failed |
intermediate_results |
dict[str, Any] | None
|
Optional intermediate results for debugging |
Machine Learning Algorithms¶
Quantum Support Vector Machine¶
superquantx.algorithms.QuantumSVM ¶
QuantumSVM(backend: str | Any, feature_map: str | Any | None = 'ZZFeatureMap', feature_map_reps: int = 2, C: float = 1.0, gamma: float | None = None, quantum_kernel: Callable | None = None, shots: int = 1024, normalize_data: bool = True, auto_feature_map_mode: str = 'auto', **kwargs)
Bases: SupervisedQuantumAlgorithm
Quantum Support Vector Machine for classification.
This implementation uses quantum feature maps to transform data into a high-dimensional Hilbert space where linear separation is possible. The quantum kernel is computed using quantum circuits.
The algorithm works by: 1. Encoding classical data into quantum states using feature maps 2. Computing quantum kernels between data points 3. Training a classical SVM using the quantum kernel matrix
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
feature_map
|
str | Any | None
|
Feature map name ('ZZFeatureMap', 'PauliFeatureMap',
'AmplitudeMap', 'AngleEncoding', 'ZFeatureMap'), a custom object,
or |
'ZZFeatureMap'
|
feature_map_reps
|
int
|
Number of repetitions in the feature map |
2
|
C
|
float
|
Regularization parameter for SVM |
1.0
|
gamma
|
float | None
|
Quantum kernel bandwidth. Features are multiplied by |
None
|
quantum_kernel
|
Callable | None
|
Custom quantum kernel function |
None
|
shots
|
int
|
Number of measurement shots |
1024
|
auto_feature_map_mode
|
str
|
When feature_map is auto/None, selection mode
( |
'auto'
|
**kwargs
|
Additional parameters |
{}
|
Example
qsvm = QuantumSVM(backend='pennylane', feature_map='ZZFeatureMap') qsvm.fit(X_train, y_train) predictions = qsvm.predict(X_test) accuracy = qsvm.score(X_test, y_test)
Spike: automatic encoding selection (Qmes if installed, else heuristic)¶
qsvm_auto = QuantumSVM(backend='simulator', feature_map='auto') qsvm_auto.fit(X_train, y_train)
Source code in src/superquantx/algorithms/quantum_svm.py
Functions¶
fit ¶
Train the quantum SVM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data features |
required |
y
|
ndarray
|
Training data labels |
required |
**kwargs
|
Additional training parameters |
{}
|
Returns:
| Type | Description |
|---|---|
QuantumSVM
|
Self for method chaining |
Source code in src/superquantx/algorithms/quantum_svm.py
predict ¶
Make predictions using the trained quantum SVM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional prediction parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted labels |
Source code in src/superquantx/algorithms/quantum_svm.py
predict_proba ¶
Predict class probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted class probabilities |
Source code in src/superquantx/algorithms/quantum_svm.py
decision_function ¶
Compute decision function values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Decision function values |
Source code in src/superquantx/algorithms/quantum_svm.py
get_support_vectors ¶
Get support vectors from the trained model.
Source code in src/superquantx/algorithms/quantum_svm.py
get_quantum_kernel_matrix ¶
Get the quantum kernel matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray | None
|
Data to compute kernel matrix for (default: training data) |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Quantum kernel matrix |
Source code in src/superquantx/algorithms/quantum_svm.py
analyze_kernel ¶
Analyze properties of the quantum kernel.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with kernel analysis results |
Source code in src/superquantx/algorithms/quantum_svm.py
get_params ¶
Get algorithm parameters.
Source code in src/superquantx/algorithms/quantum_svm.py
set_params ¶
Set algorithm parameters.
Source code in src/superquantx/algorithms/quantum_svm.py
Quantum Neural Network¶
superquantx.algorithms.QuantumNN ¶
QuantumNN(backend: str | Any, n_layers: int = 3, architecture: str = 'hybrid', encoding: str = 'angle', entanglement: str = 'linear', measurement: str = 'expectation', optimizer: str = 'adam', learning_rate: float = 0.01, batch_size: int = 32, max_epochs: int = 100, shots: int = 1024, task_type: str = 'classification', **kwargs)
Bases: SupervisedQuantumAlgorithm
Quantum Neural Network for classification and regression.
This implementation uses parameterized quantum circuits as neural network layers, with classical optimization to train the quantum parameters.
The network can be configured with different architectures: - Pure quantum: Only quantum layers - Hybrid: Combination of quantum and classical layers - Variational: Variational quantum circuits with measurement
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
n_layers
|
int
|
Number of quantum layers |
3
|
architecture
|
str
|
Network architecture ('pure', 'hybrid', 'variational') |
'hybrid'
|
encoding
|
str
|
Data encoding method ('amplitude', 'angle', 'basis') |
'angle'
|
entanglement
|
str
|
Entanglement pattern ('linear', 'circular', 'full') |
'linear'
|
measurement
|
str
|
Measurement strategy ('expectation', 'sampling', 'statevector') |
'expectation'
|
optimizer
|
str
|
Classical optimizer for training |
'adam'
|
learning_rate
|
float
|
Learning rate for training |
0.01
|
batch_size
|
int
|
Training batch size |
32
|
shots
|
int
|
Number of measurement shots |
1024
|
**kwargs
|
Additional parameters |
{}
|
Example
qnn = QuantumNN(backend='pennylane', n_layers=3, architecture='hybrid') qnn.fit(X_train, y_train) predictions = qnn.predict(X_test) accuracy = qnn.score(X_test, y_test)
Source code in src/superquantx/algorithms/quantum_nn.py
Functions¶
fit ¶
Train the quantum neural network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data features |
required |
y
|
ndarray
|
Training data labels |
required |
**kwargs
|
Additional training parameters |
{}
|
Returns:
| Type | Description |
|---|---|
QuantumNN
|
Self for method chaining |
Source code in src/superquantx/algorithms/quantum_nn.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
predict ¶
Make predictions using the trained quantum neural network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional prediction parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted labels or values |
Source code in src/superquantx/algorithms/quantum_nn.py
predict_proba ¶
Predict class probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted class probabilities |
Source code in src/superquantx/algorithms/quantum_nn.py
get_circuit_depth ¶
Get the depth of the quantum circuit.
Source code in src/superquantx/algorithms/quantum_nn.py
get_training_history ¶
Get training history.
analyze_expressivity ¶
Analyze the expressivity of the quantum neural network.
Source code in src/superquantx/algorithms/quantum_nn.py
get_params ¶
Get quantum neural network parameters.
Source code in src/superquantx/algorithms/quantum_nn.py
set_params ¶
Set quantum neural network parameters.
Source code in src/superquantx/algorithms/quantum_nn.py
Hybrid Classifier¶
superquantx.algorithms.HybridClassifier ¶
HybridClassifier(backend: str | Any, hybrid_mode: str = 'ensemble', quantum_algorithms: list[str] | None = None, classical_algorithms: list[str] | None = None, quantum_weight: float = 0.5, feature_selection: bool = False, meta_learner: str = 'logistic_regression', shots: int = 1024, normalize_data: bool = True, **kwargs)
Bases: SupervisedQuantumAlgorithm
Hybrid Classical-Quantum Classifier.
This classifier combines classical and quantum machine learning algorithms to leverage the strengths of both approaches. It can operate in different modes: - Ensemble: Combines predictions from multiple quantum and classical models - Sequential: Uses quantum features as input to classical models - Voting: Majority voting among quantum and classical predictions - Stacking: Uses meta-learner to combine quantum and classical predictions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for quantum components |
required |
hybrid_mode
|
str
|
Mode of operation ('ensemble', 'sequential', 'voting', 'stacking') |
'ensemble'
|
quantum_algorithms
|
list[str] | None
|
List of quantum algorithms to include |
None
|
classical_algorithms
|
list[str] | None
|
List of classical algorithms to include |
None
|
quantum_weight
|
float
|
Weight for quantum predictions (0-1) |
0.5
|
feature_selection
|
bool
|
Whether to use quantum feature selection |
False
|
meta_learner
|
str
|
Meta-learning algorithm for stacking mode |
'logistic_regression'
|
shots
|
int
|
Number of measurement shots |
1024
|
**kwargs
|
Additional parameters |
{}
|
Example
hybrid = HybridClassifier( ... backend='pennylane', ... hybrid_mode='ensemble', ... quantum_algorithms=['quantum_svm', 'quantum_nn'], ... classical_algorithms=['random_forest', 'svm'] ... ) hybrid.fit(X_train, y_train) predictions = hybrid.predict(X_test)
Source code in src/superquantx/algorithms/hybrid_classifier.py
Functions¶
fit ¶
Train the hybrid classifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data features |
required |
y
|
ndarray
|
Training data labels |
required |
**kwargs
|
Additional training parameters |
{}
|
Returns:
| Type | Description |
|---|---|
HybridClassifier
|
Self for method chaining |
Source code in src/superquantx/algorithms/hybrid_classifier.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
predict ¶
Make predictions using the hybrid classifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional prediction parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted labels |
Source code in src/superquantx/algorithms/hybrid_classifier.py
predict_proba ¶
Predict class probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data for prediction |
required |
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted class probabilities |
Source code in src/superquantx/algorithms/hybrid_classifier.py
get_model_performance ¶
Get detailed performance metrics for all models.
Source code in src/superquantx/algorithms/hybrid_classifier.py
get_feature_importance ¶
cross_validate ¶
Perform cross-validation on the hybrid classifier.
Source code in src/superquantx/algorithms/hybrid_classifier.py
get_params ¶
Get hybrid classifier parameters.
Source code in src/superquantx/algorithms/hybrid_classifier.py
set_params ¶
Set hybrid classifier parameters.
Source code in src/superquantx/algorithms/hybrid_classifier.py
Quantum Principal Component Analysis¶
superquantx.algorithms.QuantumPCA ¶
QuantumPCA(backend: str | Any, n_components: int = 2, method: str = 'vqe', encoding: str = 'amplitude', max_iterations: int = 1000, tolerance: float = 1e-06, shots: int = 1024, classical_fallback: bool = True, normalize_data: bool = True, **kwargs)
Bases: UnsupervisedQuantumAlgorithm
Quantum Principal Component Analysis for dimensionality reduction.
This implementation uses quantum algorithms to perform PCA, potentially offering exponential speedup for certain types of data matrices.
The algorithm can use different quantum approaches: - Quantum Matrix Inversion: For density matrix diagonalization - Variational Quantum Eigensolver: For finding principal eigenvectors - Quantum Phase Estimation: For eigenvalue extraction - Quantum Singular Value Decomposition: Direct SVD approach
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
n_components
|
int
|
Number of principal components to extract |
2
|
method
|
str
|
Quantum method ('vqe', 'phase_estimation', 'matrix_inversion', 'qsvd') |
'vqe'
|
encoding
|
str
|
Data encoding method ('amplitude', 'dense', 'sparse') |
'amplitude'
|
max_iterations
|
int
|
Maximum iterations for variational methods |
1000
|
tolerance
|
float
|
Convergence tolerance |
1e-06
|
shots
|
int
|
Number of measurement shots |
1024
|
classical_fallback
|
bool
|
Use classical PCA if quantum fails |
True
|
**kwargs
|
Additional parameters |
{}
|
Example
qpca = QuantumPCA(backend='pennylane', n_components=3, method='vqe') qpca.fit(X_train) X_reduced = qpca.transform(X_test) X_reconstructed = qpca.inverse_transform(X_reduced)
Source code in src/superquantx/algorithms/quantum_pca.py
Functions¶
fit ¶
Fit quantum PCA to the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data |
required |
y
|
ndarray | None
|
Ignored (unsupervised learning) |
None
|
**kwargs
|
Additional fitting parameters |
{}
|
Returns:
| Type | Description |
|---|---|
QuantumPCA
|
Self for method chaining |
Source code in src/superquantx/algorithms/quantum_pca.py
transform ¶
Transform data to lower dimensional space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Data to transform |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Transformed data |
Source code in src/superquantx/algorithms/quantum_pca.py
inverse_transform ¶
Reconstruct data from lower dimensional representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_transformed
|
ndarray
|
Transformed data |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Reconstructed data |
Source code in src/superquantx/algorithms/quantum_pca.py
fit_transform ¶
predict ¶
get_quantum_advantage_metrics ¶
Analyze potential quantum advantage.
Source code in src/superquantx/algorithms/quantum_pca.py
compare_with_classical ¶
Compare quantum PCA results with classical PCA.
Source code in src/superquantx/algorithms/quantum_pca.py
analyze_convergence ¶
Analyze convergence properties of the quantum algorithm.
Source code in src/superquantx/algorithms/quantum_pca.py
get_params ¶
Get quantum PCA parameters.
Source code in src/superquantx/algorithms/quantum_pca.py
set_params ¶
Set quantum PCA parameters.
Source code in src/superquantx/algorithms/quantum_pca.py
Quantum K-Means¶
superquantx.algorithms.QuantumKMeans ¶
QuantumKMeans(backend: str | Any, n_clusters: int = 3, method: str = 'distance', distance_metric: str = 'euclidean', encoding: str = 'amplitude', max_iterations: int = 300, tolerance: float = 0.0001, init_method: str = 'k-means++', shots: int = 1024, classical_fallback: bool = True, normalize_data: bool = True, random_state: int | None = None, **kwargs)
Bases: UnsupervisedQuantumAlgorithm
Quantum K-Means clustering algorithm.
This implementation uses quantum algorithms to perform K-means clustering, potentially offering speedup for high-dimensional data through quantum distance calculations and amplitude estimation.
The algorithm can use different quantum approaches: - Quantum Distance Calculation: Use quantum circuits to compute distances - Quantum Amplitude Estimation: For probabilistic distance measurements - Variational Quantum Clustering: Use VQC for cluster optimization - Quantum Annealing: For global cluster optimization
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
n_clusters
|
int
|
Number of clusters (k) |
3
|
method
|
str
|
Quantum method ('distance', 'amplitude', 'variational', 'annealing') |
'distance'
|
distance_metric
|
str
|
Distance metric ('euclidean', 'manhattan', 'quantum') |
'euclidean'
|
encoding
|
str
|
Data encoding method ('amplitude', 'angle', 'dense') |
'amplitude'
|
max_iterations
|
int
|
Maximum iterations for clustering |
300
|
tolerance
|
float
|
Convergence tolerance |
0.0001
|
init_method
|
str
|
Centroid initialization ('random', 'k-means++', 'quantum') |
'k-means++'
|
shots
|
int
|
Number of measurement shots |
1024
|
classical_fallback
|
bool
|
Use classical K-means if quantum fails |
True
|
**kwargs
|
Additional parameters |
{}
|
Example
qkmeans = QuantumKMeans(backend='pennylane', n_clusters=3, method='distance') qkmeans.fit(X_train) labels = qkmeans.predict(X_test) centroids = qkmeans.cluster_centers_
Source code in src/superquantx/algorithms/quantum_kmeans.py
Functions¶
fit ¶
Fit quantum K-means to the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Training data |
required |
y
|
ndarray | None
|
Ignored (unsupervised learning) |
None
|
**kwargs
|
Additional fitting parameters |
{}
|
Returns:
| Type | Description |
|---|---|
QuantumKMeans
|
Self for method chaining |
Source code in src/superquantx/algorithms/quantum_kmeans.py
predict ¶
Predict cluster labels for new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Data to cluster |
required |
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Cluster labels |
Source code in src/superquantx/algorithms/quantum_kmeans.py
fit_predict ¶
transform ¶
Transform data to cluster-distance space.
Source code in src/superquantx/algorithms/quantum_kmeans.py
get_quantum_advantage_metrics ¶
Analyze potential quantum advantage.
Source code in src/superquantx/algorithms/quantum_kmeans.py
compare_with_classical ¶
Compare quantum K-means results with classical K-means.
Source code in src/superquantx/algorithms/quantum_kmeans.py
analyze_convergence ¶
Analyze convergence properties.
Source code in src/superquantx/algorithms/quantum_kmeans.py
get_params ¶
Get quantum K-means parameters.
Source code in src/superquantx/algorithms/quantum_kmeans.py
set_params ¶
Set quantum K-means parameters.
Source code in src/superquantx/algorithms/quantum_kmeans.py
Optimization Algorithms¶
Variational Quantum Eigensolver¶
superquantx.algorithms.VQE ¶
VQE(hamiltonian: ndarray | Any, ansatz: str | Callable = 'RealAmplitudes', backend: str | Any = 'simulator', optimizer: str = 'COBYLA', shots: int = 1024, maxiter: int = 1000, initial_params: ndarray | None = None, include_custom_gates: bool = False, client=None, reps: int = 1, **kwargs)
Bases: OptimizationQuantumAlgorithm
Variational Quantum Eigensolver for finding ground states.
VQE is a hybrid quantum-classical algorithm that uses a parameterized quantum circuit (ansatz) to find the ground state energy of a given Hamiltonian by minimizing the expectation value.
The algorithm works by: 1. Preparing a parameterized quantum state |ψ(θ)⟩ 2. Measuring the expectation value ⟨ψ(θ)|H|ψ(θ)⟩ 3. Classically optimizing parameters θ to minimize energy 4. Iterating until convergence
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
'simulator'
|
hamiltonian
|
ndarray | Any
|
Target Hamiltonian (matrix or operator) |
required |
ansatz
|
str | Callable
|
Parameterized circuit ansatz ('UCCSD', 'RealAmplitudes', etc.) |
'RealAmplitudes'
|
optimizer
|
str
|
Classical optimizer ('COBYLA', 'L-BFGS-B', etc.) |
'COBYLA'
|
shots
|
int
|
Number of measurement shots |
1024
|
maxiter
|
int
|
Maximum optimization iterations |
1000
|
initial_params
|
ndarray | None
|
Initial parameter values |
None
|
**kwargs
|
Additional parameters |
{}
|
Example
Define H2 molecule Hamiltonian¶
H2_hamiltonian = create_h2_hamiltonian(bond_distance=0.74) vqe = VQE(backend='pennylane', hamiltonian=H2_hamiltonian, ansatz='UCCSD') result = vqe.optimize() ground_energy = result.result['optimal_value']
Source code in src/superquantx/algorithms/vqe.py
Functions¶
exact_ground_energy ¶
fit ¶
Fit VQE (setup for optimization).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray | None
|
Optional Hamiltonian, if none was given to the constructor |
None
|
y
|
ndarray | None
|
Not used in VQE |
None
|
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
VQE
|
Self for method chaining |
Source code in src/superquantx/algorithms/vqe.py
predict ¶
Return the optimised state vector (qubit 0 most significant).
Source code in src/superquantx/algorithms/vqe.py
get_energy_landscape ¶
get_energy_landscape(param_indices: list[int], param_ranges: list[tuple[float, float]], resolution: int = 20) -> dict[str, Any]
Compute energy landscape for visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_indices
|
list[int]
|
Indices of parameters to vary |
required |
param_ranges
|
list[tuple[float, float]]
|
Ranges for each parameter |
required |
resolution
|
int
|
Number of points per dimension |
20
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with landscape data |
Source code in src/superquantx/algorithms/vqe.py
analyze_convergence ¶
Analyze VQE convergence properties.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Convergence analysis results |
Source code in src/superquantx/algorithms/vqe.py
compare_with_exact ¶
Compare VQE result with exact ground state energy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exact_ground_energy
|
float
|
Known exact ground state energy |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Comparison analysis |
Source code in src/superquantx/algorithms/vqe.py
get_params ¶
Get VQE parameters.
Source code in src/superquantx/algorithms/vqe.py
set_params ¶
Set VQE parameters.
Source code in src/superquantx/algorithms/vqe.py
find_ground_state ¶
Find the ground state energy of the Hamiltonian.
This is a convenience method that combines fit() and _run_optimization() to find the ground state energy in a single call.
Returns:
| Type | Description |
|---|---|
float
|
Ground state energy |
Example
vqe = VQE(backend='simulator', hamiltonian=hamiltonian) ground_energy = vqe.find_ground_state()
Source code in src/superquantx/algorithms/vqe.py
superquantx.algorithms.create_vqe_for_molecule ¶
create_vqe_for_molecule(molecule_name: str, bond_distance: float | None = None, backend: str = 'simulator', ansatz: str = 'RealAmplitudes', optimizer: str = 'COBYLA', client=None, **kwargs) -> VQE
Create a VQE instance for a small molecule.
Only H2 in STO-3G at its equilibrium bond length (0.735 Angstrom) ships
with the library. Other molecules or bond lengths need a Hamiltonian from
a chemistry package (e.g. PySCF + OpenFermion or Qiskit Nature) passed to
:class:VQE directly.
Source code in src/superquantx/algorithms/vqe.py
Quantum Approximate Optimization Algorithm¶
superquantx.algorithms.QAOA ¶
QAOA(backend: str | Any, p: int = 1, problem_hamiltonian: Callable | None = None, mixer_hamiltonian: Callable | None = None, initial_state: str = 'uniform_superposition', optimizer: str = 'COBYLA', shots: int = 1024, maxiter: int = 1000, n_restarts: int = 3, **kwargs)
Bases: OptimizationQuantumAlgorithm
Quantum Approximate Optimization Algorithm for combinatorial optimization.
QAOA is a hybrid quantum-classical algorithm that alternates between quantum evolution and classical parameter optimization to find approximate solutions to combinatorial optimization problems.
The algorithm works by: 1. Preparing an initial superposition state 2. Applying alternating problem and mixer Hamiltonians 3. Measuring the quantum state 4. Classically optimizing the parameters
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
p
|
int
|
Number of QAOA layers (depth) |
1
|
problem_hamiltonian
|
Callable | None
|
Problem Hamiltonian function |
None
|
mixer_hamiltonian
|
Callable | None
|
Mixer Hamiltonian function |
None
|
initial_state
|
str
|
Initial quantum state preparation |
'uniform_superposition'
|
optimizer
|
str
|
Classical optimizer ('COBYLA', 'L-BFGS-B', etc.) |
'COBYLA'
|
shots
|
int
|
Number of measurement shots |
1024
|
maxiter
|
int
|
Maximum optimization iterations |
1000
|
**kwargs
|
Additional parameters |
{}
|
Example
Define Max-Cut problem¶
def problem_ham(gamma, graph): ... return create_maxcut_hamiltonian(gamma, graph) qaoa = QAOA(backend='pennylane', p=2, problem_hamiltonian=problem_ham) result = qaoa.optimize(graph_data)
Source code in src/superquantx/algorithms/qaoa.py
Functions¶
fit ¶
Fit QAOA to problem instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Problem instance data (e.g., adjacency matrix for Max-Cut) |
required |
y
|
ndarray | None
|
Not used in QAOA |
None
|
**kwargs
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
QAOA
|
Self for method chaining |
Source code in src/superquantx/algorithms/qaoa.py
predict ¶
Sample the optimised circuit and return the best sampled partition.
Entry i of the returned 0/1 array is the side of node i.
Source code in src/superquantx/algorithms/qaoa.py
solve ¶
Fit, optimise and sample in one call, with an exact classical check.
Returns the QAOA partition and cut, the brute-force optimum, and the approximation ratio of the expected QAOA cut.
Source code in src/superquantx/algorithms/qaoa.py
get_optimization_landscape ¶
get_optimization_landscape(param_range: tuple[float, float], resolution: int = 50) -> dict[str, Any]
Compute optimization landscape for visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_range
|
tuple[float, float]
|
Range of parameters to explore |
required |
resolution
|
int
|
Number of points per dimension |
50
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with landscape data |
Source code in src/superquantx/algorithms/qaoa.py
analyze_solution_quality ¶
Analyze quality of QAOA solution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
true_optimum
|
float | None
|
Known optimal value for comparison |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Analysis results |
Source code in src/superquantx/algorithms/qaoa.py
get_params ¶
Get QAOA parameters.
Source code in src/superquantx/algorithms/qaoa.py
set_params ¶
Set QAOA parameters.
Source code in src/superquantx/algorithms/qaoa.py
Quantum Agents¶
Base Quantum Agent¶
superquantx.algorithms.quantum_agents.QuantumAgent ¶
QuantumAgent(backend: str | Any, agent_config: dict[str, Any] | None = None, shots: int = 1024, **kwargs)
Bases: BaseQuantumAlgorithm, ABC
Base class for quantum agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend for circuit execution |
required |
agent_config
|
dict[str, Any] | None
|
Configuration dictionary for the agent |
None
|
shots
|
int
|
Number of measurement shots |
1024
|
**kwargs
|
Additional parameters (for example |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
solve
abstractmethod
¶
get_agent_info ¶
Get information about the agent and its algorithms.
Source code in src/superquantx/algorithms/quantum_agents.py
Specialized Agents¶
superquantx.algorithms.quantum_agents.QuantumPortfolioAgent ¶
QuantumPortfolioAgent(backend: str | Any, n_select: int | None = None, risk_aversion: float = 1.0, reps: int = 2, alpha: float = 0.25, n_restarts: int = 5, maxiter: int = 300, **kwargs)
Bases: QuantumAgent
Pick k of n assets with CVaR-VQE, checked against exact classical answers.
The selection problem is encoded as a diagonal Ising Hamiltonian whose
ground state is the best equal-weight k-asset portfolio. A
RealAmplitudes circuit is trained on the chosen backend to minimise the
CVaR of the energy (the mean of the best alpha fraction of outcomes,
Barkoutsos et al., Quantum 4, 256 (2020)), which works much better than the
plain expectation for combinatorial problems. shots samples are drawn
from the final state and the best sampled selection is returned. Two classical references are always
computed in the same call: the brute-force optimum of the same QUBO and a
long-only Markowitz solution with continuous weights. Practical up to
about 10 assets (2^n statevector).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
n_select
|
int | None
|
Number of assets to hold (default: half the assets) |
None
|
risk_aversion
|
float
|
Weight of the variance term |
1.0
|
reps
|
int
|
Ansatz repetitions |
2
|
alpha
|
float
|
CVaR fraction (1.0 is ordinary VQE) |
0.25
|
n_restarts
|
int
|
Optimizer restarts from different seeds |
5
|
maxiter
|
int
|
Optimizer iterations per restart |
300
|
**kwargs
|
|
{}
|
Example
agent = QuantumPortfolioAgent(backend='simulator', n_select=2, seed=0) res = agent.solve(returns) # returns: (periods x assets) res.result['selected_assets'], res.result['matches_classical_optimum']
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Estimate mean returns and covariance from a (periods x assets) matrix.
Source code in src/superquantx/algorithms/quantum_agents.py
solve ¶
Select assets with VQE and report the classical checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_instance
|
ndarray | None
|
Optional returns matrix; refits the agent if given. |
None
|
Returns:
| Type | Description |
|---|---|
QuantumResult
|
QuantumResult whose |
QuantumResult
|
its objective, the brute-force optimum, whether they match, the |
QuantumResult
|
probability VQE puts on the optimal selection, and a classical |
QuantumResult
|
Markowitz reference. |
Source code in src/superquantx/algorithms/quantum_agents.py
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
predict ¶
Return the equal weights of the VQE selection.
superquantx.algorithms.quantum_agents.QuantumOptimizationAgent ¶
QuantumOptimizationAgent(backend: str | Any, problem_type: str = 'combinatorial', p: int = 2, algorithms: list[str] | None = None, maxiter: int = 200, n_restarts: int = 3, reps: int = 2, **kwargs)
Bases: QuantumAgent
Solve small optimisation problems with QAOA or VQE plus an exact classical check.
problem_type='combinatorial':solve(adjacency)runs weighted MaxCut with QAOA and compares against brute force.problem_type='continuous':solve(hamiltonian)runs VQE and compares against exact diagonalisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
problem_type
|
str
|
'combinatorial' or 'continuous' |
'combinatorial'
|
p
|
int
|
QAOA layers |
2
|
**kwargs
|
Base parameters and extra QAOA/VQE options ( |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Store the problem: an adjacency matrix or a Hamiltonian.
solve ¶
Solve and return the quantum answer with its exact classical check.
Source code in src/superquantx/algorithms/quantum_agents.py
predict ¶
MaxCut partition (combinatorial) or energy (continuous).
Source code in src/superquantx/algorithms/quantum_agents.py
superquantx.algorithms.quantum_agents.QuantumClassificationAgent ¶
QuantumClassificationAgent(backend: str | Any, algorithms: list[str] | None = None, ensemble_method: str = 'voting', cv: int = 5, **kwargs)
Bases: QuantumAgent
Train quantum classifiers and benchmark them against tuned classical models.
solve((X, y)) runs :func:superquantx.benchmarks.compare_to_classical
on the first algorithm (QuantumSVM by default) so that the reported
accuracy is a cross-validated test accuracy next to a tuned RBF SVM and a
logistic regression on identical folds, then refits on all the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
algorithms
|
list[str] | None
|
Any of 'quantum_svm', 'quantum_nn', 'hybrid' |
None
|
ensemble_method
|
str
|
'voting', 'weighted' or 'best' (used by predict when several algorithms are trained) |
'voting'
|
cv
|
int
|
Folds for the benchmark in |
5
|
**kwargs
|
Base parameters |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Fit every algorithm. Errors propagate; nothing is silently scored as 0.
Source code in src/superquantx/algorithms/quantum_agents.py
predict ¶
Predict with one algorithm, or combine several.
Source code in src/superquantx/algorithms/quantum_agents.py
solve ¶
Benchmark against classical baselines with CV, then fit on all data.
Keyword arguments are passed to compare_to_classical.
Source code in src/superquantx/algorithms/quantum_agents.py
Examples and Usage Patterns¶
Machine Learning Example¶
import numpy as np
from sklearn.datasets import make_classification
import superquantx as sqx
# Generate sample data
X, y = make_classification(
n_samples=100,
n_features=4,
n_classes=2,
random_state=42
)
# Split data
X_train, X_test = X[:80], X[80:]
y_train, y_test = y[:80], y[80:]
# Create and train Quantum SVM
qsvm = sqx.QuantumSVM(
backend='simulator',
feature_map='ZFeatureMap',
num_features=4
)
qsvm.fit(X_train, y_train)
predictions = qsvm.predict(X_test)
accuracy = qsvm.score(X_test, y_test)
print(f"Quantum SVM Accuracy: {accuracy:.3f}")
VQE Molecule Example¶
import superquantx as sqx
# Create VQE for H2 molecule
vqe = sqx.create_vqe_for_molecule(
molecule='H2',
bond_length=0.735, # Angstroms
backend='simulator'
)
# Find ground state
ground_energy = vqe.find_ground_state()
print(f"H2 Ground State Energy: {ground_energy:.6f} Ha")
# Get optimized parameters
optimal_params = vqe.get_optimal_parameters()
print(f"Optimal parameters: {optimal_params}")
QAOA Optimization Example¶
import superquantx as sqx
# Define Max-Cut problem
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]
qaoa = sqx.QAOA(
problem_type='max_cut',
graph_edges=edges,
layers=3,
backend='simulator'
)
# Solve optimization problem
solution = qaoa.solve()
optimal_value = qaoa.get_optimal_value()
print(f"Max-Cut Solution: {solution}")
print(f"Cut Value: {optimal_value}")
Quantum Agent Example¶
import superquantx as sqx
# Create quantum portfolio optimization agent
portfolio_agent = sqx.QuantumPortfolioAgent(
backend='simulator',
risk_tolerance=0.1,
optimization_method='qaoa'
)
# Sample portfolio data
assets = ['AAPL', 'GOOGL', 'MSFT', 'TSLA']
returns = [0.12, 0.15, 0.08, 0.20]
risks = [0.05, 0.10, 0.03, 0.15]
# Optimize portfolio
optimal_weights = portfolio_agent.optimize_portfolio(
assets=assets,
expected_returns=returns,
risk_estimates=risks,
budget=10000
)
print("Optimal Portfolio:")
for asset, weight in zip(assets, optimal_weights):
print(f"{asset}: {weight:.2%}")
Best Practices¶
Algorithm Selection¶
- For Classification: Use
QuantumSVMfor small datasets,QuantumNNfor complex patterns - For Optimization: Use
VQEfor chemistry problems,QAOAfor combinatorial optimization - For Autonomous Tasks: Use specialized
QuantumAgentimplementations
Backend Optimization¶
# Choose appropriate backend for algorithm
algorithms_backends = {
'QuantumSVM': 'pennylane', # Best autodiff support
'VQE': 'qiskit', # Good hardware access
'QAOA': 'cirq', # Flexible circuit construction
'QuantumAgents': 'simulator', # Fast prototyping
}
# Use backend-specific optimizations
qsvm = sqx.QuantumSVM(
backend='pennylane',
feature_map='ZZFeatureMap', # More expressive for PennyLane
optimization_level=2
)
Performance Monitoring¶
import time
import superquantx as sqx
# Benchmark different algorithms
def benchmark_algorithm(algorithm_class, X, y, **kwargs):
start_time = time.time()
algorithm = algorithm_class(**kwargs)
algorithm.fit(X, y)
predictions = algorithm.predict(X)
execution_time = time.time() - start_time
accuracy = algorithm.score(X, y)
return {
'accuracy': accuracy,
'time': execution_time,
'algorithm': algorithm_class.__name__
}
# Compare algorithms
algorithms = [sqx.QuantumSVM, sqx.QuantumNN, sqx.HybridClassifier]
results = []
for algo in algorithms:
result = benchmark_algorithm(algo, X_train, y_train, backend='simulator')
results.append(result)
print(f"{result['algorithm']}: {result['accuracy']:.3f} accuracy in {result['time']:.2f}s")
For complete algorithm implementations and advanced usage patterns, see: - Backend Integration Guide - Tutorial Examples - User Guide