Algorithms API Reference¶
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 = '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, **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
|
Type of quantum feature map ('ZZFeatureMap', 'PauliFeatureMap', etc.) |
'ZZFeatureMap'
|
feature_map_reps
|
int
|
Number of repetitions in the feature map |
2
|
C
|
float
|
Regularization parameter for SVM |
1.0
|
gamma
|
float | None
|
Kernel coefficient (for RBF-like quantum kernels) |
None
|
quantum_kernel
|
Callable | None
|
Custom quantum kernel function |
None
|
shots
|
int
|
Number of measurement shots |
1024
|
**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)
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
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 362 363 364 365 366 367 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 |
|
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, **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¶
fit ¶
Fit VQE (setup for optimization).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray | None
|
Not used in VQE |
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 ¶
Get ground state wavefunction coefficients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray | None
|
Not used |
None
|
**kwargs
|
Additional parameters |
{}
|
Returns:
Type | Description |
---|---|
ndarray
|
Ground state wavefunction |
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, backend: str = 'simulator', ansatz: str = 'UCCSD', optimizer: str = 'COBYLA', client=None) -> VQE
Create a VQE instance pre-configured for molecular simulation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
molecule_name
|
str
|
Name of the molecule (e.g., 'H2', 'LiH') |
required |
bond_distance
|
float
|
Bond distance for the molecule (uses default if None) |
None
|
backend
|
str
|
Quantum backend to use |
'simulator'
|
ansatz
|
str
|
Ansatz circuit type |
'UCCSD'
|
optimizer
|
str
|
Classical optimizer |
'COBYLA'
|
client
|
Optional client for quantum execution |
None
|
Returns:
Type | Description |
---|---|
VQE
|
Configured VQE instance |
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, **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 ¶
Get optimal solution from QAOA results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Problem instance (not used if same as training) |
required |
**kwargs
|
Additional parameters |
{}
|
Returns:
Type | Description |
---|---|
ndarray
|
Optimal bit string solution |
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.
Quantum agents are specialized combinations of quantum algorithms designed for specific problem domains. They provide high-level interfaces for complex quantum machine learning workflows.
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 |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
solve
abstractmethod
¶
Solve a problem using the quantum agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
problem_instance
|
Any
|
Problem data/specification |
required |
**kwargs
|
Additional solving parameters |
{}
|
Returns:
Type | Description |
---|---|
QuantumResult
|
Solution result |
Source code in src/superquantx/algorithms/quantum_agents.py
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, risk_model: str = 'mean_variance', optimization_objective: str = 'sharpe', constraints: list[dict] | None = None, rebalancing_frequency: str = 'monthly', **kwargs)
Bases: QuantumAgent
Quantum agent for portfolio optimization.
This agent combines QAOA and VQE algorithms to solve portfolio optimization problems including mean-variance optimization, risk parity, and constrained optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
risk_model
|
str
|
Risk model to use ('mean_variance', 'black_litterman', 'factor') |
'mean_variance'
|
optimization_objective
|
str
|
Objective function ('return', 'sharpe', 'risk_parity') |
'sharpe'
|
constraints
|
list[dict] | None
|
List of constraint specifications |
None
|
rebalancing_frequency
|
str
|
How often to rebalance |
'monthly'
|
**kwargs
|
Additional parameters |
{}
|
Example
agent = QuantumPortfolioAgent( ... backend='pennylane', ... risk_model='mean_variance', ... optimization_objective='sharpe' ... ) result = agent.solve(portfolio_data) optimal_weights = result.result['weights']
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Fit the portfolio agent to historical data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Historical returns data (samples x assets) |
required |
y
|
ndarray | None
|
Not used |
None
|
**kwargs
|
Additional parameters |
{}
|
Returns:
Type | Description |
---|---|
QuantumPortfolioAgent
|
Self |
Source code in src/superquantx/algorithms/quantum_agents.py
predict ¶
Predict optimal portfolio weights.
Source code in src/superquantx/algorithms/quantum_agents.py
solve ¶
Solve portfolio optimization problem.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
problem_instance
|
ndarray
|
Returns data or problem specification |
required |
**kwargs
|
Solving parameters |
{}
|
Returns:
Type | Description |
---|---|
QuantumResult
|
Portfolio optimization result |
Source code in src/superquantx/algorithms/quantum_agents.py
superquantx.algorithms.quantum_agents.QuantumOptimizationAgent ¶
QuantumOptimizationAgent(backend: str | Any, problem_type: str = 'combinatorial', algorithms: list[str] | None = None, **kwargs)
Bases: QuantumAgent
Quantum agent for optimization problems.
This agent provides a unified interface for solving various optimization problems using QAOA, VQE, and other quantum optimization algorithms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
problem_type
|
str
|
Type of optimization ('combinatorial', 'continuous', 'mixed') |
'combinatorial'
|
algorithms
|
list[str] | None
|
List of algorithms to use |
None
|
**kwargs
|
Additional parameters |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Fit optimization algorithms to problem.
Source code in src/superquantx/algorithms/quantum_agents.py
predict ¶
Predict optimal solution.
Source code in src/superquantx/algorithms/quantum_agents.py
solve ¶
Solve optimization problem.
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', auto_tune: bool = False, **kwargs)
Bases: QuantumAgent
Quantum agent for classification tasks.
This agent combines multiple quantum classifiers and provides automatic model selection, hyperparameter optimization, and ensemble methods for robust classification.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backend
|
str | Any
|
Quantum backend |
required |
algorithms
|
list[str] | None
|
List of algorithms to include ('quantum_svm', 'quantum_nn', 'hybrid') |
None
|
ensemble_method
|
str
|
How to combine predictions ('voting', 'weighted', 'stacking') |
'voting'
|
auto_tune
|
bool
|
Whether to automatically tune hyperparameters |
False
|
**kwargs
|
Additional parameters |
{}
|
Source code in src/superquantx/algorithms/quantum_agents.py
Functions¶
fit ¶
Fit all classification algorithms.
Source code in src/superquantx/algorithms/quantum_agents.py
predict ¶
Make ensemble predictions.
Source code in src/superquantx/algorithms/quantum_agents.py
solve ¶
Solve classification problem.
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
QuantumSVM
for small datasets,QuantumNN
for complex patterns - For Optimization: Use
VQE
for chemistry problems,QAOA
for combinatorial optimization - For Autonomous Tasks: Use specialized
QuantumAgent
implementations
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