Utilities API Reference¶
SuperQuantX provides comprehensive utility modules for optimization, visualization, benchmarking, data handling, and command-line operations. This API reference covers all utility functions and classes.
Optimization Utilities¶
Circuit Optimization¶
superquantx.utils.optimization.optimize_circuit ¶
optimize_circuit(cost_function: Callable[[ndarray], float], initial_params: ndarray, gradient_function: Callable[[ndarray], ndarray] | None = None, optimizer: str = 'adam', max_iterations: int = 100, tolerance: float = 1e-06, learning_rate: float = 0.01, verbose: bool = False) -> dict[str, Any]
Optimize quantum circuit parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cost_function
|
Callable[[ndarray], float]
|
Function to minimize f(params) -> cost |
required |
initial_params
|
ndarray
|
Initial parameter values |
required |
gradient_function
|
Callable[[ndarray], ndarray] | None
|
Function to compute gradients (optional) |
None
|
optimizer
|
str
|
Optimizer type ('adam', 'sgd', 'lbfgs') |
'adam'
|
max_iterations
|
int
|
Maximum number of iterations |
100
|
tolerance
|
float
|
Convergence tolerance |
1e-06
|
learning_rate
|
float
|
Learning rate for gradient-based optimizers |
0.01
|
verbose
|
bool
|
Whether to print progress |
False
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary with optimization results |
Source code in src/superquantx/utils/optimization.py
superquantx.utils.optimization.optimize_parameters ¶
optimize_parameters(objective_function: Callable, bounds: list[tuple[float, float]], method: str = 'scipy', max_evaluations: int = 1000, random_state: int | None = None) -> dict[str, Any]
Optimize parameters using various methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
objective_function
|
Callable
|
Function to minimize |
required |
bounds
|
list[tuple[float, float]]
|
Parameter bounds as list of (min, max) tuples |
required |
method
|
str
|
Optimization method ('scipy', 'random_search', 'grid_search') |
'scipy'
|
max_evaluations
|
int
|
Maximum function evaluations |
1000
|
random_state
|
int | None
|
Random seed |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Optimization results dictionary |
Source code in src/superquantx/utils/optimization.py
Optimizers¶
superquantx.utils.optimization.gradient_descent ¶
gradient_descent(cost_function: Callable[[ndarray], float], gradient_function: Callable[[ndarray], ndarray], initial_params: ndarray, learning_rate: float = 0.01, max_iterations: int = 1000, tolerance: float = 1e-06) -> tuple[np.ndarray, list[float]]
Perform gradient descent optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cost_function
|
Callable[[ndarray], float]
|
Cost function to minimize |
required |
gradient_function
|
Callable[[ndarray], ndarray]
|
Function returning gradients |
required |
initial_params
|
ndarray
|
Initial parameter values |
required |
learning_rate
|
float
|
Learning rate |
0.01
|
max_iterations
|
int
|
Maximum iterations |
1000
|
tolerance
|
float
|
Convergence tolerance |
1e-06
|
Returns:
Type | Description |
---|---|
tuple[ndarray, list[float]]
|
Tuple of (optimal_params, cost_history) |
Source code in src/superquantx/utils/optimization.py
superquantx.utils.optimization.adam_optimizer ¶
adam_optimizer(cost_function: Callable[[ndarray], float], gradient_function: Callable[[ndarray], ndarray], initial_params: ndarray, learning_rate: float = 0.001, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-08, max_iterations: int = 1000, tolerance: float = 1e-06) -> tuple[np.ndarray, list[float]]
Perform Adam optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cost_function
|
Callable[[ndarray], float]
|
Cost function to minimize |
required |
gradient_function
|
Callable[[ndarray], ndarray]
|
Function returning gradients |
required |
initial_params
|
ndarray
|
Initial parameter values |
required |
learning_rate
|
float
|
Learning rate |
0.001
|
beta1
|
float
|
Exponential decay rate for first moment |
0.9
|
beta2
|
float
|
Exponential decay rate for second moment |
0.999
|
epsilon
|
float
|
Small constant for numerical stability |
1e-08
|
max_iterations
|
int
|
Maximum iterations |
1000
|
tolerance
|
float
|
Convergence tolerance |
1e-06
|
Returns:
Type | Description |
---|---|
tuple[ndarray, list[float]]
|
Tuple of (optimal_params, cost_history) |
Source code in src/superquantx/utils/optimization.py
Visualization Utilities¶
Result Visualization¶
superquantx.utils.visualization.visualize_results ¶
visualize_results(results: dict[str, Any], plot_type: str = 'optimization', backend: str = 'matplotlib', save_path: str | None = None, **kwargs) -> None
Visualize quantum machine learning results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
dict[str, Any]
|
Results dictionary from algorithm execution |
required |
plot_type
|
str
|
Type of plot ('optimization', 'classification', 'regression') |
'optimization'
|
backend
|
str
|
Plotting backend ('matplotlib' or 'plotly') |
'matplotlib'
|
save_path
|
str | None
|
Path to save the plot |
None
|
**kwargs
|
Additional plotting arguments |
{}
|
Source code in src/superquantx/utils/visualization.py
superquantx.utils.visualization.plot_optimization_history ¶
plot_optimization_history(results: dict[str, Any], backend: str = 'matplotlib', save_path: str | None = None, **kwargs) -> None
Plot optimization history from algorithm results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
dict[str, Any]
|
Results containing 'cost_history' or similar |
required |
backend
|
str
|
Plotting backend |
'matplotlib'
|
save_path
|
str | None
|
Path to save the plot |
None
|
**kwargs
|
Additional plotting arguments |
{}
|
Source code in src/superquantx/utils/visualization.py
Quantum State Visualization¶
superquantx.utils.visualization.plot_circuit ¶
plot_circuit(circuit_data: dict[str, Any], backend: str = 'matplotlib', save_path: str | None = None, **kwargs) -> None
Plot quantum circuit diagram.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
circuit_data
|
dict[str, Any]
|
Circuit information dictionary |
required |
backend
|
str
|
Plotting backend |
'matplotlib'
|
save_path
|
str | None
|
Path to save the plot |
None
|
**kwargs
|
Additional plotting arguments |
{}
|
Source code in src/superquantx/utils/visualization.py
superquantx.utils.visualization.plot_quantum_state ¶
plot_quantum_state(state_vector: ndarray, backend: str = 'matplotlib', representation: str = 'bar', save_path: str | None = None, **kwargs) -> None
Plot quantum state vector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_vector
|
ndarray
|
Complex quantum state vector |
required |
backend
|
str
|
Plotting backend |
'matplotlib'
|
representation
|
str
|
How to represent state ('bar', 'phase', 'bloch') |
'bar'
|
save_path
|
str | None
|
Path to save the plot |
None
|
**kwargs
|
Additional plotting arguments |
{}
|
Source code in src/superquantx/utils/visualization.py
superquantx.utils.visualization.plot_bloch_sphere ¶
plot_bloch_sphere(state_vector: ndarray, backend: str = 'matplotlib', save_path: str | None = None, **kwargs) -> None
Plot quantum state on Bloch sphere (for single qubit states).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_vector
|
ndarray
|
Single qubit state vector [α, β] |
required |
backend
|
str
|
Plotting backend |
'matplotlib'
|
save_path
|
str | None
|
Path to save the plot |
None
|
**kwargs
|
Additional plotting arguments |
{}
|
Source code in src/superquantx/utils/visualization.py
Benchmarking Utilities¶
Algorithm Benchmarking¶
superquantx.utils.benchmarking.benchmark_algorithm ¶
benchmark_algorithm(algorithm: Any, datasets: list[tuple[str, Any]], metrics: list[str] | None = None, n_runs: int = 1, verbose: bool = True) -> list[BenchmarkResult]
Benchmark quantum algorithm performance across multiple datasets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
algorithm
|
Any
|
Quantum algorithm instance |
required |
datasets
|
list[tuple[str, Any]]
|
List of (name, dataset) tuples |
required |
metrics
|
list[str] | None
|
List of metrics to compute |
None
|
n_runs
|
int
|
Number of runs for averaging |
1
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
Type | Description |
---|---|
list[BenchmarkResult]
|
List of benchmark results |
Source code in src/superquantx/utils/benchmarking.py
superquantx.utils.benchmarking.benchmark_backend ¶
benchmark_backend(backends: list[Any], test_circuit: Callable, n_qubits_range: list[int] = None, n_shots: int = 1024, verbose: bool = True) -> dict[str, list[BenchmarkResult]]
Benchmark different quantum backends.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
backends
|
list[Any]
|
List of backend instances |
required |
test_circuit
|
Callable
|
Function that creates test circuit |
required |
n_qubits_range
|
list[int]
|
Range of qubit numbers to test |
None
|
n_shots
|
int
|
Number of shots for each measurement |
1024
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
Type | Description |
---|---|
dict[str, list[BenchmarkResult]]
|
Dictionary mapping backend names to benchmark results |
Source code in src/superquantx/utils/benchmarking.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
|
Performance Analysis¶
superquantx.utils.benchmarking.performance_metrics ¶
performance_metrics(y_true: ndarray, y_pred: ndarray, task_type: str = 'classification') -> dict[str, float]
Compute performance metrics for predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_true
|
ndarray
|
True labels/values |
required |
y_pred
|
ndarray
|
Predicted labels/values |
required |
task_type
|
str
|
Type of task ('classification' or 'regression') |
'classification'
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary of computed metrics |
Source code in src/superquantx/utils/benchmarking.py
superquantx.utils.benchmarking.compare_algorithms ¶
compare_algorithms(algorithms: list[Any], dataset: Any, metrics: list[str] = None, n_runs: int = 3, verbose: bool = True) -> dict[str, Any]
Compare multiple algorithms on the same dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
algorithms
|
list[Any]
|
List of algorithm instances |
required |
dataset
|
Any
|
Dataset to use for comparison |
required |
metrics
|
list[str]
|
Metrics to compare |
None
|
n_runs
|
int
|
Number of runs for averaging |
3
|
verbose
|
bool
|
Whether to print progress |
True
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Comparison results dictionary |
Source code in src/superquantx/utils/benchmarking.py
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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
|
Feature Mapping Utilities¶
Quantum Feature Maps¶
superquantx.utils.feature_mapping.QuantumFeatureMap ¶
QuantumFeatureMap(n_features: int, reps: int = 1, entanglement: str = 'full', parameter_prefix: str = 'x')
Bases: ABC
Abstract base class for quantum feature maps.
Feature maps encode classical data into quantum states by applying parameterized quantum gates based on the input features.
Source code in src/superquantx/utils/feature_mapping.py
Attributes¶
Functions¶
map_data_point ¶
Map a single data point to quantum circuit parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
ndarray
|
Input data point of length n_features |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Circuit representation with parameters |
Source code in src/superquantx/utils/feature_mapping.py
map_data ¶
Map multiple data points to quantum circuits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Input data of shape (n_samples, n_features) |
required |
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
List of circuit representations |
Source code in src/superquantx/utils/feature_mapping.py
superquantx.utils.feature_mapping.create_feature_map ¶
Factory function to create quantum feature maps.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
feature_map_type
|
str
|
Type of feature map ('Z', 'ZZ', 'Pauli') |
required |
n_features
|
int
|
Number of input features |
required |
**kwargs
|
Additional arguments for specific feature maps |
{}
|
Returns:
Type | Description |
---|---|
QuantumFeatureMap
|
QuantumFeatureMap instance |
Source code in src/superquantx/utils/feature_mapping.py
Specific Feature Maps¶
superquantx.utils.feature_mapping.pauli_feature_map ¶
pauli_feature_map(n_features: int, paulis: list[str] = None, reps: int = 1, alpha: float = 2.0, entanglement: str = 'full') -> PauliFeatureMap
Create a Pauli feature map with specified Pauli strings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_features
|
int
|
Number of input features |
required |
paulis
|
list[str]
|
List of Pauli strings to use |
None
|
reps
|
int
|
Number of repetitions |
1
|
alpha
|
float
|
Scaling factor |
2.0
|
entanglement
|
str
|
Entanglement pattern |
'full'
|
Returns:
Type | Description |
---|---|
PauliFeatureMap
|
PauliFeatureMap instance |
Source code in src/superquantx/utils/feature_mapping.py
superquantx.utils.feature_mapping.zz_feature_map ¶
zz_feature_map(n_features: int, reps: int = 1, entanglement: str = 'linear', alpha: float = 2.0) -> ZZFeatureMap
Create a ZZ feature map with specified parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_features
|
int
|
Number of input features |
required |
reps
|
int
|
Number of repetitions |
1
|
entanglement
|
str
|
Entanglement pattern ('linear', 'circular', 'full') |
'linear'
|
alpha
|
float
|
Scaling factor |
2.0
|
Returns:
Type | Description |
---|---|
ZZFeatureMap
|
ZZFeatureMap instance |
Source code in src/superquantx/utils/feature_mapping.py
Quantum Utilities¶
Quantum Information Measures¶
superquantx.utils.quantum_utils.fidelity ¶
Calculate quantum fidelity between two quantum states.
For pure states |ψ₁⟩ and |ψ₂⟩: F(ψ₁, ψ₂) = |⟨ψ₁|ψ₂⟩|²
For mixed states ρ₁ and ρ₂: F(ρ₁, ρ₂) = Tr(√(√ρ₁ ρ₂ √ρ₁))²
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state1
|
ndarray
|
First quantum state (vector or density matrix) |
required |
state2
|
ndarray
|
Second quantum state (vector or density matrix) |
required |
validate
|
bool
|
Whether to validate inputs |
True
|
Returns:
Type | Description |
---|---|
float
|
Fidelity value between 0 and 1 |
Source code in src/superquantx/utils/quantum_utils.py
superquantx.utils.quantum_utils.trace_distance ¶
Calculate trace distance between two quantum states.
For quantum states ρ₁ and ρ₂: D(ρ₁, ρ₂) = (½) * Tr(|ρ₁ - ρ₂|)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state1
|
ndarray
|
First quantum state |
required |
state2
|
ndarray
|
Second quantum state |
required |
validate
|
bool
|
Whether to validate inputs |
True
|
Returns:
Type | Description |
---|---|
float
|
Trace distance between 0 and 1 |
Source code in src/superquantx/utils/quantum_utils.py
superquantx.utils.quantum_utils.quantum_mutual_information ¶
quantum_mutual_information(joint_state: ndarray, subsystem_dims: tuple[int, int], validate: bool = True) -> float
Calculate quantum mutual information between two subsystems.
I(A:B) = S(ρₐ) + S(ρᵦ) - S(ρₐᵦ)
where S(ρ) is the von Neumann entropy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
joint_state
|
ndarray
|
Joint quantum state of both subsystems |
required |
subsystem_dims
|
tuple[int, int]
|
Dimensions of subsystems (dim_A, dim_B) |
required |
validate
|
bool
|
Whether to validate inputs |
True
|
Returns:
Type | Description |
---|---|
float
|
Quantum mutual information |
Source code in src/superquantx/utils/quantum_utils.py
superquantx.utils.quantum_utils.entanglement_measure ¶
entanglement_measure(state: ndarray, subsystem_dims: tuple[int, int], measure: str = 'negativity', validate: bool = True) -> float
Calculate entanglement measure for a bipartite quantum state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
ndarray
|
Quantum state (pure or mixed) |
required |
subsystem_dims
|
tuple[int, int]
|
Dimensions of subsystems (dim_A, dim_B) |
required |
measure
|
str
|
Type of measure ('negativity', 'concurrence', 'entropy') |
'negativity'
|
validate
|
bool
|
Whether to validate inputs |
True
|
Returns:
Type | Description |
---|---|
float
|
Entanglement measure value |
Source code in src/superquantx/utils/quantum_utils.py
Classical Utilities¶
Machine Learning Utilities¶
superquantx.utils.classical_utils.cross_validation ¶
cross_validation(algorithm: Any, X: ndarray, y: ndarray, cv_folds: int = 5, scoring: str = 'accuracy', stratify: bool = True, random_state: int | None = 42, verbose: bool = False) -> CrossValidationResult
Perform k-fold cross-validation on quantum algorithm.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
algorithm
|
Any
|
Quantum algorithm instance |
required |
X
|
ndarray
|
Feature matrix |
required |
y
|
ndarray
|
Target vector |
required |
cv_folds
|
int
|
Number of CV folds |
5
|
scoring
|
str
|
Scoring metric ('accuracy', 'mse', 'mae') |
'accuracy'
|
stratify
|
bool
|
Whether to use stratified CV for classification |
True
|
random_state
|
int | None
|
Random seed |
42
|
verbose
|
bool
|
Whether to print progress |
False
|
Returns:
Type | Description |
---|---|
CrossValidationResult
|
CrossValidationResult with scores and timing info |
Source code in src/superquantx/utils/classical_utils.py
superquantx.utils.classical_utils.hyperparameter_search ¶
hyperparameter_search(algorithm_class: type, param_grid: dict[str, list[Any]], X: ndarray, y: ndarray, cv_folds: int = 3, scoring: str = 'accuracy', n_jobs: int = 1, random_state: int | None = 42, verbose: bool = False) -> dict[str, Any]
Perform grid search for hyperparameter optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
algorithm_class
|
type
|
Quantum algorithm class |
required |
param_grid
|
dict[str, list[Any]]
|
Dictionary of parameter names and values to try |
required |
X
|
ndarray
|
Feature matrix |
required |
y
|
ndarray
|
Target vector |
required |
cv_folds
|
int
|
Number of CV folds |
3
|
scoring
|
str
|
Scoring metric |
'accuracy'
|
n_jobs
|
int
|
Number of parallel jobs (not implemented) |
1
|
random_state
|
int | None
|
Random seed |
42
|
verbose
|
bool
|
Whether to print progress |
False
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary with best parameters and results |
Source code in src/superquantx/utils/classical_utils.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
|
superquantx.utils.classical_utils.model_selection ¶
model_selection(algorithms: list[tuple[str, type, dict[str, Any]]], X: ndarray, y: ndarray, cv_folds: int = 5, scoring: str = 'accuracy', test_size: float = 0.2, random_state: int | None = 42, verbose: bool = False) -> dict[str, Any]
Compare multiple algorithms and select the best one.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
algorithms
|
list[tuple[str, type, dict[str, Any]]]
|
List of (name, class, params) tuples |
required |
X
|
ndarray
|
Feature matrix |
required |
y
|
ndarray
|
Target vector |
required |
cv_folds
|
int
|
Number of CV folds |
5
|
scoring
|
str
|
Scoring metric |
'accuracy'
|
test_size
|
float
|
Proportion for test set |
0.2
|
random_state
|
int | None
|
Random seed |
42
|
verbose
|
bool
|
Whether to print progress |
False
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary with model selection results |
Source code in src/superquantx/utils/classical_utils.py
206 207 208 209 210 211 212 213 214 215 216 217 218 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 |
|
superquantx.utils.classical_utils.data_splitting ¶
data_splitting(X: ndarray, y: ndarray, train_size: float = 0.7, val_size: float = 0.15, test_size: float = 0.15, stratify: bool = True, random_state: int | None = 42) -> tuple[np.ndarray, ...]
Split data into train, validation, and test sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Feature matrix |
required |
y
|
ndarray
|
Target vector |
required |
train_size
|
float
|
Proportion for training |
0.7
|
val_size
|
float
|
Proportion for validation |
0.15
|
test_size
|
float
|
Proportion for testing |
0.15
|
stratify
|
bool
|
Whether to stratify splits for classification |
True
|
random_state
|
int | None
|
Random seed |
42
|
Returns:
Type | Description |
---|---|
tuple[ndarray, ...]
|
Tuple of (X_train, X_val, X_test, y_train, y_val, y_test) |
Source code in src/superquantx/utils/classical_utils.py
Datasets¶
Quantum-Adapted Classical Datasets¶
superquantx.datasets.load_iris_quantum ¶
load_iris_quantum(n_features: Optional[int] = None, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Load and preprocess the Iris dataset for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_features
|
Optional[int]
|
Number of features to keep (default: all 4) |
None
|
encoding
|
str
|
Type of quantum encoding ('amplitude', 'angle', 'basis') |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion of dataset for testing |
0.2
|
random_state
|
Optional[int]
|
Random seed for reproducibility |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/quantum_datasets.py
superquantx.datasets.load_wine_quantum ¶
load_wine_quantum(n_features: Optional[int] = 8, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Load and preprocess the Wine dataset for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_features
|
Optional[int]
|
Number of top features to keep (default: 8) |
8
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion of dataset for testing |
0.2
|
random_state
|
Optional[int]
|
Random seed for reproducibility |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/quantum_datasets.py
superquantx.datasets.load_digits_quantum ¶
load_digits_quantum(n_classes: int = 10, n_pixels: Optional[int] = 32, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Load and preprocess the Digits dataset for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_classes
|
int
|
Number of digit classes to include (2-10) |
10
|
n_pixels
|
Optional[int]
|
Number of pixels to keep (reduces from 64) |
32
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion of dataset for testing |
0.2
|
random_state
|
Optional[int]
|
Random seed for reproducibility |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/quantum_datasets.py
superquantx.datasets.load_breast_cancer_quantum ¶
load_breast_cancer_quantum(n_features: Optional[int] = 16, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Load and preprocess the Breast Cancer dataset for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_features
|
Optional[int]
|
Number of top features to keep |
16
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion of dataset for testing |
0.2
|
random_state
|
Optional[int]
|
Random seed for reproducibility |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/quantum_datasets.py
Synthetic Data Generators¶
superquantx.datasets.generate_classification_data ¶
generate_classification_data(n_samples: int = 200, n_features: int = 4, n_classes: int = 2, n_redundant: int = 0, n_informative: Optional[int] = None, class_sep: float = 1.0, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Generate synthetic classification data for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_samples
|
int
|
Number of samples to generate |
200
|
n_features
|
int
|
Number of features (should be power of 2 for quantum efficiency) |
4
|
n_classes
|
int
|
Number of classes |
2
|
n_redundant
|
int
|
Number of redundant features |
0
|
n_informative
|
Optional[int]
|
Number of informative features (default: n_features) |
None
|
class_sep
|
float
|
Class separation factor |
1.0
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion for test split |
0.2
|
random_state
|
Optional[int]
|
Random seed |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/synthetic.py
superquantx.datasets.generate_regression_data ¶
generate_regression_data(n_samples: int = 200, n_features: int = 4, n_informative: Optional[int] = None, noise: float = 0.1, encoding: str = 'amplitude', normalize: bool = True, test_size: float = 0.2, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Generate synthetic regression data for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_samples
|
int
|
Number of samples to generate |
200
|
n_features
|
int
|
Number of features |
4
|
n_informative
|
Optional[int]
|
Number of informative features |
None
|
noise
|
float
|
Noise level in target |
0.1
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
test_size
|
float
|
Proportion for test split |
0.2
|
random_state
|
Optional[int]
|
Random seed |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X_train, X_test, y_train, y_test, metadata) |
Source code in src/superquantx/datasets/synthetic.py
superquantx.datasets.generate_clustering_data ¶
generate_clustering_data(n_samples: int = 200, n_features: int = 4, n_clusters: int = 3, cluster_std: float = 1.0, center_box: Tuple[float, float] = (-10.0, 10.0), encoding: str = 'amplitude', normalize: bool = True, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, Dict[str, Any]]
Generate synthetic clustering data for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_samples
|
int
|
Number of samples to generate |
200
|
n_features
|
int
|
Number of features |
4
|
n_clusters
|
int
|
Number of clusters |
3
|
cluster_std
|
float
|
Standard deviation of clusters |
1.0
|
center_box
|
Tuple[float, float]
|
Bounding box for cluster centers |
(-10.0, 10.0)
|
encoding
|
str
|
Type of quantum encoding |
'amplitude'
|
normalize
|
bool
|
Whether to normalize features |
True
|
random_state
|
Optional[int]
|
Random seed |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, Dict[str, Any]]
|
Tuple of (X, y_true, metadata) |
Source code in src/superquantx/datasets/synthetic.py
superquantx.datasets.generate_portfolio_data ¶
generate_portfolio_data(n_assets: int = 8, n_scenarios: int = 100, risk_level: float = 0.2, correlation: float = 0.3, normalize: bool = True, random_state: Optional[int] = 42) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]
Generate synthetic portfolio optimization data for quantum finance algorithms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_assets
|
int
|
Number of assets in portfolio |
8
|
n_scenarios
|
int
|
Number of return scenarios |
100
|
risk_level
|
float
|
Overall risk level (volatility) |
0.2
|
correlation
|
float
|
Average correlation between assets |
0.3
|
normalize
|
bool
|
Whether to normalize returns |
True
|
random_state
|
Optional[int]
|
Random seed |
42
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, ndarray, ndarray, Dict[str, Any]]
|
Tuple of (returns, covariance_matrix, expected_returns, metadata) |
Source code in src/superquantx/datasets/synthetic.py
Molecular Datasets¶
superquantx.datasets.load_molecule ¶
load_molecule(name: str, bond_length: Optional[float] = None, basis: str = 'sto-3g') -> Tuple[Molecule, Dict[str, Any]]
Load a predefined molecule for quantum simulation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Molecule name ('H2', 'LiH', 'BeH2', 'H2O', 'NH3', 'CH4') |
required |
bond_length
|
Optional[float]
|
Custom bond length (if applicable) |
None
|
basis
|
str
|
Basis set for quantum chemistry calculations |
'sto-3g'
|
Returns:
Type | Description |
---|---|
Tuple[Molecule, Dict[str, Any]]
|
Tuple of (molecule, metadata) |
Source code in src/superquantx/datasets/molecular.py
superquantx.datasets.load_h2_molecule ¶
load_h2_molecule(bond_length: float = 0.735, basis: str = 'sto-3g') -> Tuple[Molecule, Dict[str, Any]]
Load H2 molecule with specified bond length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bond_length
|
float
|
H-H bond length in Angstroms |
0.735
|
basis
|
str
|
Basis set |
'sto-3g'
|
Returns:
Type | Description |
---|---|
Tuple[Molecule, Dict[str, Any]]
|
Tuple of (molecule, metadata) |
Source code in src/superquantx/datasets/molecular.py
superquantx.datasets.load_lih_molecule ¶
load_lih_molecule(bond_length: float = 1.595, basis: str = 'sto-3g') -> Tuple[Molecule, Dict[str, Any]]
Load LiH molecule with specified bond length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bond_length
|
float
|
Li-H bond length in Angstroms |
1.595
|
basis
|
str
|
Basis set |
'sto-3g'
|
Returns:
Type | Description |
---|---|
Tuple[Molecule, Dict[str, Any]]
|
Tuple of (molecule, metadata) |
Source code in src/superquantx/datasets/molecular.py
superquantx.datasets.load_beh2_molecule ¶
load_beh2_molecule(bond_length: float = 1.326, basis: str = 'sto-3g') -> Tuple[Molecule, Dict[str, Any]]
Load BeH2 molecule with specified bond length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bond_length
|
float
|
Be-H bond length in Angstroms |
1.326
|
basis
|
str
|
Basis set |
'sto-3g'
|
Returns:
Type | Description |
---|---|
Tuple[Molecule, Dict[str, Any]]
|
Tuple of (molecule, metadata) |
Source code in src/superquantx/datasets/molecular.py
Data Preprocessing¶
superquantx.datasets.QuantumFeatureEncoder ¶
superquantx.datasets.AmplitudeEncoder ¶
Bases: QuantumFeatureEncoder
Amplitude encoding for quantum machine learning.
Encodes classical data as amplitudes of quantum states. Each data point becomes a quantum state |ψ⟩ = Σᵢ xᵢ|i⟩.
The data is normalized so that ||x||₂ = 1 for proper quantum state encoding.
Source code in src/superquantx/datasets/preprocessing.py
Functions¶
fit ¶
Fit the amplitude encoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Training data of shape (n_samples, n_features) |
required |
Returns:
Type | Description |
---|---|
AmplitudeEncoder
|
Self for method chaining |
Source code in src/superquantx/datasets/preprocessing.py
transform ¶
Transform data using amplitude encoding.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Data to transform of shape (n_samples, n_features) |
required |
Returns:
Type | Description |
---|---|
ndarray
|
Transformed data with proper normalization |
Source code in src/superquantx/datasets/preprocessing.py
superquantx.datasets.AngleEncoder ¶
Bases: QuantumFeatureEncoder
Angle encoding for quantum machine learning.
Encodes classical features as rotation angles in quantum circuits. Each feature xᵢ becomes a rotation angle, typically in [0, 2π].
Source code in src/superquantx/datasets/preprocessing.py
Functions¶
fit ¶
Fit the angle encoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Training data of shape (n_samples, n_features) |
required |
Returns:
Type | Description |
---|---|
AngleEncoder
|
Self for method chaining |
Source code in src/superquantx/datasets/preprocessing.py
transform ¶
Transform data using angle encoding.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Data to transform of shape (n_samples, n_features) |
required |
Returns:
Type | Description |
---|---|
ndarray
|
Data scaled to angle range |
Source code in src/superquantx/datasets/preprocessing.py
superquantx.datasets.normalize_quantum_data ¶
normalize_quantum_data(X: ndarray, method: Literal['l1', 'l2', 'max'] = 'l2', axis: int = 1) -> np.ndarray
Normalize data for quantum machine learning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
ndarray
|
Data to normalize of shape (n_samples, n_features) |
required |
method
|
Literal['l1', 'l2', 'max']
|
Normalization method ('l1', 'l2', or 'max') |
'l2'
|
axis
|
int
|
Axis along which to normalize (1 for samples, 0 for features) |
1
|
Returns:
Type | Description |
---|---|
ndarray
|
Normalized data |
Source code in src/superquantx/datasets/preprocessing.py
Command Line Interface¶
Main CLI Application¶
superquantx.cli.main ¶
Main CLI entry point for SuperQuantX.
This module provides the main CLI application using Click framework, with subcommands for various quantum machine learning operations.
Functions¶
cli ¶
SuperQuantX: Building the Foundation for Quantum Agentic AI
Deploy quantum-enhanced autonomous agents and AI systems in minutes. From quantum circuits to intelligent agents across all quantum platforms.
Examples:
sqx create-agent trading # Deploy quantum trading agent sqx run automl --data portfolio # Quantum AutoML optimization sqx run qsvm --data iris # Traditional quantum algorithm sqx benchmark quantum-vs-classical # Performance comparison sqx benchmark --backend all # Benchmark all backends
Source code in src/superquantx/cli/main.py
version ¶
Show detailed version information.
Source code in src/superquantx/cli/main.py
shell ¶
Start interactive SuperQuantX shell.
Source code in src/superquantx/cli/main.py
examples ¶
Generate example scripts and notebooks.
Source code in src/superquantx/cli/main.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
|
create_app ¶
main ¶
Main entry point for the CLI.
superquantx.cli.create_app ¶
CLI Commands¶
superquantx.cli.run_algorithm ¶
run_algorithm(algorithm: str, data: str, backend: str, output: str | None, config_file: str | None, verbose: bool)
Run a quantum algorithm on specified dataset.
Source code in src/superquantx/cli/commands.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 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 |
|
superquantx.cli.list_algorithms ¶
List available quantum algorithms.
Source code in src/superquantx/cli/commands.py
superquantx.cli.list_backends ¶
List quantum computing backends.
Source code in src/superquantx/cli/commands.py
superquantx.cli.benchmark ¶
Benchmark algorithms across datasets and backends.
Source code in src/superquantx/cli/commands.py
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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
|
superquantx.cli.configure ¶
Configure SuperQuantX settings.
Source code in src/superquantx/cli/commands.py
superquantx.cli.info ¶
Show system and backend information.
Source code in src/superquantx/cli/commands.py
Usage Examples¶
Optimization Workflow¶
import superquantx as sqx
import numpy as np
# Create parameterized circuit
backend = sqx.get_backend('simulator')
circuit = backend.create_circuit(4)
# Add parameterized gates
params = sqx.Parameter('theta', shape=(8,))
for i in range(4):
circuit = backend.add_gate(circuit, 'ry', i, [params[i]])
for i in range(3):
circuit = backend.add_gate(circuit, 'cx', [i, i+1])
for i in range(4):
circuit = backend.add_gate(circuit, 'ry', i, [params[i+4]])
# Define cost function
def cost_function(parameters):
bound_circuit = circuit.bind_parameters({params: parameters})
result = backend.execute_circuit(bound_circuit)
# Calculate some cost based on measurement results
counts = result['counts']
return -sum(int(bitstring, 2) * count for bitstring, count in counts.items())
# Optimize parameters
from superquantx.utils import optimize_parameters, adam_optimizer
optimal_params = optimize_parameters(
cost_function=cost_function,
initial_params=np.random.random(8) * 2 * np.pi,
optimizer=adam_optimizer(learning_rate=0.01),
max_iterations=100
)
print(f"Optimal parameters: {optimal_params}")
Visualization Example¶
from superquantx.utils import visualize_results, plot_optimization_history
# Execute circuit with optimal parameters
final_circuit = circuit.bind_parameters({params: optimal_params})
result = backend.execute_circuit(final_circuit, shots=1000)
# Visualize measurement results
fig = visualize_results(
result['counts'],
title='Optimized Circuit Results',
plot_type='histogram'
)
fig.show()
# Plot optimization history
history = {
'iteration': list(range(100)),
'cost': [cost_function(p) for p in optimization_history],
'gradient_norm': [np.linalg.norm(g) for g in gradient_history]
}
plot_optimization_history(history, metrics=['cost', 'gradient_norm'])
Benchmarking Example¶
from superquantx.utils import benchmark_algorithm, compare_algorithms
# Define test problem
def test_classification_problem():
X, y = sqx.datasets.load_iris_quantum()
return X[:100], y[:100] # Use subset for faster benchmarking
# Benchmark single algorithm
qsvm_metrics = benchmark_algorithm(
algorithm_class=sqx.QuantumSVM,
problem_generator=test_classification_problem,
backend='simulator',
n_trials=5,
metrics=['accuracy', 'training_time', 'inference_time']
)
print("QSVM Benchmarks:")
for metric, value in qsvm_metrics.items():
print(f" {metric}: {value:.4f} ± {qsvm_metrics[f'{metric}_std']:.4f}")
# Compare multiple algorithms
algorithms = {
'QSVM': sqx.QuantumSVM,
'QNN': sqx.QuantumNN,
'Hybrid': sqx.HybridClassifier
}
comparison = compare_algorithms(
algorithms=algorithms,
problem_generator=test_classification_problem,
backend='simulator',
n_trials=3
)
# Print comparison table
print("\nAlgorithm Comparison:")
print("Algorithm | Accuracy | Training Time | Inference Time")
print("-" * 50)
for algo_name, metrics in comparison.items():
print(f"{algo_name:9} | {metrics['accuracy']:.3f} | {metrics['training_time']:.3f}s | {metrics['inference_time']:.3f}s")
Feature Mapping Example¶
from superquantx.utils import QuantumFeatureMap, zz_feature_map
# Create custom feature map
feature_map = QuantumFeatureMap(
feature_dimension=4,
reps=2,
entanglement='linear',
rotation_gates=['ry', 'rz']
)
# Sample data
X = np.random.random((10, 4))
# Encode data into quantum circuits
encoded_circuits = []
for x in X:
circuit = feature_map.encode(x, backend=backend)
encoded_circuits.append(circuit)
# Pre-built ZZ feature map
zz_map = zz_feature_map(feature_dimension=4, reps=2)
zz_circuit = zz_map.encode(X[0], backend=backend)
# Calculate quantum kernel matrix
def quantum_kernel(x1, x2, feature_map, backend):
"""Calculate quantum kernel between two data points."""
circuit1 = feature_map.encode(x1, backend)
circuit2 = feature_map.encode(x2, backend)
# Create kernel circuit: |0⟩ -> U†(x2) U(x1) |0⟩
kernel_circuit = circuit1.compose(circuit2.inverse())
# Measure overlap
result = backend.execute_circuit(kernel_circuit)
prob_zero = result['counts'].get('0' * kernel_circuit.n_qubits, 0) / sum(result['counts'].values())
return prob_zero
# Compute kernel matrix
kernel_matrix = np.zeros((len(X), len(X)))
for i in range(len(X)):
for j in range(i, len(X)):
kernel_val = quantum_kernel(X[i], X[j], feature_map, backend)
kernel_matrix[i, j] = kernel_val
kernel_matrix[j, i] = kernel_val
print(f"Quantum kernel matrix shape: {kernel_matrix.shape}")
Dataset Usage Example¶
# Load quantum-adapted datasets
X_iris, y_iris = sqx.datasets.load_iris_quantum()
X_wine, y_wine = sqx.datasets.load_wine_quantum()
print(f"Iris dataset: {X_iris.shape} features, {len(set(y_iris))} classes")
print(f"Wine dataset: {X_wine.shape} features, {len(set(y_wine))} classes")
# Generate synthetic data
X_synthetic, y_synthetic = sqx.datasets.generate_classification_data(
n_samples=200,
n_features=4,
n_classes=3,
n_informative=3,
n_clusters_per_class=1,
random_state=42
)
# Portfolio data for financial applications
portfolio_data = sqx.datasets.generate_portfolio_data(
n_assets=10,
n_time_periods=100,
correlation_structure='block',
volatility_regime='changing'
)
print(f"Portfolio returns shape: {portfolio_data['returns'].shape}")
print(f"Risk factors: {list(portfolio_data['risk_factors'].keys())}")
# Molecular datasets for quantum chemistry
h2_data = sqx.datasets.load_h2_molecule(bond_length=0.735)
print(f"H2 molecule: {h2_data['n_qubits']} qubits, {h2_data['n_orbitals']} orbitals")
print(f"Ground state energy: {h2_data['ground_energy']:.6f} Ha")
Data Preprocessing Example¶
from superquantx.datasets import QuantumFeatureEncoder, AmplitudeEncoder, AngleEncoder
# Amplitude encoding
amplitude_encoder = AmplitudeEncoder()
X_normalized = amplitude_encoder.fit_transform(X_iris)
print(f"Original range: [{X_iris.min():.3f}, {X_iris.max():.3f}]")
print(f"Encoded range: [{X_normalized.min():.3f}, {X_normalized.max():.3f}]")
# Angle encoding
angle_encoder = AngleEncoder(encoding_type='linear')
X_angles = angle_encoder.fit_transform(X_iris)
print(f"Angle encoding shape: {X_angles.shape}")
print(f"Angle range: [{X_angles.min():.3f}, {X_angles.max():.3f}]")
# Quantum feature encoding with dimensionality reduction
quantum_encoder = QuantumFeatureEncoder(
target_dimension=8, # Reduce to 8 features for quantum circuit
encoding_method='pca',
normalization='standard'
)
X_quantum = quantum_encoder.fit_transform(X_iris)
print(f"Quantum encoding: {X_iris.shape} -> {X_quantum.shape}")
Command Line Usage¶
# List available algorithms
superquantx list-algorithms
# List available backends
superquantx list-backends
# Run algorithm from command line
superquantx run-algorithm QSVM \
--data iris \
--backend simulator \
--feature-map ZZFeatureMap \
--shots 1000 \
--output results.json
# Benchmark algorithms
superquantx benchmark \
--algorithms QSVM,QNN,HybridClassifier \
--dataset wine \
--backend simulator \
--trials 5 \
--output benchmark_results.csv
# Configure SuperQuantX
superquantx configure \
--backend-preference "pennylane,qiskit,simulator" \
--default-shots 1024 \
--optimization-level 2
# Get system information
superquantx info --backends --versions --capabilities
Quantum Information Analysis¶
from superquantx.utils import fidelity, trace_distance, entanglement_measure
# Create two quantum states
backend = sqx.get_backend('simulator')
# Bell state
bell_circuit = backend.create_circuit(2)
bell_circuit = backend.add_gate(bell_circuit, 'h', 0)
bell_circuit = backend.add_gate(bell_circuit, 'cx', [0, 1])
bell_state = backend.get_statevector(bell_circuit)
# Random state
random_circuit = backend.create_circuit(2)
random_circuit = backend.add_gate(random_circuit, 'ry', 0, [np.pi/3])
random_circuit = backend.add_gate(random_circuit, 'rz', 1, [np.pi/4])
random_state = backend.get_statevector(random_circuit)
# Calculate quantum information measures
state_fidelity = fidelity(bell_state, random_state)
trace_dist = trace_distance(bell_state, random_state)
entanglement = entanglement_measure(bell_state)
print(f"Fidelity: {state_fidelity:.4f}")
print(f"Trace distance: {trace_dist:.4f}")
print(f"Entanglement (Bell state): {entanglement:.4f}")
Best Practices¶
Optimization Guidelines¶
- Start Simple: Begin with basic optimizers before advanced methods
- Monitor Convergence: Track optimization metrics throughout training
- Parameter Initialization: Use informed initial parameter guesses
- Early Stopping: Implement convergence criteria to avoid overfitting
Visualization Standards¶
- Consistent Styling: Use consistent color schemes and layouts
- Clear Labels: Always include axis labels and titles
- Error Bars: Show confidence intervals when appropriate
- Interactive Plots: Use interactive visualizations for complex data
Benchmarking Protocol¶
- Multiple Trials: Run multiple independent trials for statistical significance
- Controlled Environment: Fix random seeds for reproducible results
- Baseline Comparison: Always compare against classical baselines
- Resource Tracking: Monitor computational resources (time, memory, shots)
Data Handling¶
- Preprocessing: Always preprocess data appropriately for quantum algorithms
- Validation: Use proper train/validation/test splits
- Feature Scaling: Normalize features to appropriate ranges
- Dimensionality: Consider quantum-appropriate feature dimensions
For additional examples and advanced usage patterns, see: - Optimization Tutorial - Visualization Guide - Benchmarking Best Practices - Data Preprocessing Guide