diff --git a/CHANGELOG.md b/CHANGELOG.md index d849c97..88f375e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +Demo-readiness release: every result is computed, and every result is +checked against a classical reference. + +### Added +- `compare_to_classical` and `ComparisonResult`: benchmark any quantum + classifier against a tuned RBF SVM and logistic regression on identical + folds, with equal tuning budgets, per-fold preprocessing, hardware circuit + counts and the Nadeau-Bengio corrected t-test (protocol of arXiv:2610.42029). +- `QAOA.solve(adjacency)` for MaxCut with brute-force optimum and + approximation ratio; `brute_force_maxcut` and `cut_value` helpers. +- Built-in H2 (STO-3G, 0.735 Angstrom) Hamiltonian; VQE reports the exact + ground energy. +- `QuantumPortfolioAgent` using CVaR-VQE (Barkoutsos et al. 2020), checked + against brute-force selection and a Markowitz reference. +- `ZFeatureMap`. +- `examples/showcase.py` and `docs/showcase.md` with real output. +- `superquantx benchmark` runs `compare_to_classical`. +- Documentation: benchmarking guide, FAQ, troubleshooting, "What works today" + backend table. + +### Changed +- All six gate-model backends (simulator, PennyLane, Qiskit, Cirq, Braket + local, pytket) run real circuits; bit order is normalised to big-endian. +- Fidelity kernels use the requested feature map on every backend and give + K(x, x) = 1. +- `QuantumSVM(gamma=...)` is the kernel bandwidth. +- `QuantumNN` trains with parameter-shift gradients and a softmax readout. +- Agents rewritten around real computation; unsupported agent features + raise `NotImplementedError` instead of returning made-up numbers. +- `superquantx list-backends` runs a Bell circuit per backend; versions are + read with `importlib.metadata`. +- Qiskit floor raised; `pytest-asyncio` added to the dev extra. + +### Removed +- Random and RBF fallbacks that silently replaced quantum results. +- Dead `src/superquantx/algorithms.py` (shadowed by the `algorithms` package). +- Interactive `input()` prompts from examples. +- Claims of quantum reinforcement learning, NLP and computer vision support. + +### Fixed +- The library no longer configures the root logger on import. +- CLI `version` crash, `braket.__version__` crash, literal `\n` output and + help examples that used a nonexistent `sqx` command. + ### Planned -- Quantum reinforcement learning algorithms -- Quantum natural language processing -- Fault-tolerant quantum algorithms -- Quantum federated learning +- Azure Quantum, Rigetti Forest (pyQuil), NVIDIA cuQuantum and TensorFlow + Quantum backends. These are not implemented yet. ## [0.2.0] - 2026-09-04 diff --git a/README.md b/README.md index e7cd222..b76832f 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,22 @@ [![PyPI - Version](https://img.shields.io/pypi/v/superquantx)](https://pypi.org/project/superquantx/) [![Python Version](https://img.shields.io/pypi/pyversions/superquantx)](https://pypi.org/project/superquantx/) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -[![Tests](https://github.com/SuperagenticAI/superquantx/workflows/Tests/badge.svg)](https://github.com/SuperagenticAI/superquantx/actions) +[![Tests](https://github.com/SuperagenticAI/superquantx/actions/workflows/ci.yml/badge.svg)](https://github.com/SuperagenticAI/superquantx/actions/workflows/ci.yml) [![Documentation](https://img.shields.io/badge/docs-mkdocs-blue)](https://superagenticai.github.io/superquantx) -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) # SuperQuantX -### The foundation for the future of Agentic and Quantum AI -SuperQuantX unified API for the next wave of Quantum AI. It's a foundation to build powerful Quantum Agentic AI systems with a single interface to Qiskit, Cirq, PennyLane, and more. SuperQuantX is your launchpad into the world of Quantum + Agentic AI. -**Unified Quantum Computing Platform - Building autonomous quantum-enhanced AI systems** +**One API across quantum SDKs, with a classical baseline for every result.** -> ๐Ÿ“– **[Read the Full Documentation โ†’](https://superagenticai.github.io/superquantx/)** +SuperQuantX is an experimental, open-source toolkit for quantum machine +learning and optimisation research by [Superagentic AI](https://super-agentic.ai). +The same circuits and algorithms run on PennyLane, Qiskit, Cirq, Amazon +Braket, pytket and a built-in simulator, and every algorithm reports a +classical reference so you can see whether the quantum part earns its keep. -**Research by [Superagentic AI](https://super-agentic.ai) - Quantum AI Research** - -## ๐Ÿš€ What is SuperQuantX? - -SuperQuantX is a **unified quantum computing platform** that makes quantum algorithms and quantum machine learning accessible through a single, consistent API. Whether you're a researcher, developer, or quantum enthusiast, SuperQuantX provides: - -- **๐ŸŽฏ Single API** - Works across all major quantum backends (IBM, Google, AWS, Quantinuum, D-Wave) -- **๐Ÿค– Quantum Agents** - Pre-built autonomous agents for trading, research, and optimization -- **๐Ÿง  Quantum ML** - Advanced quantum machine learning algorithms and neural networks -- **โšก Easy Setup** - Get started in minutes with comprehensive documentation +> ๐Ÿ“– **[Documentation](https://superagenticai.github.io/superquantx/)** ยท +> ๐ŸŽฌ **[Showcase with real output](docs/showcase.md)**
@@ -31,228 +24,141 @@ SuperQuantX is a **unified quantum computing platform** that makes quantum algor
-## โœจ Key Features - -### **๐Ÿ”— Universal Quantum Backend Support** -```python -# Same code works on ANY quantum platform -qsvm = sqx.QuantumSVM(backend='pennylane') # PennyLane -qsvm = sqx.QuantumSVM(backend='qiskit') # IBM Qiskit -qsvm = sqx.QuantumSVM(backend='cirq') # Google Cirq -qsvm = sqx.QuantumSVM(backend='braket') # AWS Braket -qsvm = sqx.QuantumSVM(backend='quantinuum') # Quantinuum H-Series -``` - -### **๐Ÿค– Autonomous Quantum Agents** -Ready-to-deploy intelligent agents powered by quantum algorithms: -- **QuantumTradingAgent** - Portfolio optimization and risk analysis -- **QuantumResearchAgent** - Scientific hypothesis generation and testing -- **QuantumOptimizationAgent** - Complex combinatorial and continuous optimization -- **QuantumClassificationAgent** - Advanced ML with quantum advantage +> **Research software.** Everything below runs on classically simulated +> quantum circuits. Nothing here demonstrates quantum advantage, and the +> library is designed to tell you when a quantum model does not beat a +> classical one. + +## What works today + +| Backend | Runs on | Status | +|---------|---------|--------| +| `simulator` | built-in NumPy statevector | โœ… tested | +| `pennylane` | `default.qubit` | โœ… tested | +| `qiskit` | Qiskit Aer | โœ… tested | +| `cirq` | Cirq simulator | โœ… tested | +| `braket` | Amazon Braket `LocalSimulator` | โœ… tested | +| `tket` | pytket local simulator | โœ… tested | +| `ocean` | D-Wave Ocean (QUBO/Ising only) | โš ๏ธ annealing only, hardware needs a Leap token | +| IBM Quantum, Braket devices (IonQ, Rigetti), Quantinuum H-Series | via `qiskit`, `braket`, `tket` | โš ๏ธ untested, needs your own credentials | +| Azure Quantum, Rigetti Forest, cuQuantum, TensorFlow Quantum | | ๐Ÿšง planned, not implemented | + +"Tested" means the unit tests run a Bell state, a qubit-order check, exact +expectation values and the fidelity kernel on that backend. Check your own +install with `superquantx list-backends`. + +| Algorithm | Classical check it reports | +|-----------|----------------------------| +| `VQE` (RealAmplitudes, EfficientSU2) | exact ground energy (H2 STO-3G built in) | +| `QAOA` for MaxCut | brute-force optimum and approximation ratio | +| `QuantumSVM` (fidelity kernel) | tuned RBF SVM and logistic regression via `compare_to_classical` | +| `QuantumNN` (parameter-shift gradients) | `compare_to_classical` works with any sklearn-style classifier | +| `QuantumPortfolioAgent` (CVaR-VQE) | brute-force optimal selection and a Markowitz reference | +| `QuantumClassificationAgent` | `compare_to_classical` verdict and p-value | + +## Quick start -### **๐Ÿง  Quantum Machine Learning** -State-of-the-art quantum ML algorithms: -- **Quantum Support Vector Machines** - Enhanced pattern recognition -- **Quantum Neural Networks** - Hybrid quantum-classical architectures -- **QAOA & VQE** - Optimization and molecular simulation -- **Quantum Clustering** - Advanced data analysis techniques - -## ๐Ÿš€ Quick Start - -### Installation ```bash -# Install with uv (recommended) -curl -LsSf https://astral.sh/uv/install.sh | sh git clone https://github.com/SuperagenticAI/superquantx.git cd superquantx -uv sync --extra all +uv sync --extra all-backends # or: pip install -e ".[all-backends]" -# Or with pip -pip install superquantx +uv run superquantx list-backends # Bell-state check on every backend +uv run python examples/showcase.py ``` -### Deploy Your First Quantum Agent -```python -import superquantx as sqx +The PyPI release (`pip install superquantx`) lags behind `main`; install +from source for the behaviour described here. -# Deploy quantum trading agent -agent = sqx.QuantumTradingAgent( - strategy="quantum_portfolio", - risk_tolerance=0.3 -) -results = agent.deploy() -print(f"Performance: {results.result['performance']}") -``` +### A quantum classifier, honestly benchmarked -### Quantum Machine Learning ```python -# Quantum SVM with automatic backend selection -import numpy as np -qsvm = sqx.QuantumSVM(backend='auto') - -# Mock training data for demonstration -X_train = np.random.rand(20, 4) -y_train = np.random.choice([0, 1], 20) -X_test = np.random.rand(10, 4) -y_test = np.random.choice([0, 1], 10) +import superquantx as sqx +from sklearn.datasets import make_moons -qsvm.fit(X_train, y_train) -accuracy = qsvm.score(X_test, y_test) -print(f"Quantum SVM accuracy: {accuracy}") +X, y = make_moons(n_samples=100, noise=0.2, random_state=0) +result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend="pennylane"), cv=5) +print(result.table()) ``` -### Advanced Quantum Algorithms -```python -# Molecular simulation with VQE -import numpy as np -from sklearn.datasets import make_classification - -# Create sample Hamiltonian for VQE -hamiltonian = np.array([[1, 0], [0, -1]]) # Simple Pauli-Z -vqe = sqx.VQE(hamiltonian=hamiltonian, backend="pennylane") -ground_state = vqe.find_ground_state() -print(f"Ground state energy: {ground_state}") - -# Optimization with QAOA -X, y = make_classification(n_samples=10, n_features=4, n_classes=2, random_state=42) -qaoa = sqx.QAOA(backend="pennylane") -qaoa.fit(X, y) -print("โœ… QAOA successfully fitted for optimization tasks") +```text +model accuracy wall time grid QPU circuits +---------------------------------------------------------------------------------- +QuantumSVM (PennyLane), tuned 0.930 +/- 0.051 3.43s 25 119,000 +QuantumSVM (PennyLane), untuned 0.670 +/- 0.125 0.58s 1 - +SVC (RBF), tuned C and gamma 0.950 +/- 0.055 0.85s 25 - +Logistic regression, tuned C 0.860 +/- 0.097 0.19s 4 - +---------------------------------------------------------------------------------- +100 samples, 2 features, 5-fold stratified CV (identical folds for every model), seed=0 +quantum minus best classical: -0.020; no significant difference from SVC (RBF), tuned C and gamma (p=0.54) ``` -## ๐Ÿ“– Documentation - -**Complete documentation is available at [superagenticai.github.io/superquantx](https://superagenticai.github.io/superquantx/)** - -The documentation includes comprehensive guides for getting started, detailed API references, tutorials, and examples for all supported quantum backends. Visit the documentation site for: - -- **Getting Started** - Installation, configuration, and your first quantum program -- **User Guides** - Platform overview, backends, and algorithms -- **Tutorials** - Hands-on quantum computing and machine learning examples -- **API Reference** - Complete API documentation with examples -- **Development** - Contributing guidelines, architecture, and testing - -## ๐ŸŽฏ Supported Platforms - -SuperQuantX provides unified access to **all major quantum computing platforms**: - -| Backend | Provider | Hardware | Simulator | -|---------|----------|----------|-----------| -| **PennyLane** | Multi-vendor | โœ… Various | โœ… | -| **Qiskit** | IBM | โœ… IBM Quantum | โœ… | -| **Cirq** | Google | โœ… Google Quantum AI | โœ… | -| **AWS Braket** | Amazon | โœ… IonQ, Rigetti | โœ… | -| **TKET** | Quantinuum | โœ… H-Series | โœ… | -| **Ocean** | D-Wave | โœ… Advantage | โœ… | - -> **Python**: SuperQuantX requires **Python 3.11+**. See [backend compatibility](docs/BACKENDS.md#backend-version-compatibility) for optional-extra version floors. - -## ๐Ÿค– Quantum Agents +This follows the protocol of +[arXiv:2610.42029](https://arxiv.org/abs/2610.42029): equal tuning budgets, +identical folds, per-fold preprocessing and the Nadeau-Bengio corrected +t-test. As that paper reports, a tuned quantum kernel is statistically +indistinguishable from a tuned RBF SVM here, and bandwidth tuning (0.67 to +0.93) matters more than the circuit. See +[Benchmarking](docs/user-guide/benchmarking.md). -Pre-built autonomous agents for complex problem solving: +### VQE and QAOA with exact answers -- **๐Ÿฆ QuantumTradingAgent** - Portfolio optimization and risk analysis -- **๐Ÿ”ฌ QuantumResearchAgent** - Scientific hypothesis generation and testing -- **โšก QuantumOptimizationAgent** - Combinatorial and continuous optimization -- **๐Ÿง  QuantumClassificationAgent** - Advanced ML with quantum advantage - -## ๐Ÿงฎ Quantum Algorithms - -Comprehensive library of quantum algorithms and techniques: +```python +import numpy as np +import superquantx as sqx -### **๐Ÿ” Quantum Machine Learning** -- **Quantum Support Vector Machines (QSVM)** - Enhanced pattern recognition with quantum kernels -- **Quantum Neural Networks (QNN)** - Hybrid quantum-classical neural architectures -- **Quantum Principal Component Analysis (QPCA)** - Quantum dimensionality reduction -- **Quantum K-Means** - Clustering with quantum distance calculations +vqe = sqx.create_vqe_for_molecule("H2", backend="qiskit") +print(vqe.find_ground_state(), vqe.exact_ground_energy()) # both -1.857275 Ha -### **โšก Optimization Algorithms** -- **Quantum Approximate Optimization Algorithm (QAOA)** - Combinatorial optimization -- **Variational Quantum Eigensolver (VQE)** - Molecular simulation and optimization -- **Quantum Annealing** - Large-scale optimization with D-Wave systems +W = np.array([[0, 1, 1, 0, 1], [1, 0, 1, 1, 0], [1, 1, 0, 1, 0], + [0, 1, 1, 0, 1], [1, 0, 0, 1, 0]], dtype=float) +r = sqx.QAOA(backend="cirq", p=2, seed=7).solve(W) +print(r["cut_value"], r["classical_optimum"], r["approximation_ratio"]) +``` -### **๐Ÿง  Advanced Quantum AI** -- **Quantum Reinforcement Learning** - RL with quantum advantage -- **Quantum Natural Language Processing** - Quantum-enhanced text analysis -- **Quantum Computer Vision** - Image processing with quantum circuits +### Agents that show their work -## ๐Ÿ’ก Why SuperQuantX? +```python +import numpy as np +import superquantx as sqx -| Traditional Approach | SuperQuantX Advantage | -|--------------------|---------------------| -| โŒ Multiple complex SDKs | โœ… Single unified API | -| โŒ Months to learn quantum | โœ… Minutes to first algorithm | -| โŒ Backend-specific code | โœ… Write once, run anywhere | -| โŒ Manual optimization | โœ… Automatic backend selection | -| โŒ Limited algorithms | โœ… Comprehensive algorithm library | +returns = np.random.default_rng(0).normal(0.01, 0.02, size=(250, 6)) +res = sqx.QuantumPortfolioAgent(backend="simulator", n_select=3, seed=0).solve(returns) +print(res.result["selected_assets"], res.result["classical_selected_assets"], + res.result["matches_classical_optimum"]) +``` -## ๐Ÿค Contributing +`examples/quantum_agents_demo.py` runs the portfolio and classification +agents end to end. -We welcome contributions to SuperQuantX! Here's how to get involved: +## Command line -### **๐Ÿ”ง Development Setup** ```bash -# Fork and clone the repository -git clone https://github.com/your-username/superquantx.git -cd superquantx - -# Install development dependencies -uv sync --extra dev - -# Run tests to verify setup -uv run pytest +superquantx -v version # versions of installed backend SDKs +superquantx list-backends # real Bell-state check per backend +superquantx benchmark -d moons -b pennylane # quantum kernel vs tuned classical +superquantx run qsvm --data iris -b simulator ``` -### **๐Ÿ› Bug Reports & Feature Requests** -- **[Open an issue](https://github.com/SuperagenticAI/superquantx/issues)** - Report bugs or request features -- **[Read contributing guide](docs/development/contributing.md)** - Detailed contribution guidelines - -### **๐Ÿ“ Documentation** -Help improve our documentation: -- Fix typos and clarify explanations -- Add examples and tutorials -- Improve API documentation -- Translate documentation - -## ๐Ÿ”— Resources & Community - -### **๐Ÿ“š Learn More** -- **[Official Documentation](docs/)** - Complete guides and API reference -- **[Tutorial Notebooks](examples/)** - Jupyter notebooks with examples - - -## ๐Ÿ“„ License - -SuperQuantX is released under the [Apache License 2.0](LICENSE). Feel free to use it in your projects, research, and commercial applications. - ---- - -## ๐Ÿš€ Get Started Now +## Development ```bash -# Install SuperQuantX -pip install superquantx - -# Deploy your first quantum agent -python -c " -import superquantx as sqx -agent = sqx.QuantumOptimizationAgent() -print('โœ… SuperQuantX is ready!') -" +uv sync --extra all-backends --extra dev +uv run pytest tests/unit tests/integration +uv run ruff check src tests ``` -**Ready to explore quantum computing?** +Contributions are welcome: [open an issue](https://github.com/SuperagenticAI/superquantx/issues) +or read the [contributing guide](docs/development/contributing.md). +Python 3.11+ is required; see [backend compatibility](docs/BACKENDS.md#backend-version-compatibility) +for version floors. -๐Ÿ‘‰ **[Start with the Quick Start Guide โ†’](https://superagenticai.github.io/superquantx/)** +## License ---- +Apache License 2.0. See [LICENSE](LICENSE).
-**SuperQuantX: Making Quantum Computing Accessible to all** - -*Built with โค๏ธ by [Superagentic AI](https://super-agentic.ai)* - -โญ **Star this repo** if SuperQuantX helps your quantum journey! +*Built by [Superagentic AI](https://super-agentic.ai)*
diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index ed3d0df..ea6e6fd 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -1,5 +1,9 @@ # SuperQuantX Backend Documentation +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 2 of 13 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](getting-started/quickstart.md), the [Showcase](showcase.md) and the [Backends guide](user-guide/backends.md). + + ## Overview SuperQuantX provides a unified API that works across all major quantum computing platforms. This documentation covers all supported backends and their specific features. diff --git a/docs/api/agents.md b/docs/api/agents.md index e1087f8..3747b9d 100644 --- a/docs/api/agents.md +++ b/docs/api/agents.md @@ -1,5 +1,9 @@ # Quantum Agents API Reference +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 4 of 23 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + SuperQuantX's quantum agents represent the next evolution of AI - autonomous systems that leverage quantum computing to achieve enhanced performance in specialized domains. This reference documents all quantum agent classes and their capabilities. ## Overview diff --git a/docs/api/algorithms.md b/docs/api/algorithms.md index 3cf93b4..741cbcc 100644 --- a/docs/api/algorithms.md +++ b/docs/api/algorithms.md @@ -1,5 +1,9 @@ # Algorithms API Reference +!!! warning "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](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + 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 diff --git a/docs/api/backends.md b/docs/api/backends.md index e8212c2..134ac32 100644 --- a/docs/api/backends.md +++ b/docs/api/backends.md @@ -1,5 +1,9 @@ # Backends API Reference +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 4 of 13 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + SuperQuantX provides a unified interface to multiple quantum computing backends, enabling seamless switching between simulators and real quantum hardware from different providers. ## Base Classes diff --git a/docs/api/circuits.md b/docs/api/circuits.md index c3c64ea..febe37f 100644 --- a/docs/api/circuits.md +++ b/docs/api/circuits.md @@ -1,5 +1,9 @@ # Circuits API Reference +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 0 of 13 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + SuperQuantX provides comprehensive quantum circuit construction, manipulation, and execution capabilities. This API reference covers quantum circuits, gates, measurements, and noise modeling. ## Quantum Circuits @@ -539,6 +543,5 @@ print(f"Average execution time: {avg_execution_time:.3f}s") --- For more detailed examples and tutorials, see: -- [Circuit Construction Tutorial](../tutorials/circuits.md) -- [Noise Modeling Guide](../user-guide/noise.md) +- [Circuit Construction Tutorial](../tutorials/basic-quantum.md) - [Backend Integration](../backends/) \ No newline at end of file diff --git a/docs/api/core.md b/docs/api/core.md index c865bae..6b782cb 100644 --- a/docs/api/core.md +++ b/docs/api/core.md @@ -1,5 +1,9 @@ # Core API Reference +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 5 of 15 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + The core API provides fundamental functionality for SuperQuantX, including backend management, configuration, and system information. ## Package-Level Functions diff --git a/docs/api/utilities.md b/docs/api/utilities.md index 0bb71aa..ff15260 100644 --- a/docs/api/utilities.md +++ b/docs/api/utilities.md @@ -1,5 +1,9 @@ # Utilities API Reference +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 0 of 7 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + 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 @@ -683,7 +687,5 @@ print(f"Entanglement (Bell state): {entanglement:.4f}") --- For additional examples and advanced usage patterns, see: -- [Optimization Tutorial](../tutorials/optimization.md) -- [Visualization Guide](../user-guide/visualization.md) +- [Optimization Tutorial](../user-guide/algorithms.md) - [Benchmarking Best Practices](../user-guide/benchmarking.md) -- [Data Preprocessing Guide](../user-guide/data-preprocessing.md) \ No newline at end of file diff --git a/docs/backends/braket.md b/docs/backends/braket.md index 8ab6557..a72ddbd 100644 --- a/docs/backends/braket.md +++ b/docs/backends/braket.md @@ -1,5 +1,9 @@ # Amazon Braket Backend Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 7 of 14 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Amazon Braket is AWS's fully managed quantum computing service that provides access to quantum computers from multiple hardware providers. SuperQuantX integrates with Braket to enable cloud-based quantum computing with enterprise-grade security and scalability. ## Overview diff --git a/docs/backends/cirq.md b/docs/backends/cirq.md index 64c58e3..92e3c4a 100644 --- a/docs/backends/cirq.md +++ b/docs/backends/cirq.md @@ -1,5 +1,9 @@ # Cirq Backend Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 3 of 15 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Cirq is Google's open-source quantum computing framework that focuses on near-term quantum devices and NISQ algorithms. SuperQuantX integrates with Cirq to provide access to Google's quantum ecosystem and advanced circuit optimization features. ## Overview diff --git a/docs/backends/ocean.md b/docs/backends/ocean.md index 259c94b..942b803 100644 --- a/docs/backends/ocean.md +++ b/docs/backends/ocean.md @@ -1,5 +1,9 @@ # D-Wave Ocean Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 7 of 27 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + D-Wave Ocean is a suite of tools for solving optimization problems on D-Wave quantum annealing systems. Unlike gate-model quantum computers, D-Wave systems are quantum annealers designed specifically for solving optimization problems formulated as Quadratic Unconstrained Binary Optimization (QUBO) or Ising models. ## Overview diff --git a/docs/backends/pennylane.md b/docs/backends/pennylane.md index 2ba1702..2f8b981 100644 --- a/docs/backends/pennylane.md +++ b/docs/backends/pennylane.md @@ -1,5 +1,9 @@ # PennyLane Backend Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 3 of 13 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + PennyLane is a cross-platform quantum machine learning library that focuses on variational quantum circuits and quantum machine learning. SuperQuantX provides seamless integration with PennyLane for quantum ML applications. ## ๐Ÿ“‹ Overview diff --git a/docs/backends/qiskit.md b/docs/backends/qiskit.md index b7f52a8..25ac837 100644 --- a/docs/backends/qiskit.md +++ b/docs/backends/qiskit.md @@ -1,5 +1,9 @@ # Qiskit Backend Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 5 of 18 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Qiskit is IBM's open-source quantum computing framework that provides access to quantum simulators and real IBM quantum hardware. SuperQuantX integrates seamlessly with Qiskit to provide access to IBM's quantum ecosystem. ## Overview diff --git a/docs/backends/simulator.md b/docs/backends/simulator.md index 29f524d..1cca53a 100644 --- a/docs/backends/simulator.md +++ b/docs/backends/simulator.md @@ -1,5 +1,9 @@ # Python Simulator Backend +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 3 of 26 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + The Python Simulator backend provides a pure Python implementation of quantum circuit simulation that doesn't require external quantum computing libraries. This backend is ideal for testing, educational purposes, and as a fallback when other quantum backends are unavailable. ## Overview diff --git a/docs/backends/tket.md b/docs/backends/tket.md index 14e613b..a5db7ed 100644 --- a/docs/backends/tket.md +++ b/docs/backends/tket.md @@ -1,5 +1,9 @@ # TKET Integration +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 8 of 23 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + TKET (Quantum Toolkit) is a quantum SDK developed by Cambridge Quantum Computing (now part of Quantinuum) that provides powerful quantum circuit compilation, optimization, and execution capabilities. SuperQuantX provides comprehensive integration with TKET, enabling access to advanced quantum compilation techniques and Quantinuum's quantum hardware. ## Overview diff --git a/docs/development/architecture.md b/docs/development/architecture.md index 5aa6a9b..b538d9f 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -1,5 +1,9 @@ # SuperQuantX Architecture +!!! warning "Unverified examples" + Code on this page is illustrative and partly written as fragments. Only 5 of 16 snippets run as-is against the current release. The test suite in `tests/` is the source of truth. + + This document provides a comprehensive overview of SuperQuantX's architecture, design principles, and implementation details. ## ๐Ÿ—๏ธ High-Level Architecture diff --git a/docs/development/releases.md b/docs/development/releases.md index 0fb9922..e1d5fd4 100644 --- a/docs/development/releases.md +++ b/docs/development/releases.md @@ -1,5 +1,9 @@ # Release Process +!!! warning "Unverified examples" + Code on this page is illustrative and partly written as fragments. Only 2 of 4 snippets run as-is against the current release. The test suite in `tests/` is the source of truth. + + This document outlines the release process for SuperQuantX, including versioning, testing, and deployment procedures. ## ๐Ÿท๏ธ Versioning Strategy diff --git a/docs/development/standards.md b/docs/development/standards.md index d5b05f2..f081dfd 100644 --- a/docs/development/standards.md +++ b/docs/development/standards.md @@ -1,5 +1,9 @@ # Code Standards +!!! warning "Unverified examples" + Code on this page is illustrative and partly written as fragments. Only 6 of 17 snippets run as-is against the current release. The test suite in `tests/` is the source of truth. + + Comprehensive coding standards and guidelines for SuperQuantX development to ensure consistency, maintainability, and quality across the codebase. ## ๐ŸŽฏ General Principles diff --git a/docs/development/testing.md b/docs/development/testing.md index 341887d..278b003 100644 --- a/docs/development/testing.md +++ b/docs/development/testing.md @@ -1,5 +1,9 @@ # Testing Guide +!!! warning "Unverified examples" + Code on this page is illustrative and partly written as fragments. Only 7 of 9 snippets run as-is against the current release. The test suite in `tests/` is the source of truth. + + Comprehensive testing strategy for SuperQuantX to ensure reliability, correctness, and performance of quantum algorithms and backend integrations. ## ๐Ÿงช Testing Philosophy diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 7fc4c00..c1a2966 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -1,5 +1,9 @@ # Configuration Guide +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 11 of 17 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + This comprehensive guide covers how to configure SuperQuantX for your specific needs, from basic settings to advanced customizations for research and production-like environments. ## ๐ŸŽฏ Overview diff --git a/docs/getting-started/first-program.md b/docs/getting-started/first-program.md index 58959b0..b71b1a0 100644 --- a/docs/getting-started/first-program.md +++ b/docs/getting-started/first-program.md @@ -1,5 +1,9 @@ # Your First Quantum Program +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 4 of 13 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Welcome to your first quantum program with SuperQuantX! This comprehensive guide will walk you through building quantum applications from the ground up, explaining each concept along the way. ## ๐ŸŽฏ What You'll Learn @@ -460,8 +464,8 @@ Congratulations! You've built your first quantum programs. Here's what to explor ### Intermediate Topics 4. **[Quantum Machine Learning](../tutorials/quantum-ml.md)**: Apply QML algorithms -5. **[Multi-Backend Usage](../tutorials/multi-backend.md)**: Compare frameworks -6. **[Circuit Optimization](../user-guide/circuits.md)**: Efficient circuit design +5. **[Multi-Backend Usage](../user-guide/backends.md)**: Compare frameworks +6. **[Circuit Optimization](../api/circuits.md)**: Efficient circuit design ### Advanced Projects diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index d0445e2..7771a0a 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -34,8 +34,8 @@ SuperQuantX requires Python 3.11 or higher. Install it using pip: git clone https://github.com/SuperagenticAI/superquantx.git cd superquantx - # Install with development dependencies - pip install -e .[dev] + # Install every working backend plus development tools + uv sync --extra all-backends --extra dev ``` ## ๐Ÿ” Verify Installation @@ -51,10 +51,11 @@ backends = sqx.list_available_backends() print(f"Available backends: {backends}") ``` -You should see something like: -``` -SuperQuantX version: 0.1.1 -Available backends: {'simulator': {'available': True, 'class': 'SimulatorBackend', 'description': 'Pure Python quantum simulator backend.', 'capabilities': {...}}, 'pennylane': {'available': False, 'class': 'PennyLaneBackend', 'reason': 'Missing dependencies'}, ...} +You should see the version and a dictionary describing each backend. To +actually test every installed backend with a Bell circuit, run: + +```bash +superquantx list-backends ``` ## ๐ŸŽฏ Your First Quantum Program @@ -157,9 +158,9 @@ One of SuperQuantX's superpowers is easy backend switching. Let's compare the sa import superquantx as sqx import numpy as np -# Create sample data -X = np.random.rand(50, 2) -y = np.random.randint(0, 2, 50) +# Create sample data (random labels would make any accuracy meaningless) +from sklearn.datasets import make_moons +X, y = make_moons(n_samples=50, noise=0.1, random_state=0) # List of backends to compare backends = ['simulator', 'pennylane', 'qiskit'] @@ -171,7 +172,7 @@ for backend_name in backends: print(f"\n๐Ÿ” Testing with {backend_name}...") # Create and train model - qsvm = sqx.QuantumSVM(backend=backend_name) + qsvm = sqx.QuantumSVM(backend=backend_name, gamma=0.5) qsvm.fit(X[:40], y[:40]) # Train on first 40 samples # Test accuracy @@ -180,12 +181,23 @@ for backend_name in backends: print(f"โœ… {backend_name} accuracy: {accuracy:.3f}") - except ImportError as e: + except Exception as e: print(f"โŒ {backend_name} not available: {e}") print(f"\n๐Ÿ“Š Results Summary: {results}") ``` +Every backend computes the same exact fidelity kernel, so the accuracies +should be identical. That is a correctness check, not a benchmark. To ask +whether the quantum model is any good, compare it with tuned classical models: + +```python +result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend="simulator"), cv=5) +print(result.table()) +``` + +See [Benchmarking against classical baselines](../user-guide/benchmarking.md). + ## ๐Ÿ“Š Built-in Quantum Algorithms SuperQuantX comes with several quantum algorithms ready to use: @@ -217,10 +229,10 @@ SuperQuantX comes with several quantum algorithms ready to use: # Create a simple Hamiltonian (matrix) hamiltonian = np.array([[1, 0], [0, -1]]) - # Find ground state energy + # Find ground state energy (exact answer: -1) vqe = sqx.VQE(backend='simulator', hamiltonian=hamiltonian) ground_energy = vqe.find_ground_state() - + print(f"Ground state energy: {ground_energy:.6f}") ``` @@ -230,9 +242,10 @@ SuperQuantX comes with several quantum algorithms ready to use: import superquantx as sqx import numpy as np + from sklearn.datasets import make_moons + # Create training data - X = np.random.rand(20, 2) - y = np.random.randint(0, 2, 20) + X, y = make_moons(n_samples=40, noise=0.1, random_state=0) # Build Quantum Neural Network qnn = sqx.QuantumNN( @@ -256,7 +269,7 @@ Great job! You've successfully: โœ… Installed SuperQuantX โœ… Created your first quantum circuit โœ… Ran a quantum machine learning algorithm -โœ… Visualized quantum circuits +โœ… Inspected a circuit โœ… Compared multiple backends ### Continue Your Journey: @@ -264,7 +277,7 @@ Great job! You've successfully: 1. **Learn the Fundamentals**: [Basic Quantum Computing Tutorial](../tutorials/basic-quantum.md) 2. **Explore More Algorithms**: [Quantum Algorithms Guide](../user-guide/algorithms.md) 3. **Deep Dive into Backends**: [Backend Integration Guide](../user-guide/backends.md) -4. **Try Advanced Examples**: [Advanced Tutorials](../tutorials/advanced-examples.md) +4. **Try Advanced Examples**: [Advanced Tutorials](../showcase.md) ### Need Help? diff --git a/docs/help/faq.md b/docs/help/faq.md new file mode 100644 index 0000000..b4a8eb3 --- /dev/null +++ b/docs/help/faq.md @@ -0,0 +1,30 @@ +# FAQ + +**Is SuperQuantX production software?** +No. It is a research toolkit. Everything in the [showcase](../showcase.md) +runs on local classical simulators. + +**Does it show quantum advantage?** +No, and it is built to tell you so. Every algorithm reports a classical +reference: exact diagonalisation for VQE, brute force for QAOA and the +portfolio agent, and tuned classical models for classifiers via +[`compare_to_classical`](../user-guide/benchmarking.md). + +**Which backends work?** +`simulator`, `pennylane`, `qiskit`, `cirq`, `braket` (local simulator) and +`tket` are tested. D-Wave `ocean` handles QUBO/Ising problems only. Cloud +hardware through those SDKs is untested. Azure Quantum, Rigetti Forest, +cuQuantum and TensorFlow Quantum are planned, not implemented. Run +`superquantx list-backends` to check your installation. + +**Why do all backends give the same accuracy?** +They compute the same exact statevector kernel. Identical results are a +correctness check. + +**Why is the untuned quantum kernel so weak?** +A fidelity kernel with bandwidth 1 is often too narrow or too wide for the +data. Tuning the bandwidth (the `gamma` argument of `QuantumSVM`) matters +more than the choice of feature map; see arXiv:2610.42029. + +**Does the library configure logging?** +No. It only adds a `NullHandler`. Configure logging in your application. diff --git a/docs/help/troubleshooting.md b/docs/help/troubleshooting.md new file mode 100644 index 0000000..0731a33 --- /dev/null +++ b/docs/help/troubleshooting.md @@ -0,0 +1,29 @@ +# Troubleshooting + +**A backend is missing.** +Install its extra, for example `pip install "superquantx[qiskit]"`, or all +of them with `uv sync --extra all-backends`. Then run +`superquantx list-backends`, which runs a Bell circuit on each backend and +prints the error for any that fail. + +**`braket` fails to start.** +Use the local simulator explicitly: +`sqx.get_backend("braket", device="local:braket_sv")`. Real Braket devices +need AWS credentials. + +**`ocean` raises an error for a circuit.** +D-Wave Ocean is an annealer. It solves QUBO/Ising problems and does not run +gate-model circuits. Hardware access needs a D-Wave Leap token. + +**An algorithm result has `error` set.** +`BaseQuantumAlgorithm.optimize` records exceptions on the returned +`QuantumResult.error` instead of raising. Check it before using the result. + +**Results differ in bit order between backends.** +Use `backend.counts_big_endian(result["counts"])` and +`backend.statevector_big_endian(circuit)`, which normalise every backend to +big-endian (qubit 0 is the leftmost bit). + +**Tests fail with "async def functions are not natively supported".** +Install the dev extra, which includes `pytest-asyncio`: +`uv sync --extra dev`. diff --git a/docs/index.md b/docs/index.md index 774b6c0..5cf8082 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,38 +2,50 @@

SuperQuantX

-

Unified Quantum Computing Platform

-

Building autonomous quantum-enhanced AI systems

-

A cutting-edge quantum computing research platform that provides a unified API for quantum agentic AI systems.

+

Experimental Quantum ML Toolkit

+

No hype. Checked results.

+

One API across quantum SDKs, with a classical baseline for every result.

## Welcome to SuperQuantX -SuperQuantX bridges the gap between quantum computing and artificial intelligence, enabling researchers and developers to build sophisticated quantum-enhanced AI agents with a single, unified API. +SuperQuantX is an experimental, open-source toolkit for quantum machine +learning and optimisation research. One API runs the same circuits and +algorithms on PennyLane, Qiskit, Cirq, Amazon Braket, pytket and a built-in +simulator, and every result comes with a classical reference so you can see +whether the quantum part earns its keep. -### ๐Ÿš€ Key Features +### Key features -- **๐Ÿ”— Unified API**: Single interface for multiple quantum computing backends -- **๐ŸŽฏ Agentic AI Focus**: Specialized tools for quantum agent development -- **๐Ÿš€ Multi-Backend Support**: PennyLane, Qiskit, Cirq, Amazon Braket, TKET, D-Wave Ocean -- **๐Ÿ“Š Advanced Algorithms**: Pre-built quantum machine learning and optimization algorithms -- **๐Ÿ› ๏ธ Developer Friendly**: Comprehensive documentation and examples -- **โšก High Performance**: Optimized for research and production workloads +- **One API, six gate-model backends**: identical circuits, bit order + normalised across SDKs. +- **Algorithms with built-in checks**: VQE reports the exact ground energy, + QAOA reports the brute-force optimum, classifiers can be benchmarked with + [`compare_to_classical`](user-guide/benchmarking.md). +- **Research-grade benchmarking**: equal tuning budgets, identical folds and + a corrected t-test, following [arXiv:2610.42029](https://arxiv.org/abs/2610.42029). +- **Agents that show their work**: portfolio and classification agents + return the classical optimum or baseline alongside the quantum answer.
SuperQuantX Logo
-### ๐ŸŽฏ Supported Backends +### What works today -| Backend | Provider | Features | -|---------|----------|----------| -| **PennyLane** | Multi-vendor | Differentiable programming, ML integration | -| **Qiskit** | IBM | IBM hardware, advanced transpilation | -| **Cirq** | Google | Google hardware, NISQ algorithms | -| **Amazon Braket** | AWS | AWS cloud quantum computing | -| **TKET** | Cambridge Quantum Computing | Advanced optimization | -| **D-Wave Ocean** | D-Wave | Quantum annealing | +| Backend | Status | +|---------|--------| +| Built-in simulator | tested | +| PennyLane (`default.qubit`) | tested | +| Qiskit (Aer) | tested | +| Cirq simulator | tested | +| Amazon Braket `LocalSimulator` | tested | +| pytket local simulator | tested | +| D-Wave Ocean | QUBO/Ising only | +| IBM Quantum, Braket devices, Quantinuum hardware | untested, needs your own credentials | +| Azure Quantum, Rigetti Forest, cuQuantum, TensorFlow Quantum | planned, not implemented | + +See the [Showcase](showcase.md) for real output from every tested backend. ## Quick Start @@ -98,6 +110,14 @@ Complete API documentation. - [Agents](api/agents.md) +
+### ๐Ÿ“ Results +Real output, checked against classical baselines. + +- [Showcase](showcase.md) +- [Benchmarking against classical baselines](user-guide/benchmarking.md) +
+ ## Research Areas @@ -105,10 +125,9 @@ Complete API documentation. SuperQuantX accelerates research in: - **Quantum Machine Learning**: QSVM, QNN, quantum feature maps -- **Quantum Optimization**: QAOA, VQE, quantum annealing -- **Quantum Agents**: Decision-making quantum systems -- **Hybrid Algorithms**: Classical-quantum hybrid approaches -- **NISQ Applications**: Near-term quantum device algorithms +- **Quantum Optimization**: QAOA, VQE (including CVaR-VQE), quantum annealing via D-Wave Ocean +- **Quantum Agents**: Portfolio and classification agents with classical checks +- **Honest evaluation**: Tuned classical baselines and significance tests for every quantum model ## Community & Support diff --git a/docs/showcase.md b/docs/showcase.md new file mode 100644 index 0000000..9bd0417 --- /dev/null +++ b/docs/showcase.md @@ -0,0 +1,85 @@ +# Showcase + +`examples/showcase.py` is the five-minute demo of what SuperQuantX does +today. It runs in about 10 seconds on a laptop, entirely on local +simulators, and checks every quantum result against something classical. + +```bash +uv sync --extra all-backends +uv run python examples/showcase.py +``` + +1. **Backends.** Bell and GHZ circuits on every installed gate-model + backend. Only the correct outcomes may appear. +2. **Quantum machine learning.** A quantum kernel SVM on `make_moons`, + compared with a tuned RBF SVM and logistic regression using the protocol + of [arXiv:2610.42029](https://arxiv.org/abs/2610.42029). See + [Benchmarking](user-guide/benchmarking.md). +3. **Optimisation.** QAOA on a 5-node MaxCut instance, checked against + brute force. + +## Real output + +Captured on 2 November 2026 (Python 3.11, PennyLane 0.45, Qiskit 2.6, +Cirq 1.7, Braket SDK 1.127, pytket 2.18). Timings vary by machine; shot +counts vary with sampling. + +```text +SuperQuantX 0.2.0 showcase. All runs are local classical simulations. + +1. Bell and GHZ states on every backend (1000 shots each) +========================================================= +backend Bell 00/11 GHZ 000/111 correct time +simulator 495/505 507/493 yes 0.00s +pennylane 492/508 510/490 yes 0.01s +qiskit 511/489 507/493 yes 0.19s +cirq 517/483 485/515 yes 0.01s +braket 485/515 522/478 yes 0.03s +tket 491/509 497/503 yes 0.03s +Working: simulator, pennylane, qiskit, cirq, braket, tket + +2. Quantum kernel SVM vs tuned classical models (make_moons, pennylane) +======================================================================= +model accuracy wall time grid QPU circuits +---------------------------------------------------------------------------------- +QuantumSVM (PennyLane), tuned 0.930 +/- 0.051 3.43s 25 119,000 +QuantumSVM (PennyLane), untuned 0.670 +/- 0.125 0.58s 1 - +SVC (RBF), tuned C and gamma 0.950 +/- 0.055 0.85s 25 - +Logistic regression, tuned C 0.860 +/- 0.097 0.19s 4 - +---------------------------------------------------------------------------------- +100 samples, 2 features, 5-fold stratified CV (identical folds for every model), seed=0 +quantum minus best classical: -0.020; no significant difference from SVC (RBF), tuned C and gamma (p=0.54) +Protocol: arXiv:2610.42029. Quantum kernels are classically simulated. + +3. QAOA MaxCut vs brute force (5 nodes, 7 edges, p=2, pennylane) +================================================================ +QAOA best sampled cut : 01101 value 6 +Brute-force optimum : 01101 value 6 +Expected cut of state : 5.019 (approximation ratio 0.837; a random cut averages 3.5) +Matches optimum : yes (484 circuit evaluations, 2.4s) + +Total time 7.8s +``` + +## What this shows, and what it does not + +- Six SDKs run the same circuits through one API and agree, after bit-order + normalisation. +- The tuned quantum kernel is competitive with classical models on this + dataset, but not better: the difference from a tuned RBF SVM is not + statistically significant. That matches the published evidence. + Bandwidth tuning, not the circuit, is what lifts it from 0.67 to 0.93. +- QAOA at depth 2 finds the optimal cut among its samples. Its expected cut + (approximation ratio about 0.84) is what would matter on hardware, and + brute force is instant at this size. +- None of this is quantum advantage. All circuits are classically simulated. + +## Agents demo + +`examples/quantum_agents_demo.py` runs the portfolio agent (CVaR-VQE on a +QUBO, checked against brute-force enumeration and a Markowitz reference) and +the classification agent (which wraps `compare_to_classical`). + +```bash +uv run python examples/quantum_agents_demo.py +``` diff --git a/docs/tutorials/basic-quantum.md b/docs/tutorials/basic-quantum.md index c3584c4..8bfd4f5 100644 --- a/docs/tutorials/basic-quantum.md +++ b/docs/tutorials/basic-quantum.md @@ -1,5 +1,9 @@ # Basic Quantum Computing Tutorial +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 2 of 15 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Welcome to the world of quantum computing! This tutorial will teach you the fundamentals of quantum computing using SuperQuantX. No prior quantum knowledge required - we'll build everything from the ground up. ## ๐ŸŽฏ What You'll Learn @@ -807,9 +811,9 @@ Congratulations! You've learned the fundamentals of quantum computing: ### Continue Your Quantum Journey 1. **[Quantum Machine Learning Tutorial](quantum-ml.md)** - Apply quantum computing to machine learning -2. **[Quantum Neural Networks](quantum-nn.md)** - Build deep quantum neural networks +2. **[Quantum Neural Networks](quantum-ml.md)** - Build deep quantum neural networks 3. **[Advanced Algorithms](../user-guide/algorithms.md)** - Explore more sophisticated quantum algorithms -4. **[Multi-Backend Usage](multi-backend.md)** - Compare different quantum frameworks +4. **[Multi-Backend Usage](../user-guide/backends.md)** - Compare different quantum frameworks ### Additional Resources diff --git a/docs/tutorials/quantum-ml.md b/docs/tutorials/quantum-ml.md index e0f508a..4f83983 100644 --- a/docs/tutorials/quantum-ml.md +++ b/docs/tutorials/quantum-ml.md @@ -1,5 +1,9 @@ # Quantum Machine Learning Tutorial +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 1 of 8 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](../user-guide/backends.md). + + Learn how to apply quantum computing to machine learning problems using SuperQuantX. This tutorial covers the fundamentals of quantum machine learning (QML) and provides hands-on examples you can run today. ## ๐ŸŽฏ Learning Objectives @@ -1194,7 +1198,7 @@ You've now mastered the fundamentals of quantum machine learning! Here's what yo ### Advanced QML Topics -1. **[Quantum Neural Networks Tutorial](quantum-nn.md)** - Deep dive into advanced QNN architectures +1. **[Quantum Neural Networks Tutorial](../user-guide/algorithms.md)** - Deep dive into advanced QNN architectures 2. **Quantum Generative Models** - QGANs, QVAEs, and quantum generative modeling 3. **Quantum Reinforcement Learning** - QL algorithms and quantum environments 4. **Quantum Natural Language Processing** - Applying QML to text and language tasks @@ -1215,7 +1219,7 @@ You've now mastered the fundamentals of quantum machine learning! Here's what yo ## ๐Ÿค Need Help? -- **[Advanced Examples](advanced-examples.md)** - More complex QML implementations +- **[Advanced Examples](../showcase.md)** - More complex QML implementations - **[API Reference](../api/algorithms.md)** - Detailed documentation - **[GitHub Issues](https://github.com/SuperagenticAI/superquantx/issues)** - Ask questions - **QML Community** - Join quantum machine learning forums and discussions diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index d35ea78..3a18c96 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -1,5 +1,9 @@ # Quantum Algorithms +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 0 of 22 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](backends.md). + + SuperQuantX provides a comprehensive library of quantum algorithms, from fundamental quantum computing primitives to cutting-edge quantum machine learning methods. This guide covers how to use, customize, and combine these algorithms in your research. ## ๐ŸŽฏ Algorithm Categories @@ -992,7 +996,7 @@ For algorithm-specific help: - **[Tutorials](../tutorials/quantum-ml.md)**: Step-by-step algorithm tutorials - **[API Reference](../api/algorithms.md)**: Detailed function documentation -- **[Examples](../tutorials/advanced-examples.md)**: Real-world algorithm applications +- **[Examples](../showcase.md)**: Real-world algorithm applications - **[GitHub Issues](https://github.com/SuperagenticAI/superquantx/issues)**: Report algorithm bugs --- diff --git a/docs/user-guide/backends.md b/docs/user-guide/backends.md index 39f144b..8e83cc4 100644 --- a/docs/user-guide/backends.md +++ b/docs/user-guide/backends.md @@ -1,714 +1,108 @@ # Quantum Backends -SuperQuantX's core strength lies in its ability to provide a unified interface across multiple quantum computing frameworks. This guide explains how to work with different backends, compare their capabilities, and choose the right one for your research. +SuperQuantX gives every backend the same small interface: build a circuit, +add gates, measure, run. The algorithms (VQE, QAOA, QSVM, QNN) are written +against that interface, so they run unchanged on every gate-model backend. -## ๐ŸŽฏ Backend Overview +## What works today -A **backend** in SuperQuantX is an abstraction layer that connects your quantum algorithms to specific quantum computing frameworks or hardware. Think of it as a translator that converts your high-level SuperQuantX code into the native operations of each framework. +Every row marked "tested" is exercised by the unit tests with a Bell state, +a qubit-order check, exact expectation values and the fidelity kernel. -```python -import superquantx as sqx - -# Same algorithm, different backends -for backend_name in ['simulator', 'pennylane', 'qiskit', 'cirq']: - backend = sqx.get_backend(backend_name) - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - result = backend.run(circuit, shots=1000) - print(f"{backend_name}: {result.get_counts()}") -``` - -## ๐Ÿ” Available Backends - -### Built-in Simulator Backend - -The simulator backend is SuperQuantX's native quantum simulator, optimized for educational purposes and rapid prototyping. - -```python -# Get the simulator backend -backend = sqx.get_backend('simulator') - -# Check capabilities -caps = backend.get_capabilities() -print(f"Max qubits: {caps.max_qubits}") -print(f"Supports noise: {caps.has_noise}") -print(f"Native gates: {caps.native_gates}") -``` - -**Characteristics:** -- โœ… Always available (no additional dependencies) -- โœ… Fast for small circuits (< 20 qubits) -- โœ… Perfect for learning and prototyping -- โŒ Limited scalability -- โŒ No real quantum hardware access - -### PennyLane Backend - -PennyLane integration provides excellent quantum machine learning capabilities with automatic differentiation. - -```python -# PennyLane backend with specific device -backend = sqx.get_backend('pennylane', device='default.qubit') - -# Or use lightning for speed -fast_backend = sqx.get_backend('pennylane', device='lightning.qubit') -``` - -**Characteristics:** -- โœ… Excellent for quantum machine learning -- โœ… Automatic differentiation support -- โœ… Multiple device options (CPU, GPU, hardware) -- โœ… Strong optimization capabilities -- โŒ Learning curve for PennyLane-specific concepts +| Backend name | SDK | Runs on | Status | +|---|---|---|---| +| `simulator` | none (NumPy) | local statevector | tested | +| `pennylane` | PennyLane | `default.qubit` | tested | +| `qiskit` | Qiskit + Aer | Aer simulator | tested | +| `cirq` | Cirq | Cirq simulator | tested | +| `braket` | Amazon Braket SDK | `LocalSimulator` (`device="local:braket_sv"`) | tested | +| `tket` | pytket | pytket local simulator | tested | +| `ocean` | D-Wave Ocean | QUBO/Ising only, needs a Leap token for hardware | annealing only, not a gate-model backend | +| IBM Quantum, Braket devices, Quantinuum | via `qiskit`, `braket`, `tket` | cloud hardware | untested, needs your own credentials | +| Azure Quantum, Rigetti Forest, cuQuantum, TensorFlow Quantum | | | planned, not implemented | -### Qiskit Backend +Check your own installation with a real Bell circuit on each backend: -IBM's Qiskit framework integration provides access to IBM quantum computers and advanced simulators. - -```python -# Local Qiskit backend -backend = sqx.get_backend('qiskit', provider='local') - -# IBM Quantum backend (requires setup) -# backend = sqx.get_backend('qiskit', provider='IBMQ') +```bash +superquantx list-backends ``` -**Characteristics:** -- โœ… Access to IBM quantum hardware -- โœ… Mature ecosystem and tools -- โœ… Advanced noise modeling -- โœ… Strong community support -- โŒ Complex setup for hardware access -- โŒ Can be slower for simulations - -### Cirq Backend - -Google's Cirq framework, optimized for NISQ (Noisy Intermediate-Scale Quantum) devices. - -```python -# Cirq backend -backend = sqx.get_backend('cirq') - -# With specific simulator -backend = sqx.get_backend('cirq', simulator='SparseSimulator') -``` - -**Characteristics:** -- โœ… Optimized for NISQ algorithms -- โœ… Good for quantum simulation -- โœ… Access to Google quantum hardware (with setup) -- โœ… Flexible circuit construction -- โŒ Google-centric ecosystem -- โŒ Limited quantum ML support - -## ๐Ÿš€ Working with Backends - -### Basic Backend Operations +## Choosing a backend ```python import superquantx as sqx -# List all available backends -available = sqx.list_available_backends() -print(f"Available backends: {available}") - -# Get a specific backend -backend = sqx.get_backend('pennylane') - -# Backend information -print(f"Backend name: {backend.name}") -print(f"Backend type: {backend.backend_type}") -print(f"Version: {backend.version}") - -# Check if backend is available -if backend.is_available(): - print("โœ… Backend is ready to use") -else: - print("โŒ Backend is not available") -``` - -### Backend Configuration - -```python -# Configure backend with specific options -backend = sqx.get_backend( - 'pennylane', - device='lightning.qubit', - shots=5000, - seed=42 -) +backend = sqx.get_backend("pennylane") # or "simulator", "qiskit", "cirq", "tket" +braket = sqx.get_backend("braket", device="local:braket_sv") -# Runtime configuration changes -backend.configure( - optimization_level=2, - noise_model=None, - memory_limit='4GB' -) +print(sorted(sqx.list_available_backends())) +print(sqx.get_backend_info()) # installed SDK versions ``` -### Backend Context Manager +Algorithms accept either a backend name or a backend object: ```python -# Temporary backend switching -with sqx.backend_context('qiskit'): - # All operations in this block use Qiskit - circuit = sqx.create_circuit(2) - circuit.h(0) - result = sqx.run(circuit) - -# Back to default backend outside context -``` - -## ๐Ÿ”„ Backend Comparison - -### Performance Comparison - -```python -import time -import numpy as np - -def benchmark_backends(circuit_depth=10, num_qubits=4, shots=1000): - """Compare backend performance.""" - - backends = ['simulator', 'pennylane', 'qiskit'] - results = {} - - for backend_name in backends: - try: - backend = sqx.get_backend(backend_name) - - # Create test circuit - circuit = backend.create_circuit(num_qubits) - - # Add random gates - np.random.seed(42) - for _ in range(circuit_depth): - qubit = np.random.randint(0, num_qubits) - gate = np.random.choice(['h', 'x', 'y', 'z']) - getattr(circuit, gate)(qubit) - - # Add entangling gates - for i in range(num_qubits - 1): - circuit.cx(i, i + 1) - - circuit.measure_all() - - # Time execution - start_time = time.time() - result = backend.run(circuit, shots=shots) - end_time = time.time() - - results[backend_name] = { - 'execution_time': end_time - start_time, - 'counts': result.get_counts(), - 'success': True - } - - except Exception as e: - results[backend_name] = { - 'error': str(e), - 'success': False - } - - return results - -# Run benchmark -benchmark_results = benchmark_backends() - -print("๐Ÿƒ Backend Performance Comparison:") -for backend, result in benchmark_results.items(): - if result['success']: - print(f"{backend:12}: {result['execution_time']:.3f} seconds") - else: - print(f"{backend:12}: โŒ {result['error']}") -``` - -### Feature Comparison - -```python -def compare_backend_features(): - """Compare capabilities across backends.""" - - backends = sqx.list_available_backends() - - features = { - 'max_qubits': [], - 'has_noise': [], - 'supports_gpu': [], - 'native_gates': [], - 'measurement_types': [] - } - - comparison_data = [] - - for backend_name in backends: - try: - backend = sqx.get_backend(backend_name) - caps = backend.get_capabilities() - - row = { - 'Backend': backend_name, - 'Max Qubits': caps.max_qubits, - 'Noise Support': 'โœ…' if caps.has_noise else 'โŒ', - 'GPU Support': 'โœ…' if caps.supports_gpu else 'โŒ', - 'Gate Count': len(caps.native_gates), - 'Hardware Access': 'โœ…' if caps.hardware_access else 'โŒ' - } - comparison_data.append(row) - - except Exception as e: - print(f"โš ๏ธ Could not analyze {backend_name}: {e}") - - # Display comparison table - if comparison_data: - import pandas as pd - df = pd.DataFrame(comparison_data) - print("๐Ÿ” Backend Feature Comparison:") - print(df.to_string(index=False)) - - return comparison_data - -# Run feature comparison -feature_comparison = compare_backend_features() -``` - -## ๐ŸŽ›๏ธ Advanced Backend Usage - -### Custom Backend Selection - -```python -def smart_backend_selection(requirements): - """Automatically select best backend based on requirements.""" - - available_backends = sqx.list_available_backends() - - # Score backends based on requirements - scores = {} - - for backend_name in available_backends: - backend = sqx.get_backend(backend_name) - caps = backend.get_capabilities() - score = 0 - - # Qubit requirement - if caps.max_qubits >= requirements.get('min_qubits', 1): - score += 10 - - # GPU requirement - if requirements.get('gpu_preferred', False) and caps.supports_gpu: - score += 5 - - # Noise requirement - if requirements.get('noise_modeling', False) and caps.has_noise: - score += 5 - - # Speed preference - if backend_name == 'simulator': # Fastest for small circuits - score += 3 - elif backend_name == 'pennylane' and 'lightning' in str(caps.device): - score += 4 - - scores[backend_name] = score - - # Return best backend - best_backend = max(scores, key=scores.get) - return best_backend, scores - -# Example usage -requirements = { - 'min_qubits': 8, - 'gpu_preferred': True, - 'noise_modeling': False -} - -best_backend, all_scores = smart_backend_selection(requirements) -print(f"๐ŸŽฏ Best backend for your requirements: {best_backend}") -print(f"๐Ÿ“Š Backend scores: {all_scores}") -``` - -### Backend Pooling - -```python -class BackendPool: - """Manage multiple backends for parallel execution.""" - - def __init__(self, backend_names=None): - if backend_names is None: - backend_names = sqx.list_available_backends() - - self.backends = {} - for name in backend_names: - try: - self.backends[name] = sqx.get_backend(name) - except Exception as e: - print(f"โš ๏ธ Could not load {name}: {e}") - - def run_parallel(self, circuit, shots=1000): - """Run the same circuit on multiple backends in parallel.""" - - import concurrent.futures - - def run_on_backend(backend_name): - backend = self.backends[backend_name] - return backend.run(circuit, shots=shots) - - results = {} - with concurrent.futures.ThreadPoolExecutor() as executor: - # Submit jobs to all backends - futures = { - executor.submit(run_on_backend, name): name - for name in self.backends.keys() - } - - # Collect results - for future in concurrent.futures.as_completed(futures): - backend_name = futures[future] - try: - result = future.result() - results[backend_name] = result.get_counts() - except Exception as e: - results[backend_name] = f"Error: {e}" - - return results - -# Example usage -pool = BackendPool(['simulator', 'pennylane']) - -# Create test circuit -circuit = sqx.create_circuit(2) -circuit.h(0) -circuit.cx(0, 1) -circuit.measure_all() - -# Run on all backends -parallel_results = pool.run_parallel(circuit) -print("๐Ÿ”„ Parallel execution results:") -for backend, counts in parallel_results.items(): - print(f"{backend}: {counts}") -``` - -## ๐Ÿ”ง Backend-Specific Features - -### PennyLane-Specific Features - -```python -# Automatic differentiation with PennyLane -backend = sqx.get_backend('pennylane') - -# Create parameterized circuit -circuit = backend.create_circuit(2) -theta = backend.create_parameter('theta') -phi = backend.create_parameter('phi') - -circuit.ry(theta, 0) -circuit.rz(phi, 1) -circuit.cx(0, 1) - -# Define cost function -def cost_function(params): - return backend.expectation_value(circuit, observable='Z', params=params) +import superquantx as sqx -# Compute gradients -import jax -grad_fn = jax.grad(cost_function) -gradients = grad_fn([0.5, 0.8]) -print(f"Gradients: {gradients}") +vqe = sqx.VQE(hamiltonian={"Z": 1.0}, backend="qiskit") +print(vqe.find_ground_state()) # -1.0 ``` -### Qiskit-Specific Features +## Building and running circuits ```python -# Access Qiskit's transpiler -backend = sqx.get_backend('qiskit') +import superquantx as sqx +backend = sqx.get_backend("cirq") circuit = backend.create_circuit(3) -circuit.h(0) -circuit.cx(0, 1) -circuit.cx(1, 2) - -# Transpile for specific hardware -transpiled = backend.transpile( - circuit, - optimization_level=3, - target_device='ibm_manila' -) - -print(f"Original depth: {circuit.depth()}") -print(f"Transpiled depth: {transpiled.depth()}") -``` - -### Cirq-Specific Features - -```python -# Access Cirq's noise models -backend = sqx.get_backend('cirq') - -# Add noise model -noise_model = backend.create_noise_model( - depolarizing_prob=0.01, - damping_prob=0.02 -) - -backend.set_noise_model(noise_model) - -# Run noisy simulation -circuit = backend.create_circuit(2) -circuit.h(0) -circuit.cx(0, 1) -noisy_result = backend.run(circuit, shots=1000) -``` - -## ๐Ÿ“Š Backend Monitoring +circuit = backend.add_gate(circuit, "H", 0) +circuit = backend.add_gate(circuit, "CNOT", [0, 1]) +circuit = backend.add_gate(circuit, "CNOT", [1, 2]) +circuit = backend.add_measurement(circuit) -### Performance Monitoring - -```python -class BackendMonitor: - """Monitor backend performance and health.""" - - def __init__(self): - self.metrics = {} - - def health_check(self, backend_name): - """Check if backend is healthy.""" - try: - backend = sqx.get_backend(backend_name) - - # Simple test circuit - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - # Run test - start_time = time.time() - result = backend.run(circuit, shots=100) - elapsed = time.time() - start_time - - # Check results make sense - counts = result.get_counts() - total_counts = sum(counts.values()) - - if total_counts != 100: - return False, f"Expected 100 shots, got {total_counts}" - - if elapsed > 30: # 30 second timeout - return False, f"Too slow: {elapsed:.2f}s" - - return True, f"Healthy (response time: {elapsed:.3f}s)" - - except Exception as e: - return False, f"Error: {e}" - - def monitor_all_backends(self): - """Monitor all available backends.""" - backends = sqx.list_available_backends() - status = {} - - for backend_name in backends: - healthy, message = self.health_check(backend_name) - status[backend_name] = { - 'healthy': healthy, - 'message': message, - 'timestamp': time.time() - } - - return status - -# Example usage -monitor = BackendMonitor() -status_report = monitor.monitor_all_backends() - -print("๐Ÿฅ Backend Health Report:") -for backend, status in status_report.items(): - icon = "โœ…" if status['healthy'] else "โŒ" - print(f"{icon} {backend}: {status['message']}") +result = backend.execute_circuit(circuit, shots=1000) +print(backend.counts_big_endian(result["counts"])) # only '000' and '111' ``` -## ๐Ÿ”€ Backend Migration +Supported gates on every backend: `H`, `X`, `Y`, `Z`, `S`, `T`, `RX`, `RY`, +`RZ`, `CNOT`, `CZ`, `SWAP`, `CCX`. Controlled rotations (`CRX`, `CRY`, +`CRZ`) work everywhere except `braket`. An unknown gate raises an error +instead of being silently dropped. -### Algorithm Migration +### Bit order -```python -def migrate_algorithm_to_backend(algorithm_func, from_backend, to_backend): - """Migrate an algorithm from one backend to another.""" - - print(f"๐Ÿ”„ Migrating from {from_backend} to {to_backend}") - - # Test with original backend - original_result = algorithm_func(from_backend) - - # Test with new backend - new_result = algorithm_func(to_backend) - - # Compare results - def compare_results(result1, result2, tolerance=0.1): - """Compare quantum measurement results.""" - if not result1 or not result2: - return False - - # Compare state probabilities - all_states = set(result1.keys()) | set(result2.keys()) - - for state in all_states: - prob1 = result1.get(state, 0) / sum(result1.values()) - prob2 = result2.get(state, 0) / sum(result2.values()) - - if abs(prob1 - prob2) > tolerance: - return False - - return True - - is_compatible = compare_results(original_result, new_result) - - print(f"๐Ÿ“Š Original result: {original_result}") - print(f"๐Ÿ“Š New result: {new_result}") - print(f"โœ… Compatible: {is_compatible}") - - return is_compatible - -# Example: Migrate Bell state creation -def bell_state_algorithm(backend_name): - backend = sqx.get_backend(backend_name) - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - result = backend.run(circuit, shots=1000) - return result.get_counts() - -# Test migration -compatible = migrate_algorithm_to_backend( - bell_state_algorithm, - 'simulator', - 'pennylane' -) -``` +Qiskit and the built-in simulator order bits little-endian; the other SDKs +are big-endian. `counts_big_endian` and `statevector_big_endian` convert any +backend's output to big-endian (qubit 0 is the leftmost bit), so results are +directly comparable across backends. -## ๐Ÿ› ๏ธ Custom Backend Development - -### Creating a Custom Backend +## Expectation values and kernels ```python -from superquantx.backends import BaseBackend - -class MyCustomBackend(BaseBackend): - """Example custom backend implementation.""" - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.name = "my_custom_backend" - self.backend_type = "custom" - - def create_circuit(self, num_qubits): - """Create a quantum circuit.""" - # Your circuit implementation - return MyCustomCircuit(num_qubits) - - def run(self, circuit, shots=1000): - """Execute a quantum circuit.""" - # Your execution logic - pass - - def get_capabilities(self): - """Return backend capabilities.""" - return BackendCapabilities( - max_qubits=32, - has_noise=False, - supports_gpu=True, - native_gates=['h', 'x', 'cx'], - hardware_access=False - ) - -# Register custom backend -sqx.register_backend('my_custom', MyCustomBackend) - -# Use custom backend -custom_backend = sqx.get_backend('my_custom') -``` - -## ๐Ÿ“š Best Practices - -### Backend Selection Guidelines - -1. **For Learning**: Use `simulator` backend - simple and always available -2. **For QML Research**: Use `pennylane` backend - excellent differentiation support -3. **For IBM Hardware**: Use `qiskit` backend - direct access to IBM systems -4. **For Google Hardware**: Use `cirq` backend - optimized for Google devices -5. **For Cloud Computing**: Use `braket` backend - access to multiple hardware providers - -### Performance Optimization - -```python -# Backend-specific optimizations -def optimize_for_backend(circuit, backend_name): - """Apply backend-specific optimizations.""" - - backend = sqx.get_backend(backend_name) - - if backend_name == 'pennylane': - # PennyLane optimizations - circuit = circuit.optimize_parameters() - circuit = circuit.merge_rotations() - - elif backend_name == 'qiskit': - # Qiskit optimizations - circuit = backend.transpile(circuit, optimization_level=3) - - elif backend_name == 'cirq': - # Cirq optimizations - circuit = circuit.optimize_for_nisq() - - return circuit -``` +import numpy as np +import superquantx as sqx -### Error Handling +backend = sqx.get_backend("pennylane") -```python -def robust_backend_execution(circuit, backend_priorities=['pennylane', 'qiskit', 'simulator']): - """Execute circuit with fallback backends.""" - - for backend_name in backend_priorities: - try: - backend = sqx.get_backend(backend_name) - result = backend.run(circuit, shots=1000) - print(f"โœ… Successfully executed on {backend_name}") - return result, backend_name - - except Exception as e: - print(f"โŒ {backend_name} failed: {e}") - continue - - raise RuntimeError("All backends failed!") +circuit = backend.create_circuit(1) +circuit = backend.add_gate(circuit, "RY", 0, [np.pi]) +print(backend.compute_expectation(circuit, {"Z": 1.0})) # -1.0 -# Example usage -result, successful_backend = robust_backend_execution(my_circuit) +X = np.array([[0.1, 0.2], [0.7, -0.4]]) +K = backend.compute_kernel_matrix(X, X, feature_map="ZZFeatureMap") +print(np.diag(K)) # [1. 1.] ``` -## ๐Ÿ”ฎ Future Backend Support - -SuperQuantX is actively working on support for additional backends: - -- **IonQ**: Ion trap quantum computers -- **Rigetti**: Superconducting quantum processors -- **Xanadu**: Photonic quantum computing -- **Oxford Quantum Computing**: TKET optimization -- **Quantinuum**: Trapped ion systems - -## ๐Ÿ“ž Getting Help - -If you need help with backends: - -- **[Backend-Specific Guides](../backends/pennylane.md)**: Detailed guides for each backend -- **[Troubleshooting](../help/troubleshooting.md)**: Common backend issues -- **[FAQ](../help/faq.md)**: Frequently asked questions -- **[GitHub Issues](https://github.com/SuperagenticAI/superquantx/issues)**: Report backend bugs - ---- +Feature maps: `ZZFeatureMap`, `ZFeatureMap`, `PauliFeatureMap`, +`AngleEncoding`. Kernels are computed exactly from simulated statevectors. +They are real quantum-circuit kernels, but classically simulated, so they say +nothing about quantum advantage on their own. Use +[`compare_to_classical`](benchmarking.md) to see how they stack up. -!!! tip "Backend Recommendation" - Start with the `simulator` backend for learning, then move to `pennylane` for quantum machine learning research. Use other backends when you need specific hardware access or features. +## Hardware -!!! warning "Backend Availability" - Not all backends may be available depending on your installation. Use `sqx.list_available_backends()` to check which backends are installed and ready to use. \ No newline at end of file +Running on cloud hardware goes through the underlying SDK and your own +account (IBM Quantum token for `qiskit`, AWS credentials for `braket`, +Quantinuum credentials for `tket`). These paths are not covered by the test +suite. Start on the local simulators and move to hardware only once a result +holds up against classical baselines. diff --git a/docs/user-guide/benchmarking.md b/docs/user-guide/benchmarking.md new file mode 100644 index 0000000..34378c4 --- /dev/null +++ b/docs/user-guide/benchmarking.md @@ -0,0 +1,84 @@ +# Benchmarking Against Classical Baselines + +A quantum model result means little on its own. `compare_to_classical` puts +a quantum classifier next to tuned classical models on identical +cross-validation folds and tells you whether the difference is real. + +```python +from sklearn.datasets import make_moons +import superquantx as sqx + +X, y = make_moons(n_samples=100, noise=0.2, random_state=0) +result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend="pennylane"), cv=5) +print(result.table()) +print(result.verdict) +``` + +Real output (from [the showcase](../showcase.md)): + +```text +model accuracy wall time grid QPU circuits +---------------------------------------------------------------------------------- +QuantumSVM (PennyLane), tuned 0.930 +/- 0.051 3.51s 25 119,000 +QuantumSVM (PennyLane), untuned 0.670 +/- 0.125 0.64s 1 - +SVC (RBF), tuned C and gamma 0.950 +/- 0.055 0.89s 25 - +Logistic regression, tuned C 0.860 +/- 0.097 0.32s 4 - +---------------------------------------------------------------------------------- +100 samples, 2 features, 5-fold stratified CV (identical folds for every model), seed=0 +quantum minus best classical: -0.020; no significant difference from SVC (RBF), tuned C and gamma (p=0.54) +Protocol: arXiv:2610.42029. Quantum kernels are classically simulated. +``` + +## Protocol + +The function follows the evaluation protocol of +[Bhalgami (2026), "Empirical Evaluation of Quantum Kernel Methods for +Classification: A Comparative Study with Classical Kernels", +arXiv:2610.42029](https://arxiv.org/abs/2610.42029): + +- **Same folds for every model.** `StratifiedKFold(cv, shuffle=True, random_state=seed)`. +- **Equal tuning budget.** The quantum kernel bandwidth (input scaling) and + `C` are tuned on a 5 x 5 grid, the same size as the RBF SVM's `C` x `gamma` + grid, with nested inner cross-validation. Logistic regression tunes `C`. +- **Per-fold preprocessing.** Scaling is refit inside each fold, so no test + information leaks into training. +- **Corrected significance test.** The p-value uses the Nadeau-Bengio + corrected resampled t-test, which accounts for overlapping training sets + in cross-validation. A plain paired t-test overstates significance. +- **Hardware cost.** The "QPU circuits" column counts the circuits a real + device would need for the tuned kernel: `n(n-1)/2` training-kernel entries + plus `n_test * n_train` test entries, summed over folds and grid points. +- **Untuned reference.** The untuned row (bandwidth 1, `C` = 1) shows how much + of the quantum score comes from tuning rather than from the circuit. + +## How to read the result + +The paper and related work (Shaydulin and Wild 2022; arXiv:2503.05602) find +that once the bandwidth is tuned, fidelity quantum kernels behave much like +an RBF kernel, and tuned quantum kernels are statistically indistinguishable +from a tuned RBF SVM on standard datasets. The showcase reproduces exactly +that: bandwidth tuning lifts the quantum kernel from 0.67 to 0.93, and the +remaining gap to the RBF SVM is not significant (p = 0.54). + +So a "no significant difference" verdict is the expected, honest outcome on +small classical datasets. A claim of quantum benefit needs data where the +quantum model wins this test, at a hardware cost you can afford. + +## API + +`compare_to_classical(X, y, classifier, *, cv=5, seed=0, inner_cv=3, +bandwidth_grid=..., C_grid=..., rbf_gamma_grid=..., logreg_C_grid=..., +include_untuned=True)` returns a `ComparisonResult` with: + +- `scores`: one `ModelScore` per model (`accuracy_mean`, `accuracy_std`, + `fold_accuracies`, `wall_time_s`, `grid_size`, `best_params`, + `hardware_circuits`); +- `quantum`, `best_classical`: shortcuts to those rows; +- `p_value_vs_best_classical`, `delta_vs_best_classical`, `verdict`; +- `table()` and `to_dict()` for reporting. + +From the command line: + +```bash +superquantx benchmark --dataset moons --backend pennylane +``` diff --git a/docs/user-guide/overview.md b/docs/user-guide/overview.md index 02167b1..aee30e7 100644 --- a/docs/user-guide/overview.md +++ b/docs/user-guide/overview.md @@ -1,5 +1,9 @@ # What is SuperQuantX? +!!! warning "Unverified examples" + This page predates the current release and parts of it describe planned or older API. Only 4 of 14 code snippets on this page run as-is today. For verified, runnable code see the [Quick Start](../getting-started/quickstart.md), the [Showcase](../showcase.md) and the [Backends guide](backends.md). + + SuperQuantX is a cutting-edge **experimental quantum AI research platform** that provides a unified API for quantum-agentic systems research. It bridges the gap between multiple quantum computing frameworks and makes quantum machine learning accessible to researchers, developers, and students. ## ๐Ÿ”ฌ The Vision diff --git a/examples/basic_circuit.py b/examples/basic_circuit.py index 47ce859..4a7949e 100644 --- a/examples/basic_circuit.py +++ b/examples/basic_circuit.py @@ -8,6 +8,8 @@ - Visualizing the circuit """ +import os + import numpy as np from superquantx import QuantumCircuit, SuperQuantXClient @@ -214,7 +216,8 @@ def main(): print("=" * 40) # Get API key (optional) - api_key = input("Enter your SuperQuantX API key (or press Enter to skip remote execution): ").strip() + # Optional: set SUPERQUANTX_API_KEY to also try remote execution. + api_key = os.environ.get("SUPERQUANTX_API_KEY", "").strip() if not api_key: api_key = None diff --git a/examples/quantum_agents_demo.py b/examples/quantum_agents_demo.py index 5f41211..04379cf 100644 --- a/examples/quantum_agents_demo.py +++ b/examples/quantum_agents_demo.py @@ -1,183 +1,92 @@ -#!/usr/bin/env python3 -""" -SuperQuantX Quantum Agentic AI Demo +"""Quantum agents demo: every quantum answer next to an exact classical check. + +Run: + uv run python examples/quantum_agents_demo.py + +What it does (all circuits are classically simulated): +1. QuantumPortfolioAgent picks 3 of 6 assets with CVaR-VQE and is checked + against brute force over all selections and a classical Markowitz solution. +2. QuantumClassificationAgent trains a quantum-kernel SVM and benchmarks it + against a tuned RBF SVM and logistic regression on identical CV folds. -This example demonstrates the new quantum agents capabilities, -showcasing autonomous quantum-enhanced AI systems that can -make decisions and solve complex problems independently. +Set SQX_BACKEND to choose the backend (default: pennylane, falls back to the +built-in simulator if PennyLane is not installed). The script exits non-zero +if any step fails. """ +import os +import sys +import time +import warnings + import numpy as np +from sklearn.datasets import make_moons import superquantx as sqx -def demo_quantum_trading_agent(): - """Demonstrate quantum trading agent capabilities.""" - print("๐Ÿค– Quantum Trading Agent Demo") - print("=" * 50) - - # Create a quantum trading agent - trader = sqx.QuantumTradingAgent( - backend='simulator', - strategy='quantum_portfolio', - risk_tolerance=0.3, - markets=['crypto', 'stocks'] - ) - - # Deploy the agent - print("Deploying quantum trading agent...") - result = trader.deploy() - - if result.result: - performance = result.result['performance'] - quantum_advantage = result.result['quantum_advantage'] - - print("โœ… Agent deployed successfully!") - print(f"Expected Return: {performance['expected_return']:.2%}") - print(f"Risk Level: {performance['risk']:.2%}") - print(f"Sharpe Ratio: {performance['sharpe_ratio']:.2f}") - print(f"Quantum Advantage: {quantum_advantage:.2%}") - print(f"Execution Time: {result.execution_time:.2f}s") - else: - print(f"โŒ Deployment failed: {result.error}") - - print() - -def demo_quantum_research_agent(): - """Demonstrate quantum research agent capabilities.""" - print("๐Ÿ”ฌ Quantum Research Agent Demo") - print("=" * 50) - - # Create a quantum research agent for materials science - researcher = sqx.QuantumResearchAgent( - backend='simulator', - domain='materials_science', - hypothesis_generation=True, - experiment_design=True - ) - - # Investigate a research question - print("Investigating superconductor research question...") - result = researcher.investigate( - research_question="Novel room-temperature superconductor discovery", - constraints={"budget": 500000, "timeline": "18_months"} - ) - - if result.result: - research_plan = result.result['research_plan'] - hypothesis = result.result['hypothesis'] - experiments = result.result['experiments'] - - print("โœ… Research investigation completed!") - print(f"Research Domain: {result.result['domain']}") - print(f"Timeline: {research_plan['timeline']}") - print(f"Budget Estimate: ${research_plan['budget_estimate']:,}") - print(f"Quantum Simulations: {research_plan['quantum_simulations_required']}") - print(f"Primary Hypothesis: {hypothesis['primary_hypothesis'][:100]}...") - print(f"Experiments Designed: {len(experiments)}") - print(f"Execution Time: {result.execution_time:.2f}s") - else: - print(f"โŒ Investigation failed: {result.error}") - - print() - -def demo_quantum_optimization_agent(): - """Demonstrate quantum optimization agent capabilities.""" - print("โšก Quantum Optimization Agent Demo") - print("=" * 50) - - # Create a quantum optimization agent - optimizer = sqx.QuantumOptimizationAgent( - backend='simulator', - problem_type='combinatorial' - ) - - # Create a simple optimization problem (traveling salesman) - problem_data = { - 'num_cities': 4, - 'distances': np.random.rand(4, 4) - } - - print("Solving traveling salesman problem...") - result = optimizer.solve(problem_data) - - if result.result: - print("โœ… Optimization completed!") - print("Problem Type: combinatorial") - print(f"Algorithm Used: {result.metadata.get('algorithm_used', 'Unknown')}") - print(f"Execution Time: {result.execution_time:.2f}s") - else: - print(f"โŒ Optimization failed: {result.error}") - - print() - -def demo_traditional_quantum_ml(): - """Demonstrate traditional quantum ML algorithms for comparison.""" - print("๐Ÿ“Š Traditional Quantum ML Demo (For Comparison)") - print("=" * 50) - - # Generate sample data - np.random.seed(42) - X = np.random.rand(100, 4) - y = np.random.randint(0, 2, 100) - - # Train a quantum SVM - print("Training Quantum SVM...") - qsvm = sqx.QuantumSVM(backend='simulator') - qsvm.fit(X, y) - - # Get predictions - predictions = qsvm.predict(X[:10]) - accuracy = qsvm.score(X, y) - - print("โœ… Quantum SVM trained!") - print(f"Accuracy: {accuracy:.2%}") - print(f"Sample predictions: {predictions[:5]}") - - print() - -def main(): - """Run all quantum agent demos.""" - print("๐Ÿš€ SuperQuantX: Quantum Agentic AI Platform Demo") - print("Building the Foundation for Quantum Agentic AI") - print("=" * 60) - print() - - print("This demo showcases autonomous quantum agents that combine") - print("quantum computing with AI to solve complex real-world problems.") - print() +warnings.filterwarnings("ignore") + +def pick_backend() -> str: + name = os.environ.get("SQX_BACKEND", "pennylane") try: - # Demo quantum agents (the new hotness!) - demo_quantum_trading_agent() - demo_quantum_research_agent() - demo_quantum_optimization_agent() - - # Demo traditional quantum ML (still supported) - demo_traditional_quantum_ml() - - print("๐ŸŽฏ Summary") - print("=" * 50) - print("โœ… Quantum Trading Agent: Autonomous financial optimization") - print("โœ… Quantum Research Agent: Scientific discovery acceleration") - print("โœ… Quantum Optimization Agent: General problem solving") - print("โœ… Traditional Quantum ML: Core algorithm support") - print() - print("SuperQuantX bridges quantum computing and agentic AI,") - print("enabling developers to deploy quantum-enhanced intelligent") - print("systems in minutes, not months.") - print() - print("๐ŸŒŸ Ready to build quantum agents? Try:") - print(" pip install superquantx") - print(" import superquantx as sqx") - print(" agent = sqx.QuantumTradingAgent()") - - except Exception as e: - print(f"โŒ Demo failed: {e}") - print("This is expected if quantum backends are not fully configured.") - print("The agents are designed to work with actual quantum hardware") - print("and simulators when properly set up.") + sqx.get_backend(name) + return name + except Exception as exc: # backend extra not installed + print(f"Backend '{name}' unavailable ({exc}); using 'simulator'") + return "simulator" + + +def portfolio_demo(backend: str) -> bool: + print("\n1. QuantumPortfolioAgent: choose 3 of 6 assets") + print("-" * 60) + rng = np.random.default_rng(3) + mu = np.array([0.010, 0.008, 0.012, 0.006, 0.009, 0.011]) + A = rng.normal(size=(6, 6)) * 0.01 + returns = rng.multivariate_normal(mu, A @ A.T + np.eye(6) * 1e-4, size=250) + + agent = sqx.QuantumPortfolioAgent(backend=backend, n_select=3, seed=0) + res = agent.solve(returns) + if res.error: + print(f"FAILED: {res.error}") + return False + r = res.result + mk = r["markowitz_reference"] + print(f" quantum (CVaR-VQE) selection : {r['selected_assets']} objective {r['objective']:.6f}") + print(f" brute-force optimum : {r['classical_selected_assets']} objective {r['classical_objective']:.6f}") + print(f" matches exact optimum : {r['matches_classical_optimum']}" + f" (P(optimum) in final state = {r['probability_of_optimum']:.2f})") + print(f" quantum portfolio : return {r['expected_return']:.4f}, risk {r['risk']:.4f}") + print(f" classical Markowitz weights : return {mk['expected_return']:.4f}, risk {mk['risk']:.4f}" + f" {np.round(mk['weights'], 2)}") + print(f" time {res.execution_time:.1f}s on {backend}") + return True + + +def classification_demo(backend: str) -> bool: + print("\n2. QuantumClassificationAgent: make_moons, 5-fold CV") + print("-" * 60) + X, y = make_moons(n_samples=100, noise=0.2, random_state=0) + agent = sqx.QuantumClassificationAgent(backend=backend, seed=0) + res = agent.solve((X, y)) + if res.error: + print(f"FAILED: {res.error}") + return False + print(res.result["benchmark"].table()) + print(f" time {res.execution_time:.1f}s on {backend}") + return True + + +def main() -> int: + print(f"SuperQuantX {sqx.__version__}: quantum agents with classical baselines") + backend = pick_backend() + start = time.time() + ok = portfolio_demo(backend) and classification_demo(backend) + print("\n" + ("All agent demos completed" if ok else "Agent demo FAILED") + + f" in {time.time() - start:.1f}s") + return 0 if ok else 1 + if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/examples/quantum_ml.py b/examples/quantum_ml.py index eb4d34c..2658571 100644 --- a/examples/quantum_ml.py +++ b/examples/quantum_ml.py @@ -9,6 +9,8 @@ - Performance comparison with classical methods """ +import os + import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import make_classification, make_moons, make_regression @@ -18,7 +20,7 @@ from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC -from superquantx import SuperQuantXClient, QuantumNN +from superquantx import QuantumNN, SuperQuantXClient from superquantx.ml import ( AmplitudeEmbeddingFeatureMap, AngleEmbeddingFeatureMap, @@ -575,7 +577,8 @@ def main(): print("=" * 45) # Setup - api_key = input("Enter your SuperQuantX API key (or press Enter for simulation): ").strip() + # Optional: set SUPERQUANTX_API_KEY to also try remote execution. + api_key = os.environ.get("SUPERQUANTX_API_KEY", "").strip() client = SuperQuantXClient(api_key) if api_key else None if client: diff --git a/examples/quick_start.py b/examples/quick_start.py index 413d56f..9c47f7a 100644 --- a/examples/quick_start.py +++ b/examples/quick_start.py @@ -77,9 +77,9 @@ import superquantx as sqx import numpy as np -# Create sample data -X = np.random.rand(50, 2) -y = np.random.randint(0, 2, 50) +# Create sample data (random labels would make any accuracy meaningless) +from sklearn.datasets import make_moons +X, y = make_moons(n_samples=50, noise=0.1, random_state=0) # List of backends to compare backends = ['simulator', 'pennylane', 'qiskit'] @@ -91,7 +91,7 @@ print(f"\n๐Ÿ” Testing with {backend_name}...") # Create and train model - qsvm = sqx.QuantumSVM(backend=backend_name) + qsvm = sqx.QuantumSVM(backend=backend_name, gamma=0.5) qsvm.fit(X[:40], y[:40]) # Train on first 40 samples # Test accuracy @@ -100,9 +100,11 @@ print(f"โœ… {backend_name} accuracy: {accuracy:.3f}") - except ImportError as e: + except Exception as e: print(f"โŒ {backend_name} not available: {e}") +print("Identical accuracies are expected: every backend computes the same exact kernel.") + print(f"\n๐Ÿ“Š Results Summary: {results}") import superquantx as sqx diff --git a/examples/showcase.py b/examples/showcase.py new file mode 100644 index 0000000..c65db02 --- /dev/null +++ b/examples/showcase.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""SuperQuantX showcase: real circuits, honest baselines, exact checks. + +Three parts, each checked against something classical: + +1. Bell and GHZ circuits on every installed gate-model backend. Only the + correct outcomes (00/11, 000/111) may appear. +2. A quantum kernel SVM on make_moons, compared with a tuned RBF SVM and + logistic regression using the protocol of arXiv:2610.42029 (same folds, + same tuning budget, corrected t-test). +3. QAOA on a small MaxCut instance, checked against brute force. + +Everything runs on local simulators in well under a minute. + +Run: + python examples/showcase.py + SQX_QML_BACKEND=qiskit python examples/showcase.py +""" + +import logging +import os +import time +import warnings + + +warnings.filterwarnings("ignore") +logging.disable(logging.WARNING) + +import numpy as np # noqa: E402 +from sklearn.datasets import make_moons # noqa: E402 + +import superquantx as sqx # noqa: E402 +from superquantx.algorithms.qaoa import brute_force_maxcut # noqa: E402 + + +SHOTS = 1000 +GATE_BACKENDS = [ + ("simulator", {}), + ("pennylane", {}), + ("qiskit", {}), + ("cirq", {}), + ("braket", {"device": "local:braket_sv"}), + ("tket", {}), +] + + +def rule(title: str) -> None: + print(f"\n{title}\n{'=' * len(title)}") + + +def entangled_circuit(backend, n: int): + circuit = backend.create_circuit(n) + circuit = backend.add_gate(circuit, "H", 0) + for q in range(n - 1): + circuit = backend.add_gate(circuit, "CNOT", [q, q + 1]) + return backend.add_measurement(circuit) + + +def part_backends() -> list[str]: + rule("1. Bell and GHZ states on every backend (1000 shots each)") + print(f"{'backend':10s} {'Bell 00/11':>12s} {'GHZ 000/111':>13s} {'correct':>8s} {'time':>7s}") + working = [] + for name, kwargs in GATE_BACKENDS: + try: + backend = sqx.get_backend(name, **kwargs) + t0 = time.time() + cells, correct = [], True + for n in (2, 3): + raw = backend.execute_circuit(entangled_circuit(backend, n), shots=SHOTS) + counts = backend.counts_big_endian(raw["counts"]) + zeros, ones = counts.get("0" * n, 0), counts.get("1" * n, 0) + correct &= zeros + ones == SHOTS + cells.append(f"{zeros}/{ones}") + elapsed = time.time() - t0 + print(f"{name:10s} {cells[0]:>12s} {cells[1]:>13s} {'yes' if correct else 'NO':>8s} {elapsed:6.2f}s") + if correct: + working.append(name) + except Exception as e: # noqa: BLE001 + print(f"{name:10s} unavailable: {str(e).splitlines()[0][:60]}") + print(f"Working: {', '.join(working)}") + return working + + +def part_qml(backend: str) -> None: + rule(f"2. Quantum kernel SVM vs tuned classical models (make_moons, {backend})") + X, y = make_moons(n_samples=100, noise=0.2, random_state=0) + result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend=backend), cv=5, seed=0) + print(result.table()) + + +def part_qaoa(backend: str) -> None: + W = np.array( + [[0, 1, 1, 0, 1], + [1, 0, 1, 1, 0], + [1, 1, 0, 1, 0], + [0, 1, 1, 0, 1], + [1, 0, 0, 1, 0]], + dtype=float, + ) + n_edges = int(W.sum() / 2) + rule(f"3. QAOA MaxCut vs brute force ({len(W)} nodes, {n_edges} edges, p=2, {backend})") + t0 = time.time() + result = sqx.QAOA(backend=backend, p=2, seed=7, maxiter=200).solve(W) + _, optimum = brute_force_maxcut(W) + print(f"QAOA best sampled cut : {result['bitstring']} value {result['cut_value']:.0f}") + print(f"Brute-force optimum : {result['classical_bitstring']} value {optimum:.0f}") + print(f"Expected cut of state : {result['expected_cut']:.3f} " + f"(approximation ratio {result['approximation_ratio']:.3f}; " + f"a random cut averages {n_edges / 2:.1f})") + print(f"Matches optimum : {'yes' if result['cut_value'] == optimum else 'NO'}" + f" ({result['n_evaluations']} circuit evaluations, {time.time() - t0:.1f}s)") + + +def main() -> int: + start = time.time() + print(f"SuperQuantX {sqx.__version__} showcase. All runs are local classical simulations.") + working = part_backends() + if not working: + print("No working backend found.") + return 1 + preferred = os.environ.get("SQX_QML_BACKEND", "pennylane") + qml_backend = preferred if preferred in working else working[0] + part_qml(qml_backend) + part_qaoa(qml_backend) + print(f"\nTotal time {time.time() - start:.1f}s") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/vqe_molecule.py b/examples/vqe_molecule.py index c255689..2c7ef1f 100644 --- a/examples/vqe_molecule.py +++ b/examples/vqe_molecule.py @@ -1,425 +1,50 @@ -""" -Variational Quantum Eigensolver (VQE) for molecular ground state calculation +#!/usr/bin/env python3 +"""VQE for the H2 molecule, checked against exact diagonalisation. + +Uses the built-in two-qubit H2 Hamiltonian (STO-3G, 0.735 Angstrom, parity +mapping with two-qubit reduction). Every energy is printed next to the exact +ground energy, so you can see the error directly. -This example demonstrates: -- Setting up VQE for molecular systems -- Defining molecular Hamiltonians -- Creating parameterized ansatz circuits -- Running VQE optimization -- Analyzing results and convergence +Run: + python examples/vqe_molecule.py + SQX_BACKENDS=simulator,pennylane,qiskit python examples/vqe_molecule.py """ -import matplotlib.pyplot as plt -import numpy as np +import os +import time -from superquantx import VQE, Hamiltonian, PauliString, QuantumCircuit, SuperQuantXClient +import superquantx as sqx from superquantx.algorithms import create_vqe_for_molecule -def hydrogen_molecule_hamiltonian(): - """ - Create Hamiltonian for H2 molecule in STO-3G basis - - This is a simplified 2-qubit Hamiltonian for H2 at equilibrium - bond distance (0.74 ร…) using Jordan-Wigner mapping. - """ - print("Creating H2 molecule Hamiltonian...") - - # H2 Hamiltonian coefficients (Hartree units) - pauli_terms = { - "II": -1.0523732, # Constant term - "ZI": -0.39793742, # Z โŠ— I - "IZ": -0.39793742, # I โŠ— Z - "ZZ": -0.01128010, # Z โŠ— Z - "XX": 0.18093119, # X โŠ— X - "YY": 0.18093119 # Y โŠ— Y - } - - pauli_strings = [] - for pauli_ops, coeff in pauli_terms.items(): - pauli_strings.append(PauliString(pauli_ops, coeff)) - - hamiltonian = Hamiltonian(pauli_strings) - print(f"Hamiltonian created with {len(pauli_strings)} terms") - print(f"Exact ground state energy: {hamiltonian.ground_state_energy():.6f} Hartree") - - return hamiltonian - - -def create_hardware_efficient_ansatz(num_qubits, num_layers): - """ - Create hardware-efficient ansatz for VQE - - Args: - num_qubits: Number of qubits - num_layers: Number of ansatz layers - - Returns: - Function that creates ansatz circuit from parameters - """ - def ansatz(parameters): - circuit = QuantumCircuit(num_qubits, name=f"HEA-L{num_layers}") - - param_idx = 0 - - for layer in range(num_layers): - # Single-qubit rotations - for qubit in range(num_qubits): - circuit.ry(parameters[param_idx], qubit) - param_idx += 1 - - # Entangling layer (linear connectivity) - for qubit in range(num_qubits - 1): - circuit.cnot(qubit, qubit + 1) - - # Final layer of single-qubit rotations - for qubit in range(num_qubits): - circuit.ry(parameters[param_idx], qubit) - param_idx += 1 - - return circuit - - # Calculate total number of parameters - total_params = num_qubits * (num_layers + 1) - print(f"Hardware-efficient ansatz created: {num_layers} layers, {total_params} parameters") - - return ansatz, total_params - - -def create_uccsd_ansatz(num_qubits): - """ - Create simplified UCCSD (Unitary Coupled Cluster) ansatz - - This is a simplified version focusing on single and double excitations - for educational purposes. - """ - def ansatz(parameters): - circuit = QuantumCircuit(num_qubits, name="UCCSD") - - # Initialize in Hartree-Fock state (|01โŸฉ for H2) - circuit.x(0) # Occupy first orbital - - # Single excitation: |01โŸฉ โ†’ |10โŸฉ - theta_single = parameters[0] - circuit.h(1) - circuit.cnot(1, 0) - circuit.rz(theta_single, 0) - circuit.cnot(1, 0) - circuit.h(1) - - # Double excitation: |01โŸฉ โ†’ |10โŸฉ (same as single for 2 qubits) - if len(parameters) > 1: - theta_double = parameters[1] - circuit.h(0) - circuit.h(1) - circuit.cnot(0, 1) - circuit.rz(theta_double, 1) - circuit.cnot(0, 1) - circuit.h(0) - circuit.h(1) - - return circuit - - print("UCCSD ansatz created for H2") - return ansatz - - -def run_vqe_simulation(hamiltonian, ansatz, num_params, client=None): - """ - Run VQE optimization using simulation - - Args: - hamiltonian: Target Hamiltonian - ansatz: Parameterized ansatz function - num_params: Number of parameters - client: SuperQuantX client (None for local simulation) - - Returns: - VQE results dictionary - """ - print(f"Running VQE with {'quantum hardware' if client else 'local simulation'}...") - - # Create VQE instance - vqe = VQE( - hamiltonian=hamiltonian, - ansatz=ansatz, - client=client, - optimizer="SLSQP", - max_iterations=100, - tolerance=1e-6 - ) - - # Initial parameters (small random values) - np.random.seed(42) # For reproducibility - initial_params = np.random.uniform(-0.1, 0.1, num_params) - - print(f"Starting optimization with {num_params} parameters...") - print(f"Initial parameters: {initial_params}") - - # Run VQE - results = vqe.run(initial_parameters=initial_params) - - # Display results - print("\nVQE Results:") - print(f"Optimal energy: {results['optimal_energy']:.6f} Hartree") - print(f"Optimal parameters: {results['optimal_parameters']}") - print(f"Converged: {results['converged']}") - print(f"Number of iterations: {results['num_iterations']}") - - # Calculate error - exact_energy = results['ground_state_energy_exact'] - error = abs(results['optimal_energy'] - exact_energy) - error_mhartree = error * 1000 # Convert to milliHartree - - print(f"Exact ground state energy: {exact_energy:.6f} Hartree") - print(f"VQE error: {error:.6f} Hartree ({error_mhartree:.3f} mHartree)") - - return results, vqe - - -def plot_vqe_convergence(vqe_results, title="VQE Convergence"): - """Plot VQE optimization convergence""" - history = vqe_results['optimization_history'] - exact_energy = vqe_results['ground_state_energy_exact'] - - plt.figure(figsize=(10, 6)) - - # Plot energy vs iteration - plt.subplot(1, 2, 1) - iterations = range(len(history)) - plt.plot(iterations, history, 'b-', label='VQE Energy') - plt.axhline(y=exact_energy, color='r', linestyle='--', label='Exact Energy') - plt.xlabel('Iteration') - plt.ylabel('Energy (Hartree)') - plt.title('Energy Convergence') - plt.legend() - plt.grid(True, alpha=0.3) - - # Plot error vs iteration - plt.subplot(1, 2, 2) - errors = [abs(energy - exact_energy) * 1000 for energy in history] # mHartree - plt.semilogy(iterations, errors, 'g-', label='Energy Error') - plt.xlabel('Iteration') - plt.ylabel('Error (mHartree)') - plt.title('Error Convergence (log scale)') - plt.legend() - plt.grid(True, alpha=0.3) - - plt.tight_layout() - plt.suptitle(title, y=1.02) - plt.show() - - return plt.gcf() - - -def compare_ansatze(hamiltonian, client=None): - """Compare different ansรคtze for VQE""" - print("\nComparing different ansรคtze...") - - results_comparison = {} - - # 1. Hardware Efficient Ansatz - hea_ansatz, hea_params = create_hardware_efficient_ansatz(2, 2) - hea_results, _ = run_vqe_simulation(hamiltonian, hea_ansatz, hea_params, client) - results_comparison['HEA (L=2)'] = hea_results - - # 2. UCCSD Ansatz - uccsd_ansatz = create_uccsd_ansatz(2) - uccsd_results, _ = run_vqe_simulation(hamiltonian, uccsd_ansatz, 2, client) - results_comparison['UCCSD'] = uccsd_results - - # 3. Simple Ansatz (1 layer HEA) - simple_ansatz, simple_params = create_hardware_efficient_ansatz(2, 1) - simple_results, _ = run_vqe_simulation(hamiltonian, simple_ansatz, simple_params, client) - results_comparison['HEA (L=1)'] = simple_results - - # Compare results - print("\nAnsatz Comparison:") - print("-" * 60) - print(f"{'Ansatz':<12} {'Energy (Ha)':<12} {'Error (mHa)':<12} {'Params':<8}") - print("-" * 60) - - exact_energy = hamiltonian.ground_state_energy() - - for name, results in results_comparison.items(): - energy = results['optimal_energy'] - error = abs(energy - exact_energy) * 1000 - num_params = len(results['optimal_parameters']) - print(f"{name:<12} {energy:<12.6f} {error:<12.3f} {num_params:<8}") - - return results_comparison - - -def benchmark_vqe_scaling(): - """Benchmark VQE scaling with problem size""" - print("\nBenchmarking VQE scaling...") - - # Create simple Hamiltonians of different sizes - scaling_results = {} - - for num_qubits in [2, 3, 4]: - print(f"\nTesting {num_qubits}-qubit system...") - - # Create simple Ising-like Hamiltonian - pauli_strings = [] - for i in range(num_qubits): - # Local Z terms - z_ops = ['I'] * num_qubits - z_ops[i] = 'Z' - pauli_strings.append(PauliString(''.join(z_ops), -0.5)) - - # Nearest-neighbor ZZ terms - if i < num_qubits - 1: - zz_ops = ['I'] * num_qubits - zz_ops[i] = 'Z' - zz_ops[i + 1] = 'Z' - pauli_strings.append(PauliString(''.join(zz_ops), -0.25)) - - hamiltonian = Hamiltonian(pauli_strings) - - # Use hardware-efficient ansatz - ansatz, num_params = create_hardware_efficient_ansatz(num_qubits, 2) - - # Run VQE (with fewer iterations for speed) - vqe = VQE(hamiltonian, ansatz, optimizer="SLSQP", max_iterations=50) - - initial_params = np.random.uniform(-0.1, 0.1, num_params) - results = vqe.run(initial_parameters=initial_params) - - scaling_results[num_qubits] = { - 'energy': results['optimal_energy'], - 'exact': results['ground_state_energy_exact'], - 'params': num_params, - 'iterations': results['num_iterations'] - } - - error = abs(results['optimal_energy'] - results['ground_state_energy_exact']) - print(f" Energy: {results['optimal_energy']:.6f} (error: {error*1000:.3f} mHa)") - print(f" Parameters: {num_params}, Iterations: {results['num_iterations']}") - - return scaling_results - - -def demonstrate_vqe_features(): - """Demonstrate advanced VQE features""" - print("\nDemonstrating advanced VQE features...") - - # Create H2 Hamiltonian - hamiltonian = hydrogen_molecule_hamiltonian() - - # Test parameter initialization strategies - print("\nTesting parameter initialization strategies...") - - ansatz, num_params = create_hardware_efficient_ansatz(2, 2) - - strategies = { - 'zeros': np.zeros(num_params), - 'random_small': np.random.uniform(-0.1, 0.1, num_params), - 'random_large': np.random.uniform(-np.pi, np.pi, num_params), - 'heuristic': np.array([0.1, -0.1, 0.05, -0.05, 0.02, 0.02]) # Based on chemistry intuition - } - - strategy_results = {} - - for strategy_name, initial_params in strategies.items(): - print(f"\nTesting {strategy_name} initialization...") - - vqe = VQE(hamiltonian, ansatz, max_iterations=50, tolerance=1e-6) - results = vqe.run(initial_parameters=initial_params) - - strategy_results[strategy_name] = results - - exact_energy = results['ground_state_energy_exact'] - error = abs(results['optimal_energy'] - exact_energy) * 1000 - - print(f" Final energy: {results['optimal_energy']:.6f} Hartree") - print(f" Error: {error:.3f} mHartree") - print(f" Converged: {results['converged']}") - print(f" Iterations: {results['num_iterations']}") - - return strategy_results - - -def main(): - """Main VQE example function""" - print("SuperQuantX VQE Molecular Ground State Example") - print("=" * 50) - - # Get API key (optional) - api_key = input("Enter your SuperQuantX API key (or press Enter for simulation only): ").strip() - client = SuperQuantXClient(api_key) if api_key else None - - # Example 1: Basic H2 VQE - print("\n1. Basic H2 VQE Example") - print("-" * 25) - - # Create H2 Hamiltonian - h2_hamiltonian = hydrogen_molecule_hamiltonian() - - # Use factory function - print("Using VQE factory function...") - vqe_h2 = create_vqe_for_molecule("H2", client=client) - h2_ground_energy = vqe_h2.find_ground_state() - - print(f"Factory VQE result: {h2_ground_energy:.6f} Hartree") - - # Example 2: Custom ansatz comparison - print("\n\n2. Ansatz Comparison") - print("-" * 20) - ansatz_results = compare_ansatze(h2_hamiltonian, client) - - # Example 3: VQE scaling - print("\n\n3. VQE Scaling Analysis") - print("-" * 23) - scaling_results = benchmark_vqe_scaling() - - # Example 4: Advanced features - print("\n\n4. Advanced VQE Features") - print("-" * 25) - demonstrate_vqe_features() - - # Example 5: Visualization (if matplotlib available) - try: - print("\n\n5. Visualization") - print("-" * 15) - - # Plot convergence for best ansatz - best_ansatz = min(ansatz_results.keys(), - key=lambda k: abs(ansatz_results[k]['optimal_energy'] - - h2_hamiltonian.ground_state_energy())) - - print(f"Plotting convergence for best ansatz: {best_ansatz}") - plot_vqe_convergence(ansatz_results[best_ansatz], - f"VQE Convergence - {best_ansatz}") - - # Save plot - plt.savefig('vqe_convergence.png', dpi=150, bbox_inches='tight') - print("Convergence plot saved as 'vqe_convergence.png'") - - except ImportError: - print("Matplotlib not available, skipping visualization") - - # Summary - print("\n\nSummary of Results:") - print("=" * 30) - - exact_energy = h2_hamiltonian.ground_state_energy() +CHEMICAL_ACCURACY = 1.6e-3 # Hartree, about 1 kcal/mol - print(f"H2 Ground State (Exact): {exact_energy:.6f} Hartree") - print(f"Factory VQE Result: {h2_results['optimal_energy']:.6f} Hartree") - print("\nBest ansatz results:") - for name, results in ansatz_results.items(): - error = abs(results['optimal_energy'] - exact_energy) * 1000 - print(f" {name}: {results['optimal_energy']:.6f} Ha (error: {error:.3f} mHa)") +def main() -> int: + backends = os.environ.get("SQX_BACKENDS", "simulator,pennylane").split(",") + print("H2 ground state with VQE (electronic energy, Hartree)") + print(f"{'backend':10s} {'ansatz':15s} {'VQE':>11s} {'exact':>11s} {'error':>9s} {'time':>6s}") - print("\nScaling results:") - for num_qubits, data in scaling_results.items(): - error = abs(data['energy'] - data['exact']) * 1000 - print(f" {num_qubits} qubits: {data['energy']:.6f} Ha (error: {error:.3f} mHa)") + failures = 0 + for backend in backends: + try: + sqx.get_backend(backend) + except Exception as e: # noqa: BLE001 + print(f"{backend:10s} skipped: {e}") + continue + for ansatz in ("RealAmplitudes", "EfficientSU2"): + t0 = time.time() + vqe = create_vqe_for_molecule("H2", backend=backend, ansatz=ansatz, seed=0) + energy = vqe.find_ground_state() + exact = vqe.exact_ground_energy() + error = abs(energy - exact) + failures += error > CHEMICAL_ACCURACY + print(f"{backend:10s} {ansatz:15s} {energy:11.6f} {exact:11.6f} " + f"{error:9.1e} {time.time() - t0:5.1f}s") - print("\nVQE examples completed successfully!") + print("\nTotal energy = electronic + 0.719969 Ha nuclear repulsion (exact -1.137306 Ha).") + return 1 if failures else 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/mkdocs.yml b/mkdocs.yml index a6ed129..293a6ed 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -63,6 +63,9 @@ plugins: paths: ["src"] options: docstring_style: google + docstring_options: + warn_missing_types: false + warn_unknown_params: false show_source: true show_bases: true show_inheritance_diagram: false @@ -142,10 +145,9 @@ extra_javascript: - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js nav: - - Home: + - Home: - Overview: index.md - - Quick Start: getting-started/quickstart.md - - Installation: getting-started/installation.md + - Showcase: showcase.md - Getting Started: - Installation Guide: getting-started/installation.md - Quick Start: getting-started/quickstart.md @@ -155,6 +157,7 @@ nav: - Overview: user-guide/overview.md - Quantum Backends: user-guide/backends.md - Algorithms: user-guide/algorithms.md + - Benchmarking: user-guide/benchmarking.md - Tutorials: - Basic Quantum Computing: tutorials/basic-quantum.md - Quantum Machine Learning: tutorials/quantum-ml.md @@ -174,6 +177,9 @@ nav: - Circuits: api/circuits.md - Agents: api/agents.md - Utilities: api/utilities.md + - Help: + - FAQ: help/faq.md + - Troubleshooting: help/troubleshooting.md - Development: - Contributing: development/contributing.md - Architecture: development/architecture.md diff --git a/pyproject.toml b/pyproject.toml index efcb618..5812ac9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,9 +77,9 @@ pennylane = [ "pennylane-lightning>=0.45.0", ] qiskit = [ - "qiskit>=2.0,<3", - "qiskit-aer>=0.17.0", - "qiskit-ibm-runtime>=0.49.0", + "qiskit>=2.6,<3", + "qiskit-aer>=0.18", + "qiskit-ibm-runtime>=0.50", ] cirq = [ "cirq>=1.7.0", @@ -101,6 +101,7 @@ dev = [ "pytest>=8.0.0", "pytest-cov>=4.1.0", "pytest-mock>=3.12.0", + "pytest-asyncio>=0.23.0", "pytest-xdist>=3.5.0", "pytest-benchmark>=4.0.0", "black>=24.0.0", diff --git a/src/superquantx/__init__.py b/src/superquantx/__init__.py index c2c5007..c6ada7a 100644 --- a/src/superquantx/__init__.py +++ b/src/superquantx/__init__.py @@ -1,31 +1,24 @@ -"""SuperQuantX: Experimental Quantum AI Research Platform. - -โš ๏ธ RESEARCH SOFTWARE WARNING: This is experimental research software developed by -SuperXLab (Superagentic AI Research Division). NOT intended for production use. -For research and educational purposes only. - -Part of SuperXLab's comprehensive quantum research program - the practical implementation -platform for validating theoretical research in: - ๐Ÿ”ฌ Quantum-Inspired Agentic Systems: Superposition, interference, entanglement in agents - ๐Ÿ”ฌ Quantum Neural Networks (QNNs): Hardware-validated quantum neural architectures - ๐Ÿ”ฌ QuantumML for AI Training: Quantum-accelerated machine learning techniques - ๐Ÿ”ฌ Quantinuum Integration: Real hardware validation on H-Series quantum computers - -Research Examples: - Experimental quantum agent research: - >>> import superquantx as sqx # EXPERIMENTAL - >>> agent = sqx.QuantumTradingAgent(strategy="quantum_portfolio", backend="simulator") - >>> results = agent.solve(research_data) # Research use only - >>> print(f"Research findings: {results.metadata}") - - Quantum neural network experiments: - >>> qnn = sqx.QuantumNN(architecture='hybrid', backend='pennylane') # EXPERIMENTAL - >>> qnn.fit(X_research, y_research) # Research data only - >>> analysis = qnn.analyze_expressivity() # Research analysis - - Quantum algorithm benchmarking: - >>> qsvm = sqx.QuantumSVM(backend='simulator') # EXPERIMENTAL - >>> benchmark = sqx.benchmark_algorithm(qsvm, classical_baseline) +"""SuperQuantX: experimental quantum machine learning research toolkit. + +Research software, not intended for production use. One API runs circuits +and algorithms on PennyLane, Qiskit, Cirq, Amazon Braket, pytket and a +built-in simulator, and every algorithm reports a classical reference. + +Examples: + Classifier against tuned classical baselines (arXiv:2610.42029 protocol): + >>> import superquantx as sqx + >>> from sklearn.datasets import make_moons + >>> X, y = make_moons(100, noise=0.2, random_state=0) + >>> result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend="simulator")) + >>> print(result.table()) + + H2 ground state, checked against exact diagonalisation: + >>> vqe = sqx.create_vqe_for_molecule("H2", backend="simulator") + >>> vqe.find_ground_state(), vqe.exact_ground_energy() + + Portfolio selection, checked against brute force: + >>> agent = sqx.QuantumPortfolioAgent(backend="simulator", n_select=3) + >>> agent.solve(returns).result["matches_classical_optimum"] """ import logging @@ -88,11 +81,14 @@ from .algorithms import ( QAOA, VQE, + BaseQuantumAlgorithm, HybridClassifier, QuantumKMeans, + QuantumNeuralNetwork, QuantumNN, QuantumPCA, QuantumSVM, + create_vqe_for_molecule, ) from .backends import ( BaseBackend, @@ -179,6 +175,8 @@ def __new__(cls, **kwargs): benchmark_algorithm = None QuantumFeatureMap = None +from .benchmarks import ComparisonResult, compare_to_classical + # Set up logging logging.getLogger(__name__).addHandler(logging.NullHandler()) @@ -195,71 +193,39 @@ def get_version() -> str: """Get SuperQuantX version.""" return __version__ -def get_backend_info() -> dict[str, Any]: - """Get information about available backends.""" - info = {} - - # Check which backends are available - try: - import pennylane - info['pennylane'] = pennylane.__version__ - except ImportError: - info['pennylane'] = None - - try: - import qiskit - info['qiskit'] = qiskit.__version__ - except ImportError: - info['qiskit'] = None - - try: - import cirq - info['cirq'] = cirq.__version__ - except ImportError: - info['cirq'] = None - - try: - import braket - info['braket'] = braket.__version__ - except ImportError: - info['braket'] = None - - try: - import azure.quantum - info['azure_quantum'] = azure.quantum.__version__ - except (ImportError, AttributeError): - info['azure_quantum'] = None - - try: - import pytket - info['pytket'] = pytket.__version__ - except ImportError: - info['pytket'] = None - - try: - import dwave - info['dwave'] = dwave.ocean.__version__ - except (ImportError, AttributeError): - info['dwave'] = None - - try: - import pyquil - info['pyquil'] = pyquil.__version__ - except ImportError: - info['pyquil'] = None - - try: - import tensorflow_quantum - info['tensorflow_quantum'] = tensorflow_quantum.__version__ - except ImportError: - info['tensorflow_quantum'] = None - - try: - import cuquantum - info['cuquantum'] = cuquantum.__version__ - except (ImportError, AttributeError): - info['cuquantum'] = None - +# Distribution names used to read installed versions without importing the +# (sometimes slow or side-effecting) backend packages themselves. +_BACKEND_DISTRIBUTIONS = { + 'pennylane': ('pennylane',), + 'qiskit': ('qiskit',), + 'cirq': ('cirq-core', 'cirq'), + 'braket': ('amazon-braket-sdk',), + 'azure_quantum': ('azure-quantum',), + 'pytket': ('pytket',), + 'dwave': ('dwave-ocean-sdk', 'dwave-system'), + 'pyquil': ('pyquil',), + 'tensorflow_quantum': ('tensorflow-quantum',), + 'cuquantum': ('cuquantum-python', 'cuquantum'), +} + + +def get_backend_info() -> dict[str, str | None]: + """Return the installed version of each backend SDK, or None if absent. + + Versions come from :mod:`importlib.metadata`, so a package that does not + define ``__version__`` (for example ``braket``) is still reported. + """ + from importlib.metadata import PackageNotFoundError, version + + info: dict[str, str | None] = {} + for key, dists in _BACKEND_DISTRIBUTIONS.items(): + info[key] = None + for dist in dists: + try: + info[key] = version(dist) + break + except PackageNotFoundError: + continue return info def print_system_info() -> None: @@ -362,6 +328,9 @@ def run_diagnostics() -> dict[str, dict[str, Any]]: "cli", # Common algorithms + "BaseQuantumAlgorithm", + "QuantumNeuralNetwork", + "create_vqe_for_molecule", "QuantumSVM", "QAOA", "VQE", @@ -401,5 +370,7 @@ def run_diagnostics() -> dict[str, dict[str, Any]]: "optimize_circuit", "visualize_results", "benchmark_algorithm", + "compare_to_classical", + "ComparisonResult", "QuantumFeatureMap", ] diff --git a/src/superquantx/algorithms.py b/src/superquantx/algorithms.py deleted file mode 100644 index 87d94a3..0000000 --- a/src/superquantx/algorithms.py +++ /dev/null @@ -1,864 +0,0 @@ -"""Quantum algorithms implementation for SuperQuantX -""" - -from abc import ABC, abstractmethod -from collections.abc import Callable -from typing import Any - -import numpy as np -from scipy.optimize import minimize -from sklearn.base import BaseEstimator - -from .circuits import QuantumCircuit -from .client import SuperQuantXClient -from .gates import Hamiltonian, PauliString - - -class QuantumAlgorithm(ABC): - """Base class for quantum algorithms - """ - - def __init__(self, client: SuperQuantXClient | None = None): - """Initialize quantum algorithm - - Args: - client: SuperQuantX client for quantum execution - - """ - self.client = client - self.result_history: list[dict[str, Any]] = [] - - @abstractmethod - def run(self, *args, **kwargs) -> dict[str, Any]: - """Execute the quantum algorithm""" - pass - - def set_client(self, client: SuperQuantXClient) -> None: - """Set the quantum client""" - self.client = client - - -class VQE(QuantumAlgorithm): - """Variational Quantum Eigensolver (VQE) for finding ground state energies - """ - - def __init__( - self, - hamiltonian: Hamiltonian, - ansatz: Callable[[np.ndarray], QuantumCircuit], - client: SuperQuantXClient | None = None, - optimizer: str = "SLSQP", - max_iterations: int = 1000, - tolerance: float = 1e-6 - ): - """Initialize VQE algorithm - - Args: - hamiltonian: Target Hamiltonian - ansatz: Parameterized quantum circuit ansatz - client: SuperQuantX client for execution - optimizer: Classical optimizer method - max_iterations: Maximum optimization iterations - tolerance: Convergence tolerance - - """ - super().__init__(client) - self.hamiltonian = hamiltonian - self.ansatz = ansatz - self.optimizer = optimizer - self.max_iterations = max_iterations - self.tolerance = tolerance - - self.optimal_parameters: np.ndarray | None = None - self.optimal_energy: float | None = None - self.optimization_history: list[float] = [] - - def cost_function(self, parameters: np.ndarray) -> float: - """VQE cost function: expectation value of Hamiltonian - - Args: - parameters: Ansatz parameters - - Returns: - Energy expectation value - - """ - circuit = self.ansatz(parameters) - - if self.client is None: - # Simulate locally - energy = self._simulate_expectation_value(circuit, self.hamiltonian) - else: - # Execute on quantum backend - energy = self._execute_expectation_value(circuit, self.hamiltonian) - - self.optimization_history.append(energy) - return energy - - def _simulate_expectation_value( - self, - circuit: QuantumCircuit, - hamiltonian: Hamiltonian - ) -> float: - """Simulate expectation value locally""" - # This is a simplified simulation - # In practice, would use a quantum simulator - state = self._simulate_circuit(circuit) - return float(np.real(hamiltonian.expectation_value(state))) - - def _simulate_circuit(self, circuit: QuantumCircuit) -> np.ndarray: - """Simulate quantum circuit to get final state""" - # Initialize state |0โŸฉ^n - state = np.zeros(2 ** circuit.num_qubits, dtype=complex) - state[0] = 1.0 - - # Apply gates (simplified simulation) - for gate in circuit.gates: - if gate.name == "RY" and len(gate.qubits) == 1: - # Apply single-qubit rotation - qubit = gate.qubits[0] - theta = gate.parameters[0] - - # Create rotation matrix for full system - from .gates import GateMatrix - gate_matrix = GateMatrix.ry(theta) - - # Apply to specific qubit (simplified) - state = self._apply_single_qubit_gate(state, gate_matrix, qubit, circuit.num_qubits) - elif gate.name == "CNOT" and len(gate.qubits) == 2: - # Apply CNOT gate - control, target = gate.qubits - state = self._apply_cnot(state, control, target, circuit.num_qubits) - - return state - - def _apply_single_qubit_gate( - self, - state: np.ndarray, - gate_matrix: np.ndarray, - qubit: int, - num_qubits: int - ) -> np.ndarray: - """Apply single-qubit gate to state vector""" - # This is a simplified implementation - # Would use more efficient tensor operations in practice - - dim = 2 ** num_qubits - new_state = np.zeros_like(state) - - for i in range(dim): - # Extract qubit state - qubit_state = (i >> qubit) & 1 - - for new_qubit_state in range(2): - # Apply gate matrix element - amplitude = gate_matrix[new_qubit_state, qubit_state] - if abs(amplitude) > 1e-12: - new_i = i ^ ((qubit_state ^ new_qubit_state) << qubit) - new_state[new_i] += amplitude * state[i] - - return new_state - - def _apply_cnot( - self, - state: np.ndarray, - control: int, - target: int, - num_qubits: int - ) -> np.ndarray: - """Apply CNOT gate to state vector""" - dim = 2 ** num_qubits - new_state = np.copy(state) - - for i in range(dim): - control_bit = (i >> control) & 1 - (i >> target) & 1 - - if control_bit == 1: - # Flip target bit - flipped_i = i ^ (1 << target) - new_state[i], new_state[flipped_i] = state[flipped_i], state[i] - - return new_state - - def _execute_expectation_value( - self, - circuit: QuantumCircuit, - hamiltonian: Hamiltonian - ) -> float: - """Execute expectation value measurement on quantum backend""" - if self.client is None: - raise ValueError("Client required for quantum execution") - - # Decompose Hamiltonian into measurable terms - total_expectation = 0.0 - - for pauli_string in hamiltonian.pauli_strings: - # Create measurement circuit for this Pauli string - measurement_circuit = self._create_measurement_circuit(circuit, pauli_string) - - # Execute circuit - job = self.client.submit_job_sync( - circuit_data=measurement_circuit.to_dict(), - shots=1024 - ) - result = self.client.wait_for_job_sync(job.job_id) - - # Calculate expectation value from measurement results - expectation = self._calculate_pauli_expectation(result.results, pauli_string) - total_expectation += expectation - - return total_expectation - - def _create_measurement_circuit( - self, - circuit: QuantumCircuit, - pauli_string: PauliString - ) -> QuantumCircuit: - """Create circuit with appropriate measurements for Pauli string""" - measurement_circuit = circuit.copy() - - # Add rotation gates to measure in correct basis - for i, pauli_op in enumerate(pauli_string.pauli_ops): - if pauli_op == 'X': - measurement_circuit.ry(-np.pi/2, i) # Rotate Yโ†’Z - elif pauli_op == 'Y': - measurement_circuit.rx(np.pi/2, i) # Rotate Xโ†’Z - # Z measurements don't need rotation - - # Measure all qubits - measurement_circuit.measure_all() - - return measurement_circuit - - def _calculate_pauli_expectation( - self, - measurement_results: dict[str, Any], - pauli_string: PauliString - ) -> float: - """Calculate expectation value from measurement results""" - counts = measurement_results.get("counts", {}) - shots = sum(counts.values()) - - if shots == 0: - return 0.0 - - expectation = 0.0 - - for bitstring, count in counts.items(): - # Calculate parity for non-identity Pauli operators - parity = 1 - for i, pauli_op in enumerate(pauli_string.pauli_ops): - if pauli_op != 'I' and i < len(bitstring): - bit = int(bitstring[-(i+1)]) # Reverse order - parity *= (-1) ** bit - - expectation += parity * count / shots - - return float(np.real(pauli_string.coefficient * expectation)) - - def run( - self, - initial_parameters: np.ndarray | None = None, - **optimizer_kwargs - ) -> dict[str, Any]: - """Run VQE optimization - - Args: - initial_parameters: Initial parameter values - **optimizer_kwargs: Additional optimizer parameters - - Returns: - VQE results dictionary - - """ - if initial_parameters is None: - # Random initialization - num_params = self._estimate_parameter_count() - initial_parameters = np.random.uniform(0, 2*np.pi, num_params) - - self.optimization_history = [] - - # Run classical optimization - result = minimize( - fun=self.cost_function, - x0=initial_parameters, - method=self.optimizer, - options={'maxiter': self.max_iterations, 'ftol': self.tolerance}, - **optimizer_kwargs - ) - - self.optimal_parameters = result.x - self.optimal_energy = result.fun - - return { - "optimal_energy": self.optimal_energy, - "optimal_parameters": self.optimal_parameters, - "optimization_history": self.optimization_history, - "converged": result.success, - "num_iterations": result.nit, - "ground_state_energy_exact": self.hamiltonian.ground_state_energy() - } - - def _estimate_parameter_count(self) -> int: - """Estimate number of parameters needed for ansatz""" - # This is a heuristic - would depend on specific ansatz - return self.hamiltonian.num_qubits * 2 - - -class QAOA(QuantumAlgorithm): - """Quantum Approximate Optimization Algorithm (QAOA) - """ - - def __init__( - self, - cost_hamiltonian: Hamiltonian, - mixer_hamiltonian: Hamiltonian | None = None, - p: int = 1, - client: SuperQuantXClient | None = None, - optimizer: str = "SLSQP" - ): - """Initialize QAOA - - Args: - cost_hamiltonian: Problem Hamiltonian - mixer_hamiltonian: Mixer Hamiltonian (default: X on all qubits) - p: Number of QAOA layers - client: SuperQuantX client - optimizer: Classical optimizer - - """ - super().__init__(client) - self.cost_hamiltonian = cost_hamiltonian - self.p = p - self.optimizer = optimizer - - # Default mixer: transverse field - if mixer_hamiltonian is None: - pauli_strings = [] - for i in range(cost_hamiltonian.num_qubits): - x_ops = ['I'] * cost_hamiltonian.num_qubits - x_ops[i] = 'X' - pauli_strings.append(PauliString(''.join(x_ops), 1.0)) - self.mixer_hamiltonian = Hamiltonian(pauli_strings) - else: - self.mixer_hamiltonian = mixer_hamiltonian - - def create_qaoa_circuit(self, parameters: np.ndarray) -> QuantumCircuit: - """Create QAOA circuit with given parameters - - Args: - parameters: [beta_1, gamma_1, beta_2, gamma_2, ...] for p layers - - Returns: - QAOA quantum circuit - - """ - if len(parameters) != 2 * self.p: - raise ValueError(f"Expected {2*self.p} parameters, got {len(parameters)}") - - circuit = QuantumCircuit(self.cost_hamiltonian.num_qubits) - - # Initialize in equal superposition - for i in range(circuit.num_qubits): - circuit.h(i) - - # Apply QAOA layers - for layer in range(self.p): - gamma = parameters[2*layer] - beta = parameters[2*layer + 1] - - # Apply cost Hamiltonian evolution: exp(-i ฮณ H_C) - self._apply_hamiltonian_evolution(circuit, self.cost_hamiltonian, gamma) - - # Apply mixer Hamiltonian evolution: exp(-i ฮฒ H_M) - self._apply_hamiltonian_evolution(circuit, self.mixer_hamiltonian, beta) - - return circuit - - def _apply_hamiltonian_evolution( - self, - circuit: QuantumCircuit, - hamiltonian: Hamiltonian, - time: float - ) -> None: - """Apply Hamiltonian time evolution to circuit""" - for pauli_string in hamiltonian.pauli_strings: - angle = 2 * time * np.real(pauli_string.coefficient) - self._apply_pauli_rotation(circuit, pauli_string.pauli_ops, angle) - - def _apply_pauli_rotation( - self, - circuit: QuantumCircuit, - pauli_ops: str, - angle: float - ) -> None: - """Apply Pauli string rotation to circuit""" - # Find qubits involved in non-identity operations - active_qubits = [i for i, op in enumerate(pauli_ops) if op != 'I'] - - if not active_qubits: - return # All identity, no rotation needed - - # Change basis for X and Y measurements - for i in active_qubits: - if pauli_ops[i] == 'X': - circuit.h(i) - elif pauli_ops[i] == 'Y': - circuit.rx(np.pi/2, i) - - # Apply ZZ...Z rotation using CNOT ladder - if len(active_qubits) == 1: - circuit.rz(angle, active_qubits[0]) - else: - # CNOT ladder - for i in range(len(active_qubits) - 1): - circuit.cnot(active_qubits[i], active_qubits[-1]) - - # Rotation on last qubit - circuit.rz(angle, active_qubits[-1]) - - # Reverse CNOT ladder - for i in reversed(range(len(active_qubits) - 1)): - circuit.cnot(active_qubits[i], active_qubits[-1]) - - # Reverse basis change - for i in active_qubits: - if pauli_ops[i] == 'X': - circuit.h(i) - elif pauli_ops[i] == 'Y': - circuit.rx(-np.pi/2, i) - - def cost_function(self, parameters: np.ndarray) -> float: - """QAOA cost function""" - circuit = self.create_qaoa_circuit(parameters) - - if self.client is None: - # Simulate locally - state = self._simulate_circuit(circuit) - energy = float(np.real(self.cost_hamiltonian.expectation_value(state))) - else: - # Execute on quantum backend - energy = self._execute_expectation_value(circuit, self.cost_hamiltonian) - - return energy - - def _simulate_circuit(self, circuit: QuantumCircuit) -> np.ndarray: - """Simulate QAOA circuit""" - # Simplified simulation - would use proper quantum simulator - return np.ones(2 ** circuit.num_qubits, dtype=complex) / np.sqrt(2 ** circuit.num_qubits) - - def _execute_expectation_value( - self, - circuit: QuantumCircuit, - hamiltonian: Hamiltonian - ) -> float: - """Execute expectation value on quantum backend""" - # Similar to VQE implementation - return 0.0 # Placeholder - - def run( - self, - initial_parameters: np.ndarray | None = None, - **optimizer_kwargs - ) -> dict[str, Any]: - """Run QAOA optimization - - Args: - initial_parameters: Initial [beta, gamma] parameters - **optimizer_kwargs: Additional optimizer options - - Returns: - QAOA results - - """ - if initial_parameters is None: - # Random initialization - initial_parameters = np.random.uniform(0, 2*np.pi, 2*self.p) - - result = minimize( - fun=self.cost_function, - x0=initial_parameters, - method=self.optimizer, - **optimizer_kwargs - ) - - optimal_circuit = self.create_qaoa_circuit(result.x) - - return { - "optimal_energy": result.fun, - "optimal_parameters": result.x, - "optimal_circuit": optimal_circuit, - "converged": result.success, - "num_iterations": result.nit - } - - -class QuantumNeuralNetwork(BaseEstimator): - """Quantum Neural Network for machine learning tasks - """ - - def __init__( - self, - num_qubits: int, - num_layers: int = 2, - entangling_gates: str = "CNOT", - client: SuperQuantXClient | None = None, - optimizer: str = "SLSQP", - learning_rate: float = 0.01 - ): - """Initialize Quantum Neural Network - - Args: - num_qubits: Number of qubits - num_layers: Number of variational layers - entangling_gates: Type of entangling gates - client: SuperQuantX client - optimizer: Classical optimizer - learning_rate: Learning rate for optimization - - """ - self.num_qubits = num_qubits - self.num_layers = num_layers - self.entangling_gates = entangling_gates - self.client = client - self.optimizer = optimizer - self.learning_rate = learning_rate - - # Calculate number of parameters - self.num_parameters = num_qubits * num_layers * 3 # 3 rotation angles per qubit per layer - self.parameters: np.ndarray | None = None - - self.is_fitted_ = False - - def create_ansatz(self, parameters: np.ndarray, x: np.ndarray | None = None) -> QuantumCircuit: - """Create parameterized quantum circuit ansatz - - Args: - parameters: Variational parameters - x: Input data for encoding (optional) - - Returns: - Quantum circuit - - """ - circuit = QuantumCircuit(self.num_qubits) - - # Data encoding (amplitude encoding) - if x is not None: - self._encode_data(circuit, x) - - param_idx = 0 - for layer in range(self.num_layers): - # Parameterized single-qubit rotations - for qubit in range(self.num_qubits): - circuit.rx(parameters[param_idx], qubit) - circuit.ry(parameters[param_idx + 1], qubit) - circuit.rz(parameters[param_idx + 2], qubit) - param_idx += 3 - - # Entangling gates - if layer < self.num_layers - 1: # No entangling on last layer - self._add_entangling_layer(circuit) - - return circuit - - def _encode_data(self, circuit: QuantumCircuit, x: np.ndarray) -> None: - """Encode classical data into quantum circuit""" - # Simple angle encoding - for i, value in enumerate(x[:self.num_qubits]): - circuit.ry(value, i) - - def _add_entangling_layer(self, circuit: QuantumCircuit) -> None: - """Add entangling gates between qubits""" - if self.entangling_gates == "CNOT": - for i in range(self.num_qubits - 1): - circuit.cnot(i, i + 1) - elif self.entangling_gates == "CZ": - for i in range(self.num_qubits - 1): - circuit.cz(i, i + 1) - else: - raise ValueError(f"Unknown entangling gates: {self.entangling_gates}") - - def forward(self, X: np.ndarray, parameters: np.ndarray) -> np.ndarray: - """Forward pass through quantum neural network - - Args: - X: Input data - parameters: Network parameters - - Returns: - Output predictions - - """ - predictions = [] - - for x in X: - circuit = self.create_ansatz(parameters, x) - - # Add measurement - circuit.measure(0, 0) # Measure first qubit - - if self.client is None: - # Simulate locally - prob_0 = self._simulate_measurement_probability(circuit) - else: - # Execute on quantum backend - prob_0 = self._execute_measurement_probability(circuit) - - # Convert probability to prediction - prediction = 2 * prob_0 - 1 # Map [0,1] to [-1,1] - predictions.append(prediction) - - return np.array(predictions) - - def _simulate_measurement_probability(self, circuit: QuantumCircuit) -> float: - """Simulate measurement probability""" - # Simplified simulation - return 0.5 # Placeholder - - def _execute_measurement_probability(self, circuit: QuantumCircuit) -> float: - """Execute measurement on quantum backend""" - if self.client is None: - raise ValueError("Client required for quantum execution") - - job = self.client.submit_job_sync( - circuit_data=circuit.to_dict(), - shots=1024 - ) - result = self.client.wait_for_job_sync(job.job_id) - - counts = result.results.get("counts", {}) - total_shots = sum(counts.values()) - - # Probability of measuring |0โŸฉ - prob_0 = counts.get("0", 0) / total_shots if total_shots > 0 else 0.5 - return prob_0 - - def loss_function(self, parameters: np.ndarray, X: np.ndarray, y: np.ndarray) -> float: - """Calculate loss function""" - predictions = self.forward(X, parameters) - # Mean squared error - return np.mean((predictions - y) ** 2) - - def fit(self, X: np.ndarray, y: np.ndarray) -> "QuantumNeuralNetwork": - """Fit the quantum neural network - - Args: - X: Training data - y: Training labels - - Returns: - Fitted model - - """ - # Initialize parameters - initial_parameters = np.random.uniform(0, 2*np.pi, self.num_parameters) - - # Optimize parameters - result = minimize( - fun=lambda params: self.loss_function(params, X, y), - x0=initial_parameters, - method=self.optimizer - ) - - self.parameters = result.x - self.is_fitted_ = True - - return self - - def predict(self, X: np.ndarray) -> np.ndarray: - """Make predictions - - Args: - X: Input data - - Returns: - Predictions - - """ - if not self.is_fitted_: - raise ValueError("Model must be fitted before making predictions") - - return self.forward(X, self.parameters) - - def score(self, X: np.ndarray, y: np.ndarray) -> float: - """Calculate Rยฒ score - - Args: - X: Test data - y: True labels - - Returns: - Rยฒ score - - """ - predictions = self.predict(X) - ss_res = np.sum((y - predictions) ** 2) - ss_tot = np.sum((y - np.mean(y)) ** 2) - return 1 - (ss_res / ss_tot) if ss_tot != 0 else 0.0 - - -class QuantumFourierTransform(QuantumAlgorithm): - """Quantum Fourier Transform implementation - """ - - def __init__(self, num_qubits: int, client: SuperQuantXClient | None = None): - """Initialize QFT - - Args: - num_qubits: Number of qubits - client: SuperQuantX client - - """ - super().__init__(client) - self.num_qubits = num_qubits - - def create_qft_circuit(self, inverse: bool = False) -> QuantumCircuit: - """Create QFT circuit - - Args: - inverse: Whether to create inverse QFT - - Returns: - QFT circuit - - """ - circuit = QuantumCircuit(self.num_qubits) - - if inverse: - # Inverse QFT: reverse the forward QFT - qft_circuit = self.create_qft_circuit(inverse=False) - return qft_circuit.inverse() - - # Forward QFT - for j in range(self.num_qubits): - # Apply Hadamard - circuit.h(j) - - # Apply controlled phase rotations - for k in range(j + 1, self.num_qubits): - angle = np.pi / (2 ** (k - j)) - circuit.crz(angle, k, j) - - # Reverse qubit order - for i in range(self.num_qubits // 2): - circuit.swap(i, self.num_qubits - 1 - i) - - return circuit - - def run(self, initial_state: np.ndarray | None = None) -> dict[str, Any]: - """Execute QFT - - Args: - initial_state: Initial quantum state - - Returns: - QFT results - - """ - circuit = self.create_qft_circuit() - - if self.client is None: - # Local simulation - if initial_state is None: - initial_state = np.zeros(2 ** self.num_qubits, dtype=complex) - initial_state[0] = 1.0 - - # Apply QFT (simplified) - fourier_state = np.fft.fft(initial_state) / np.sqrt(len(initial_state)) - - return { - "circuit": circuit, - "initial_state": initial_state, - "fourier_state": fourier_state - } - else: - # Execute on quantum backend - job = self.client.submit_job_sync(circuit_data=circuit.to_dict()) - result = self.client.wait_for_job_sync(job.job_id) - - return { - "circuit": circuit, - "job_result": result - } - - -# Factory functions for common algorithms -def create_vqe_for_molecule( - molecule_name: str, - basis_set: str = "sto-3g", - client: SuperQuantXClient | None = None -) -> VQE: - """Create VQE instance for molecular ground state calculation - - Args: - molecule_name: Molecule identifier (e.g., "H2", "LiH") - basis_set: Quantum chemistry basis set - client: SuperQuantX client - - Returns: - Configured VQE instance - - """ - # This would interface with quantum chemistry libraries - # For now, create a simple Hamiltonian - - if molecule_name.upper() == "H2": - # Simple H2 Hamiltonian (placeholder) - hamiltonian = Hamiltonian.from_dict({ - "ZZ": -1.0523732, - "ZI": -0.39793742, - "IZ": -0.39793742, - "XX": -0.01128010, - "YY": 0.01128010 - }) - - def h2_ansatz(params): - circuit = QuantumCircuit(2) - circuit.h(0) - circuit.h(1) - circuit.ry(params[0], 0) - circuit.ry(params[1], 1) - circuit.cnot(0, 1) - return circuit - - return VQE(hamiltonian, h2_ansatz, client) - - else: - raise ValueError(f"Molecule {molecule_name} not implemented") - - -def create_qaoa_for_max_cut( - graph_edges: list[tuple[int, int]], - num_nodes: int, - p: int = 1, - client: SuperQuantXClient | None = None -) -> QAOA: - """Create QAOA instance for Max-Cut problem - - Args: - graph_edges: List of graph edges as (node1, node2) tuples - num_nodes: Number of nodes in graph - p: QAOA depth parameter - client: SuperQuantX client - - Returns: - Configured QAOA instance - - """ - # Build Max-Cut Hamiltonian - pauli_strings = [] - - for edge in graph_edges: - i, j = edge - if i < num_nodes and j < num_nodes: - # Add ZZ term for edge (i,j) - zz_ops = ['I'] * num_nodes - zz_ops[i] = 'Z' - zz_ops[j] = 'Z' - pauli_strings.append(PauliString(''.join(zz_ops), 0.5)) - - cost_hamiltonian = Hamiltonian(pauli_strings) - - return QAOA(cost_hamiltonian, p=p, client=client) diff --git a/src/superquantx/algorithms/base_algorithm.py b/src/superquantx/algorithms/base_algorithm.py index b6205c5..8786108 100644 --- a/src/superquantx/algorithms/base_algorithm.py +++ b/src/superquantx/algorithms/base_algorithm.py @@ -369,11 +369,14 @@ def __init__(self, *args, **kwargs): self.optimal_value_ = None self.optimization_history_ = [] - def optimize(self, objective_function, initial_params: np.ndarray | None = None, **kwargs) -> QuantumResult: + def optimize(self, objective_function=None, initial_params: np.ndarray | None = None, **kwargs) -> QuantumResult: """Optimize objective function. + Failures are reported in ``QuantumResult.error`` (and ``result`` is None); + callers should check it. + Args: - objective_function: Function to optimize + objective_function: Function to optimize (None uses the algorithm's own) initial_params: Initial parameter values **kwargs: Additional optimization parameters @@ -389,7 +392,7 @@ def optimize(self, objective_function, initial_params: np.ndarray | None = None, return QuantumResult( result=result, metadata={ - 'converged': True, + 'converged': bool(result.get('success', True)) if isinstance(result, dict) else True, 'n_iterations': len(self.optimization_history_), 'final_cost': self.optimal_value_, }, diff --git a/src/superquantx/algorithms/qaoa.py b/src/superquantx/algorithms/qaoa.py index acfd9e3..8a3c26d 100644 --- a/src/superquantx/algorithms/qaoa.py +++ b/src/superquantx/algorithms/qaoa.py @@ -11,11 +11,35 @@ import numpy as np from scipy.optimize import minimize +from ..backends.base_backend import maxcut_values from .base_algorithm import OptimizationQuantumAlgorithm logger = logging.getLogger(__name__) + +def brute_force_maxcut(adjacency: np.ndarray) -> tuple[np.ndarray, float]: + """Classical exact MaxCut by enumerating all 2^n partitions. + + Returns the best bitstring (entry i is the side of node i) and its cut value. + Practical up to roughly 20 nodes. + """ + W = np.asarray(adjacency, dtype=float) + n = W.shape[0] + values = maxcut_values(W) + best = int(np.argmax(values)) + bits = np.array([(best >> (n - 1 - i)) & 1 for i in range(n)]) + return bits, float(values[best]) + + +def cut_value(adjacency: np.ndarray, bits: np.ndarray) -> float: + """Cut value of a partition given as a 0/1 array.""" + W = np.asarray(adjacency, dtype=float) + bits = np.asarray(bits).astype(int) + diff = bits[:, None] != bits[None, :] + return float(np.sum(np.triu(W, 1) * diff)) + + class QAOA(OptimizationQuantumAlgorithm): """Quantum Approximate Optimization Algorithm for combinatorial optimization. @@ -59,11 +83,13 @@ def __init__( optimizer: str = 'COBYLA', shots: int = 1024, maxiter: int = 1000, + n_restarts: int = 3, **kwargs ) -> None: super().__init__(backend=backend, shots=shots, **kwargs) self.p = p + self.n_restarts = n_restarts self.problem_hamiltonian = problem_hamiltonian self.mixer_hamiltonian = mixer_hamiltonian or self._default_mixer self.initial_state = initial_state @@ -82,112 +108,36 @@ def __init__( logger.info(f"Initialized QAOA with p={p}, optimizer={optimizer}") def _default_mixer(self, beta: float) -> Any: - """Default X-mixer Hamiltonian.""" - if hasattr(self.backend, 'create_mixer_hamiltonian'): - return self.backend.create_mixer_hamiltonian(beta, self.n_qubits) - else: - return self._fallback_mixer(beta) - - def _fallback_mixer(self, beta: float) -> Any: - """Fallback mixer implementation.""" - logger.warning("Using fallback mixer implementation") - return None - - def _create_initial_state(self) -> Any: - """Create initial quantum state.""" - if self.initial_state == 'uniform_superposition': - if hasattr(self.backend, 'create_uniform_superposition'): - return self.backend.create_uniform_superposition(self.n_qubits) - else: - return self._fallback_initial_state() - else: - return self.initial_state - - def _fallback_initial_state(self) -> Any: - """Fallback initial state preparation.""" - logger.warning("Using fallback initial state") - return None + """Marker for the standard transverse-field (RX) mixer built by the backend.""" + return 'x_mixer' def _create_qaoa_circuit(self, params: np.ndarray) -> Any: - """Create QAOA circuit with given parameters. - - Args: - params: Array of [gamma_1, beta_1, ..., gamma_p, beta_p] - - Returns: - Quantum circuit - - """ + """Create the QAOA circuit for params ``[gamma_1..gamma_p, beta_1..beta_p]``.""" + params = np.asarray(params, dtype=float) if len(params) != 2 * self.p: raise ValueError(f"Expected {2*self.p} parameters, got {len(params)}") - - gammas = params[:self.p] - betas = params[self.p:] - - try: - if hasattr(self.backend, 'create_qaoa_circuit'): - return self.backend.create_qaoa_circuit( - n_qubits=self.n_qubits, - gammas=gammas, - betas=betas, - problem_hamiltonian=self.problem_hamiltonian, - mixer_hamiltonian=self.mixer_hamiltonian, - initial_state=self._create_initial_state(), - problem_instance=self.problem_instance - ) - else: - return self._fallback_circuit(gammas, betas) - except Exception as e: - logger.error(f"Failed to create QAOA circuit: {e}") - return self._fallback_circuit(gammas, betas) - - def _fallback_circuit(self, gammas: np.ndarray, betas: np.ndarray) -> Any: - """Fallback circuit implementation.""" - logger.warning("Using fallback QAOA circuit") - return None + return self.backend.create_qaoa_circuit( + n_qubits=self.n_qubits, + gammas=params[:self.p], + betas=params[self.p:], + problem_hamiltonian=self.problem_hamiltonian, + mixer_hamiltonian=self.mixer_hamiltonian, + initial_state=self.initial_state, + problem_instance=self.problem_instance, + ) def _objective_function(self, params: np.ndarray) -> float: - """QAOA objective function to minimize. - - Args: - params: Circuit parameters - - Returns: - Negative expectation value (for minimization) - - """ - try: - # Create circuit with current parameters - circuit = self._create_qaoa_circuit(params) - - # Execute circuit and get measurement results - if hasattr(self.backend, 'execute_qaoa'): - expectation = self.backend.execute_qaoa( - circuit, - self.problem_hamiltonian, - self.problem_instance, - shots=self.shots - ) - else: - expectation = self._fallback_execution(circuit) - - # Store optimization history - self.optimization_history_.append({ - 'params': params.copy(), - 'cost': expectation, - 'iteration': len(self.optimization_history_) - }) - - return -expectation # Negative for minimization - - except Exception as e: - logger.error(f"Error in objective function: {e}") - return float('inf') - - def _fallback_execution(self, circuit: Any) -> float: - """Fallback circuit execution.""" - logger.warning("Using fallback circuit execution") - return np.random.random() # Placeholder + """Negative expected cut value of the QAOA state (minimised by scipy).""" + circuit = self._create_qaoa_circuit(params) + expectation = float(self.backend.execute_qaoa( + circuit, self.problem_hamiltonian, self.problem_instance, shots=self.shots + )) + self.optimization_history_.append({ + 'params': np.array(params, copy=True), + 'cost': expectation, + 'iteration': len(self.optimization_history_), + }) + return -expectation def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QAOA': """Fit QAOA to problem instance. @@ -213,44 +163,49 @@ def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QAOA': return self def _infer_qubits(self, problem_instance: np.ndarray) -> int: - """Infer number of qubits from problem instance.""" - if len(problem_instance.shape) == 2: - # Assume square matrix (e.g., graph adjacency matrix) - return problem_instance.shape[0] - else: - # Assume 1D problem encoding - return int(np.ceil(np.log2(len(problem_instance)))) - - def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Get optimal solution from QAOA results. - - Args: - X: Problem instance (not used if same as training) - **kwargs: Additional parameters + """One qubit per node of the (square) adjacency matrix.""" + problem_instance = np.asarray(problem_instance) + if problem_instance.ndim != 2 or problem_instance.shape[0] != problem_instance.shape[1]: + raise ValueError( + "QAOA currently solves weighted MaxCut: pass a square adjacency matrix" + ) + return problem_instance.shape[0] - Returns: - Optimal bit string solution + def predict(self, X: np.ndarray | None = None, **kwargs) -> np.ndarray: + """Sample the optimised circuit and return the best sampled partition. + Entry i of the returned 0/1 array is the side of node i. """ - if not self.is_fitted or not self.optimal_params_: + if not self.is_fitted or self.optimal_params_ is None: raise ValueError("QAOA must be fitted and optimized before prediction") - - # Create circuit with optimal parameters circuit = self._create_qaoa_circuit(self.optimal_params_) + samples = self.backend.sample_circuit(circuit, shots=self.shots) + unique = np.unique(samples, axis=0) + values = [cut_value(self.problem_instance, row) for row in unique] + return unique[int(np.argmax(values))] - # Sample from the optimized quantum state - if hasattr(self.backend, 'sample_circuit'): - samples = self.backend.sample_circuit(circuit, shots=self.shots) - # Return most frequent bit string - unique, counts = np.unique(samples, axis=0, return_counts=True) - best_solution = unique[np.argmax(counts)] - else: - # Fallback: return random solution - best_solution = np.random.randint(0, 2, self.n_qubits) + def solve(self, adjacency: np.ndarray) -> dict[str, Any]: + """Fit, optimise and sample in one call, with an exact classical check. - return best_solution + Returns the QAOA partition and cut, the brute-force optimum, and the + approximation ratio of the expected QAOA cut. + """ + self.fit(np.asarray(adjacency, dtype=float)) + result = self._run_optimization(None) + bits = self.predict() + best_bits, best_cut = brute_force_maxcut(self.problem_instance) + return { + 'bitstring': ''.join(str(int(b)) for b in bits), + 'cut_value': cut_value(self.problem_instance, bits), + 'expected_cut': self.optimal_value_, + 'classical_bitstring': ''.join(str(int(b)) for b in best_bits), + 'classical_optimum': best_cut, + 'approximation_ratio': self.optimal_value_ / best_cut if best_cut else float('nan'), + 'optimal_params': self.optimal_params_, + 'n_evaluations': result['n_iterations'], + } - def _run_optimization(self, objective_function, initial_params: np.ndarray | None = None, **kwargs): + def _run_optimization(self, objective_function=None, initial_params: np.ndarray | None = None, **kwargs): """Run QAOA optimization. Args: @@ -265,53 +220,42 @@ def _run_optimization(self, objective_function, initial_params: np.ndarray | Non if not self.is_fitted: raise ValueError("QAOA must be fitted before optimization") - # Use provided initial parameters or generate random ones - if initial_params is None: - initial_params = self._generate_initial_params() - - logger.info(f"Starting QAOA optimization with {len(initial_params)} parameters") - - # Set up parameter bounds - bounds = [] - for i in range(self.p): - bounds.append(self.gamma_bounds) # gamma bounds - for i in range(self.p): - bounds.append(self.beta_bounds) # beta bounds + bounds = [self.gamma_bounds] * self.p + [self.beta_bounds] * self.p + rng = np.random.default_rng(self.seed) + starts = [np.asarray(initial_params, dtype=float)] if initial_params is not None else [] + while len(starts) < max(1, self.n_restarts): + starts.append(self._generate_initial_params(rng)) - # Run classical optimization - try: + best = None + total_evals = 0 + for x0 in starts: result = minimize( fun=self._objective_function, - x0=initial_params, + x0=x0, method=self.optimizer, bounds=bounds, - options={ - 'maxiter': self.maxiter, - 'disp': True - } + options={'maxiter': self.maxiter, 'disp': False}, ) + total_evals += result.nfev + if best is None or result.fun < best.fun: + best = result - self.optimal_params_ = result.x - self.optimal_value_ = -result.fun # Convert back from minimization - - logger.info(f"QAOA optimization completed. Best value: {self.optimal_value_:.6f}") - - return { - 'optimal_params': self.optimal_params_, - 'optimal_value': self.optimal_value_, - 'success': result.success, - 'message': result.message, - 'n_iterations': result.nfev, - } - - except Exception as e: - logger.error(f"QAOA optimization failed: {e}") - raise + self.optimal_params_ = best.x + self.optimal_value_ = -float(best.fun) + logger.info("QAOA optimization completed. Expected cut: %.6f", self.optimal_value_) + return { + 'optimal_params': self.optimal_params_, + 'optimal_value': self.optimal_value_, + 'success': bool(best.success), + 'message': best.message, + 'n_iterations': total_evals, + } - def _generate_initial_params(self) -> np.ndarray: + def _generate_initial_params(self, rng: np.random.Generator | None = None) -> np.ndarray: """Generate random initial parameters.""" - gammas = np.random.uniform(*self.gamma_bounds, self.p) - betas = np.random.uniform(*self.beta_bounds, self.p) + rng = rng or np.random.default_rng(self.seed) + gammas = rng.uniform(*self.gamma_bounds, self.p) + betas = rng.uniform(*self.beta_bounds, self.p) return np.concatenate([gammas, betas]) def get_optimization_landscape(self, param_range: tuple[float, float], resolution: int = 50) -> dict[str, Any]: @@ -356,7 +300,7 @@ def analyze_solution_quality(self, true_optimum: float | None = None) -> dict[st Analysis results """ - if not self.optimal_value_: + if self.optimal_value_ is None: raise ValueError("No optimal solution available") analysis = { diff --git a/src/superquantx/algorithms/quantum_agents.py b/src/superquantx/algorithms/quantum_agents.py index f60f513..869537e 100644 --- a/src/superquantx/algorithms/quantum_agents.py +++ b/src/superquantx/algorithms/quantum_agents.py @@ -1,28 +1,36 @@ -"""Quantum Agentic AI: Autonomous quantum-enhanced intelligent systems. - -This module implements autonomous quantum agents that can independently make -decisions, optimize complex problems, and adapt their behavior based on quantum -advantages. These agents represent the next evolution of AI - systems that -leverage quantum computing to achieve superhuman performance in specialized domains. - -Key Agent Types: -- QuantumTradingAgent: Autonomous financial trading with quantum portfolio optimization -- QuantumResearchAgent: Scientific discovery and hypothesis generation -- QuantumOptimizationAgent: General combinatorial and continuous optimization -- QuantumClassificationAgent: Automated ML with quantum-classical ensemble methods - -Each agent combines multiple quantum algorithms, classical AI techniques, and -autonomous decision-making capabilities to solve complex real-world problems -without human intervention. +"""Quantum agents: task-level wrappers around the quantum algorithms. + +An agent bundles one or more quantum algorithms for a problem domain and, +crucially, always reports a classical baseline next to the quantum answer. +No agent in this module reports a "quantum advantage": every number it returns +is either computed by a (classically simulated) quantum circuit or by an exact +classical method run in the same call, and the two are labelled as such. + +Agents: + +* :class:`QuantumPortfolioAgent`: pick ``k`` of ``n`` assets by minimising a + mean-variance QUBO with VQE; checked against brute force and a classical + Markowitz solution. +* :class:`QuantumClassificationAgent`: trains quantum classifiers and + benchmarks them against tuned classical models with + :func:`superquantx.benchmarks.compare_to_classical`. +* :class:`QuantumOptimizationAgent`: weighted MaxCut with QAOA (checked by + brute force) or ground-state search with VQE (checked by exact + diagonalisation). +* :class:`QuantumTradingAgent` and :class:`QuantumResearchAgent`: experimental. + Only the parts backed by real computation are implemented; everything else + raises ``NotImplementedError``. """ +from __future__ import annotations + import logging import time from abc import ABC, abstractmethod -from collections.abc import Callable from typing import Any import numpy as np +from scipy.optimize import minimize from sklearn.metrics import accuracy_score from .base_algorithm import BaseQuantumAlgorithm, QuantumResult @@ -30,23 +38,20 @@ from .qaoa import QAOA from .quantum_nn import QuantumNN from .quantum_svm import QuantumSVM -from .vqe import VQE +from .vqe import H2_STO3G_0735, VQE logger = logging.getLogger(__name__) + class QuantumAgent(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. - Args: backend: Quantum backend for circuit execution agent_config: Configuration dictionary for the agent shots: Number of measurement shots - **kwargs: Additional parameters + **kwargs: Additional parameters (for example ``seed``) """ @@ -58,34 +63,28 @@ def __init__( **kwargs ) -> None: super().__init__(backend=backend, shots=shots, **kwargs) - self.agent_config = agent_config or {} - self.algorithms = {} - self.results_history = [] - self.performance_metrics = {} - + self.algorithms: dict[str, Any] = {} + self.results_history: list[Any] = [] + self.performance_metrics: dict[str, Any] = {} self._initialize_agent() - - logger.info(f"Initialized {self.__class__.__name__}") + logger.info("Initialized %s", self.__class__.__name__) @abstractmethod def _initialize_agent(self) -> None: """Initialize agent-specific algorithms and configurations.""" - pass @abstractmethod def solve(self, problem_instance: Any, **kwargs) -> QuantumResult: - """Solve a problem using the quantum agent. - - Args: - problem_instance: Problem data/specification - **kwargs: Additional solving parameters - - Returns: - Solution result - - """ - pass + """Solve a problem using the quantum agent.""" + + def _result(self, result: dict[str, Any], start: float, **metadata) -> QuantumResult: + return QuantumResult( + result=result, + metadata=metadata, + execution_time=time.time() - start, + backend_info=self.get_circuit_info(), + ) def get_agent_info(self) -> dict[str, Any]: """Get information about the agent and its algorithms.""" @@ -97,319 +96,239 @@ def get_agent_info(self) -> dict[str, Any]: 'performance_metrics': self.performance_metrics, } -class QuantumPortfolioAgent(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. +# --------------------------------------------------------------------------- +# Portfolio selection +# --------------------------------------------------------------------------- + +def portfolio_qubo_values(mu: np.ndarray, sigma: np.ndarray, k: int, + risk_aversion: float = 1.0, penalty: float | None = None) -> np.ndarray: + """Objective of every asset selection, indexed by big-endian bitstring. + + For selection ``x`` (``x_i = 1`` means asset i is held, equal weight ``1/k``): + + f(x) = risk_aversion * x^T Sigma x / k^2 - mu^T x / k + penalty * (sum(x) - k)^2 + + The penalty enforces holding exactly ``k`` assets. By default it is 1.5 times + the spread of the unpenalised objective, which is the smallest safe choice + and keeps the energy landscape well scaled for VQE. + """ + mu = np.asarray(mu, dtype=float) + sigma = np.asarray(sigma, dtype=float) + n = len(mu) + idx = np.arange(2 ** n) + X = ((idx[:, None] >> (n - 1 - np.arange(n))) & 1).astype(float) + risk = np.einsum('bi,ij,bj->b', X, sigma, X) / k ** 2 + ret = X @ mu / k + f0 = risk_aversion * risk - ret + if penalty is None: + penalty = 1.5 * max(float(f0.max() - f0.min()), 1e-12) + return f0 + penalty * (X.sum(axis=1) - k) ** 2 + + +class QuantumPortfolioAgent(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). Args: backend: Quantum backend - risk_model: Risk model to use ('mean_variance', 'black_litterman', 'factor') - optimization_objective: Objective function ('return', 'sharpe', 'risk_parity') - constraints: List of constraint specifications - rebalancing_frequency: How often to rebalance - **kwargs: Additional parameters + n_select: Number of assets to hold (default: half the assets) + risk_aversion: Weight of the variance term + reps: Ansatz repetitions + alpha: CVaR fraction (1.0 is ordinary VQE) + n_restarts: Optimizer restarts from different seeds + maxiter: Optimizer iterations per restart + **kwargs: ``seed`` and other base parameters Example: - >>> agent = QuantumPortfolioAgent( - ... backend='pennylane', - ... risk_model='mean_variance', - ... optimization_objective='sharpe' - ... ) - >>> result = agent.solve(portfolio_data) - >>> optimal_weights = result.result['weights'] + >>> 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'] """ def __init__( self, backend: str | Any, - risk_model: str = 'mean_variance', - optimization_objective: str = 'sharpe', - constraints: list[dict] | None = None, - rebalancing_frequency: str = 'monthly', + 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 ) -> None: - agent_config = { - 'risk_model': risk_model, - 'optimization_objective': optimization_objective, - 'constraints': constraints or [], - 'rebalancing_frequency': rebalancing_frequency, - } - - super().__init__(backend=backend, agent_config=agent_config, **kwargs) - - self.risk_model = risk_model - self.optimization_objective = optimization_objective - self.constraints = constraints or [] - self.rebalancing_frequency = rebalancing_frequency - - # Portfolio-specific data - self.returns_data = None - self.covariance_matrix = None + if not 0.0 < alpha <= 1.0: + raise ValueError("alpha must be in (0, 1]") + self.alpha = alpha + self.n_select = n_select + self.risk_aversion = risk_aversion + self.reps = reps + self.n_restarts = n_restarts + self.maxiter = maxiter + super().__init__(backend=backend, agent_config={ + 'n_select': n_select, 'risk_aversion': risk_aversion, 'reps': reps, + }, **kwargs) self.expected_returns = None + self.covariance_matrix = None self.optimal_weights = None def _initialize_agent(self) -> None: - """Initialize portfolio optimization algorithms.""" - # QAOA for discrete portfolio optimization - self.algorithms['qaoa'] = QAOA( - backend=self.backend, - p=3, # 3 layers for good performance - shots=self.shots - ) - - # VQE for continuous optimization - self.algorithms['vqe'] = VQE( - backend=self.backend, - hamiltonian=None, # Will be set based on problem - ansatz='RealAmplitudes', - shots=self.shots - ) - - def _prepare_portfolio_hamiltonian(self, returns: np.ndarray, covariance: np.ndarray, - risk_aversion: float = 1.0) -> np.ndarray: - """Prepare Hamiltonian for portfolio optimization.""" - n_assets = len(returns) - - # Mean-variance Hamiltonian: H = ฮป * w^T ฮฃ w - w^T ฮผ - # Where w is weights, ฮฃ is covariance, ฮผ is expected returns - - # Quadratic term (risk) - H_risk = risk_aversion * covariance - - # Linear term (expected return) - H_return = -returns # Negative because we want to maximize - - # Combine into Hamiltonian matrix - # This is a simplified representation - actual implementation would - # need proper quantum encoding - H = np.zeros((2 * n_assets, 2 * n_assets)) - H[:n_assets, :n_assets] = H_risk - np.fill_diagonal(H[:n_assets, :n_assets], H[:n_assets, :n_assets].diagonal() + H_return) - - return H - - def _encode_constraints(self, constraints: list[dict], n_assets: int) -> list[Callable]: - """Encode portfolio constraints as quantum operators.""" - quantum_constraints = [] - - for constraint in constraints: - constraint_type = constraint.get('type') - - if constraint_type == 'budget': - # Budget constraint: sum of weights = 1 - def budget_constraint(weights): - return (np.sum(weights) - 1.0) ** 2 - quantum_constraints.append(budget_constraint) - - elif constraint_type == 'long_only': - # Long-only constraint: all weights >= 0 - def long_only_constraint(weights): - return np.sum(np.maximum(0, -weights) ** 2) - quantum_constraints.append(long_only_constraint) - - elif constraint_type == 'max_weight': - # Maximum weight constraint - max_weight_value = constraint.get('value', 0.3) - def max_weight_constraint(weights, max_weight=max_weight_value): - return np.sum(np.maximum(0, weights - max_weight) ** 2) - quantum_constraints.append(max_weight_constraint) - - elif constraint_type == 'sector_limit': - # Sector exposure limit - sector_assets_list = constraint.get('assets', []) - max_exposure_value = constraint.get('value', 0.5) - def sector_constraint(weights, sector_assets=sector_assets_list, max_exposure=max_exposure_value): - sector_exposure = np.sum(weights[sector_assets]) - return np.maximum(0, sector_exposure - max_exposure) ** 2 - quantum_constraints.append(sector_constraint) - - return quantum_constraints - - def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QuantumPortfolioAgent': - """Fit the portfolio agent to historical data. - - Args: - X: Historical returns data (samples x assets) - y: Not used - **kwargs: Additional parameters - - Returns: - Self - - """ - logger.info(f"Fitting portfolio agent to data with {X.shape[1]} assets") - - self.returns_data = X + self.algorithms = {} - # Compute statistics - self.expected_returns = np.mean(X, axis=0) + def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> QuantumPortfolioAgent: + """Estimate mean returns and covariance from a (periods x assets) matrix.""" + X = np.asarray(X, dtype=float) + if X.ndim != 2 or X.shape[1] < 2: + raise ValueError("Pass historical returns as a (periods x assets) matrix") + self.expected_returns = X.mean(axis=0) self.covariance_matrix = np.cov(X.T) - - # Prepare optimization problem - risk_aversion = kwargs.get('risk_aversion', 1.0) - hamiltonian = self._prepare_portfolio_hamiltonian( - self.expected_returns, self.covariance_matrix, risk_aversion - ) - - # Setup VQE with portfolio Hamiltonian - self.algorithms['vqe'].hamiltonian = hamiltonian - self.algorithms['vqe'].fit() - - # Setup QAOA for discrete version - self.algorithms['qaoa'].fit(X) - self.is_fitted = True return self - def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Predict optimal portfolio weights.""" - if not self.is_fitted: - raise ValueError("Agent must be fitted before prediction") + def _markowitz(self) -> dict[str, Any]: + """Classical reference: long-only, fully invested mean-variance weights.""" + mu, sigma, n = self.expected_returns, self.covariance_matrix, len(self.expected_returns) + + def objective(w): + return self.risk_aversion * w @ sigma @ w - mu @ w + + res = minimize(objective, np.full(n, 1.0 / n), method='SLSQP', + bounds=[(0.0, 1.0)] * n, + constraints=[{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]) + w = np.clip(res.x, 0, None) + w /= w.sum() + return {'weights': w, **self._metrics(w)} - # Use the trained algorithms to find optimal weights - result = self.solve(X, **kwargs) - return result.result.get('weights', np.ones(X.shape[1]) / X.shape[1]) + def _metrics(self, w: np.ndarray) -> dict[str, float]: + ret = float(w @ self.expected_returns) + risk = float(np.sqrt(w @ self.covariance_matrix @ w)) + return {'expected_return': ret, 'risk': risk, + 'sharpe_ratio': ret / risk if risk > 0 else float('nan')} - def solve(self, problem_instance: np.ndarray, **kwargs) -> QuantumResult: - """Solve portfolio optimization problem. + def solve(self, problem_instance: np.ndarray | None = None, **kwargs) -> QuantumResult: + """Select assets with VQE and report the classical checks. Args: - problem_instance: Returns data or problem specification - **kwargs: Solving parameters + problem_instance: Optional returns matrix; refits the agent if given. Returns: - Portfolio optimization result + QuantumResult whose ``result`` has the quantum selection and weights, + its objective, the brute-force optimum, whether they match, the + probability VQE puts on the optimal selection, and a classical + Markowitz reference. """ - start_time = time.time() - - try: - method = kwargs.get('method', 'vqe') - - if method == 'vqe': - # Use VQE for continuous optimization - vqe_result = self.algorithms['vqe'].optimize() - optimal_params = vqe_result['optimal_params'] - - # Convert quantum parameters to portfolio weights - n_assets = len(self.expected_returns) - weights = self._params_to_weights(optimal_params, n_assets) - - elif method == 'qaoa': - # Use QAOA for discrete optimization - self.algorithms['qaoa'].optimize(lambda x: self._portfolio_objective(x)) - optimal_solution = self.algorithms['qaoa'].predict(problem_instance) - - # Convert binary solution to weights - weights = self._binary_to_weights(optimal_solution) - - else: - raise ValueError(f"Unknown optimization method: {method}") - - # Apply constraints - weights = self._apply_constraints(weights) + start = time.time() + if problem_instance is not None: + self.fit(problem_instance) + if not self.is_fitted: + raise ValueError("Call fit(returns) or pass returns to solve()") + + n = len(self.expected_returns) + k = self.n_select or max(1, n // 2) + values = portfolio_qubo_values(self.expected_returns, self.covariance_matrix, k, + self.risk_aversion) + # Rescale so feasible selections span [0, 1]: same ground state, but the + # optimizer sees the differences that matter instead of the penalty wall. + feasible = np.array([bin(i).count('1') == k for i in range(2 ** n)]) + spread = max(values[feasible].max() - values[feasible].min(), 1e-12) + H = np.diag((values - values.min()) / spread) + + order = np.argsort(H.diagonal()) + h_sorted = H.diagonal()[order] + n_params = self.backend.ansatz_param_count('RealAmplitudes', n, reps=self.reps) + + def probabilities(params): + circuit = self.backend.create_ansatz('RealAmplitudes', n, params, reps=self.reps) + return np.abs(self.backend.statevector_big_endian(circuit)) ** 2 + + def cvar(params): + # Mean energy of the best alpha fraction of the distribution (exact, from probabilities). + p_sorted = probabilities(params)[order] + cum = np.cumsum(p_sorted) + take = np.clip(self.alpha - (cum - p_sorted), 0.0, p_sorted) + return float(np.sum(take * h_sorted) / self.alpha) + + base_seed = 0 if self.seed is None else self.seed + best = None + for r in range(max(1, self.n_restarts)): + x0 = np.random.default_rng(base_seed + r).uniform(-np.pi, np.pi, n_params) + res = minimize(cvar, x0, method='COBYLA', options={'maxiter': self.maxiter}) + if best is None or res.fun < best.fun: + best = res + probs = probabilities(best.x) + probs = probs / probs.sum() + samples = np.random.default_rng(base_seed).choice(len(probs), size=self.shots, p=probs) + q_index = int(samples[np.argmin(values[samples])]) + c_index = int(np.argmin(values)) + self.optimal_params_ = best.x + + def bits(i): + return np.array([(i >> (n - 1 - j)) & 1 for j in range(n)]) + + q_bits, c_bits = bits(q_index), bits(c_index) + weights = q_bits / max(1, q_bits.sum()) + self.optimal_weights = weights + + result = { + 'selected_assets': [int(i) for i in np.flatnonzero(q_bits)], + 'weights': weights, + 'objective': float(values[q_index]), + 'cvar_rescaled': float(best.fun), + 'shots': self.shots, + 'feasible': bool(q_bits.sum() == k), + 'classical_selected_assets': [int(i) for i in np.flatnonzero(c_bits)], + 'classical_objective': float(values[c_index]), + 'matches_classical_optimum': bool(q_index == c_index), + 'objective_gap': float(values[q_index] - values[c_index]), + 'probability_of_optimum': float(probs[c_index]), + 'optimum_sampled': bool(np.any(samples == c_index)), + 'markowitz_reference': self._markowitz(), + **self._metrics(weights), + } + self.performance_metrics = {k_: result[k_] for k_ in + ('matches_classical_optimum', 'probability_of_optimum')} + return self._result(result, start, n_assets=n, n_select=k, + method='CVaR-VQE on a mean-variance QUBO; brute force check', + n_evaluations=int(best.nfev)) - # Compute portfolio metrics - expected_return = np.dot(weights, self.expected_returns) - portfolio_risk = np.sqrt(np.dot(weights, np.dot(self.covariance_matrix, weights))) - sharpe_ratio = expected_return / portfolio_risk if portfolio_risk > 0 else 0 + def predict(self, X: np.ndarray | None = None, **kwargs) -> np.ndarray: + """Return the equal weights of the VQE selection.""" + if self.optimal_weights is None: + self.solve(X) + return self.optimal_weights - result = { - 'weights': weights, - 'expected_return': expected_return, - 'risk': portfolio_risk, - 'sharpe_ratio': sharpe_ratio, - 'method': method, - } - return QuantumResult( - result=result, - metadata={ - 'n_assets': len(weights), - 'optimization_method': method, - 'constraints_applied': len(self.constraints), - }, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - ) - - except Exception as e: - logger.error(f"Portfolio optimization failed: {e}") - return QuantumResult( - result=None, - metadata={'error': str(e)}, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - error=str(e), - ) - - def _params_to_weights(self, params: np.ndarray, n_assets: int) -> np.ndarray: - """Convert quantum parameters to portfolio weights.""" - # Simple mapping - could be more sophisticated - weights = np.abs(params[:n_assets]) - weights = weights / np.sum(weights) # Normalize - return weights - - def _binary_to_weights(self, binary_solution: np.ndarray) -> np.ndarray: - """Convert binary solution to portfolio weights.""" - # Equal weighting of selected assets - selected_assets = np.where(binary_solution == 1)[0] - weights = np.zeros(len(binary_solution)) - if len(selected_assets) > 0: - weights[selected_assets] = 1.0 / len(selected_assets) - return weights - - def _portfolio_objective(self, weights: np.ndarray) -> float: - """Portfolio objective function.""" - if self.optimization_objective == 'return': - return -np.dot(weights, self.expected_returns) # Negative for minimization - elif self.optimization_objective == 'risk': - return np.sqrt(np.dot(weights, np.dot(self.covariance_matrix, weights))) - elif self.optimization_objective == 'sharpe': - ret = np.dot(weights, self.expected_returns) - risk = np.sqrt(np.dot(weights, np.dot(self.covariance_matrix, weights))) - return -ret / risk if risk > 0 else 0 # Negative for minimization - else: - return 0 - - def _apply_constraints(self, weights: np.ndarray) -> np.ndarray: - """Apply portfolio constraints to weights.""" - # Simple constraint application - could be more sophisticated - - # Budget constraint (sum to 1) - weights = weights / np.sum(weights) if np.sum(weights) > 0 else weights - - # Long-only constraint - if any(c.get('type') == 'long_only' for c in self.constraints): - weights = np.maximum(weights, 0) - weights = weights / np.sum(weights) if np.sum(weights) > 0 else weights - - # Maximum weight constraints - max_weight_constraints = [c for c in self.constraints if c.get('type') == 'max_weight'] - for constraint in max_weight_constraints: - max_weight = constraint.get('value', 0.3) - weights = np.minimum(weights, max_weight) - weights = weights / np.sum(weights) if np.sum(weights) > 0 else weights - - return weights +# --------------------------------------------------------------------------- +# Classification +# --------------------------------------------------------------------------- class QuantumClassificationAgent(QuantumAgent): - """Quantum agent for classification tasks. + """Train quantum classifiers and benchmark them against tuned classical models. - This agent combines multiple quantum classifiers and provides - automatic model selection, hyperparameter optimization, and - ensemble methods for robust classification. + ``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. Args: backend: Quantum backend - algorithms: List of algorithms to include ('quantum_svm', 'quantum_nn', 'hybrid') - ensemble_method: How to combine predictions ('voting', 'weighted', 'stacking') - auto_tune: Whether to automatically tune hyperparameters - **kwargs: Additional parameters + algorithms: Any of 'quantum_svm', 'quantum_nn', 'hybrid' + ensemble_method: 'voting', 'weighted' or 'best' (used by predict when + several algorithms are trained) + cv: Folds for the benchmark in ``solve`` + **kwargs: Base parameters """ @@ -418,590 +337,305 @@ def __init__( backend: str | Any, algorithms: list[str] | None = None, ensemble_method: str = 'voting', - auto_tune: bool = False, + cv: int = 5, **kwargs ) -> None: - agent_config = { - 'algorithms': algorithms or ['quantum_svm', 'quantum_nn'], - 'ensemble_method': ensemble_method, - 'auto_tune': auto_tune, - } - - super().__init__(backend=backend, agent_config=agent_config, **kwargs) - + self.available_algorithms = algorithms or ['quantum_svm'] self.ensemble_method = ensemble_method - self.auto_tune = auto_tune - self.available_algorithms = algorithms or ['quantum_svm', 'quantum_nn'] + self.cv = cv + super().__init__(backend=backend, agent_config={ + 'algorithms': self.available_algorithms, 'ensemble_method': ensemble_method, + }, **kwargs) def _initialize_agent(self) -> None: - """Initialize classification algorithms.""" - for algo in self.available_algorithms: - if algo == 'quantum_svm': - self.algorithms['quantum_svm'] = QuantumSVM( - backend=self.backend, - shots=self.shots - ) - elif algo == 'quantum_nn': - self.algorithms['quantum_nn'] = QuantumNN( - backend=self.backend, - shots=self.shots, - task_type='classification' - ) - elif algo == 'hybrid': - self.algorithms['hybrid'] = HybridClassifier( - backend=self.backend, - shots=self.shots - ) - - def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'QuantumClassificationAgent': - """Fit all classification algorithms.""" - logger.info(f"Fitting classification agent with {len(self.algorithms)} algorithms") + builders = { + 'quantum_svm': lambda: QuantumSVM(backend=self.backend, shots=self.shots), + 'quantum_nn': lambda: QuantumNN(backend=self.backend, shots=self.shots, + task_type='classification', seed=self.seed), + 'hybrid': lambda: HybridClassifier(backend=self.backend, shots=self.shots), + } + for name in self.available_algorithms: + if name not in builders: + raise ValueError(f"Unknown algorithm '{name}'. Use {sorted(builders)}") + self.algorithms[name] = builders[name]() + def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> QuantumClassificationAgent: + """Fit every algorithm. Errors propagate; nothing is silently scored as 0.""" for name, algorithm in self.algorithms.items(): - try: - logger.info(f"Training {name}") - algorithm.fit(X, y) - - # Evaluate performance - predictions = algorithm.predict(X) - accuracy = accuracy_score(y, predictions) - self.performance_metrics[name] = accuracy - - logger.info(f"{name} training accuracy: {accuracy:.4f}") - - except Exception as e: - logger.error(f"Failed to train {name}: {e}") - self.performance_metrics[name] = 0.0 - + algorithm.fit(X, y) + self.performance_metrics[name] = { + 'train_accuracy': float(accuracy_score(y, algorithm.predict(X))) + } self.is_fitted = True return self def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Make ensemble predictions.""" + """Predict with one algorithm, or combine several.""" if not self.is_fitted: raise ValueError("Agent must be fitted before prediction") - - predictions = {} - - # Get predictions from all algorithms - for name, algorithm in self.algorithms.items(): - try: - predictions[name] = algorithm.predict(X) - except Exception as e: - logger.error(f"Failed to get predictions from {name}: {e}") - - if not predictions: - raise ValueError("No successful predictions from any algorithm") - - # Combine predictions based on ensemble method - if self.ensemble_method == 'voting': - return self._majority_voting(predictions) - elif self.ensemble_method == 'weighted': - return self._weighted_voting(predictions) - else: - # Return best performing algorithm's predictions - best_algo = max(self.performance_metrics.items(), key=lambda x: x[1])[0] - return predictions.get(best_algo, list(predictions.values())[0]) - - def _majority_voting(self, predictions: dict[str, np.ndarray]) -> np.ndarray: - """Majority voting ensemble.""" - pred_arrays = list(predictions.values()) - n_samples = len(pred_arrays[0]) - final_predictions = [] - - for i in range(n_samples): - sample_preds = [pred[i] for pred in pred_arrays] - unique, counts = np.unique(sample_preds, return_counts=True) - final_predictions.append(unique[np.argmax(counts)]) - - return np.array(final_predictions) - - def _weighted_voting(self, predictions: dict[str, np.ndarray]) -> np.ndarray: - """Weighted voting based on performance.""" - weights = {} - total_weight = 0 - - for name in predictions.keys(): - weight = self.performance_metrics.get(name, 0.1) - weights[name] = weight - total_weight += weight - - # Normalize weights - for name in weights: - weights[name] /= total_weight if total_weight > 0 else 1 - - # Weighted prediction (simplified for discrete labels) - pred_arrays = list(predictions.values()) - algorithm_names = list(predictions.keys()) - - n_samples = len(pred_arrays[0]) - final_predictions = [] - - for i in range(n_samples): - weighted_votes = {} - for j, name in enumerate(algorithm_names): - pred = pred_arrays[j][i] - if pred not in weighted_votes: - weighted_votes[pred] = 0 - weighted_votes[pred] += weights[name] - - final_predictions.append(max(weighted_votes.items(), key=lambda x: x[1])[0]) - - return np.array(final_predictions) + preds = {name: np.asarray(a.predict(X)) for name, a in self.algorithms.items()} + if len(preds) == 1: + return next(iter(preds.values())) + if self.ensemble_method == 'best': + best = max(self.performance_metrics, + key=lambda n: self.performance_metrics[n]['train_accuracy']) + return preds[best] + weights = {n: (self.performance_metrics[n]['train_accuracy'] + if self.ensemble_method == 'weighted' else 1.0) for n in preds} + out = [] + for i in range(len(X)): + votes: dict[Any, float] = {} + for n, p in preds.items(): + votes[p[i]] = votes.get(p[i], 0.0) + weights[n] + out.append(max(votes.items(), key=lambda kv: kv[1])[0]) + return np.array(out) def solve(self, problem_instance: tuple[np.ndarray, np.ndarray], **kwargs) -> QuantumResult: - """Solve classification problem.""" - import time - - X, y = problem_instance - start_time = time.time() + """Benchmark against classical baselines with CV, then fit on all data. - try: - # Fit and predict - self.fit(X, y) - predictions = self.predict(X) - - # Compute metrics - accuracy = accuracy_score(y, predictions) + Keyword arguments are passed to ``compare_to_classical``. + """ + from ..benchmarks import compare_to_classical - result = { - 'predictions': predictions, - 'accuracy': accuracy, - 'individual_performances': self.performance_metrics.copy(), - 'ensemble_method': self.ensemble_method, - } + start = time.time() + X, y = problem_instance + name, algorithm = next(iter(self.algorithms.items())) + kwargs.setdefault('cv', self.cv) + kwargs.setdefault('seed', 0 if self.seed is None else self.seed) + benchmark = compare_to_classical(X, y, algorithm, **kwargs) + self.fit(X, y) + result = { + 'algorithm': name, + 'cv_accuracy': benchmark.quantum.accuracy_mean, + 'cv_accuracy_std': benchmark.quantum.accuracy_std, + 'best_classical': benchmark.best_classical.name, + 'best_classical_cv_accuracy': benchmark.best_classical.accuracy_mean, + 'delta_vs_best_classical': benchmark.delta_vs_best_classical, + 'p_value': benchmark.p_value_vs_best_classical, + 'verdict': benchmark.verdict, + 'benchmark': benchmark, + 'train_accuracy': self.performance_metrics[name]['train_accuracy'], + } + return self._result(result, start, n_samples=len(X), n_features=X.shape[1], + n_classes=len(np.unique(y)), algorithms_used=list(self.algorithms)) - return QuantumResult( - result=result, - metadata={ - 'n_samples': len(X), - 'n_features': X.shape[1], - 'n_classes': len(np.unique(y)), - 'algorithms_used': list(self.algorithms.keys()), - }, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - ) - - except Exception as e: - logger.error(f"Classification failed: {e}") - return QuantumResult( - result=None, - metadata={'error': str(e)}, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - error=str(e), - ) +# --------------------------------------------------------------------------- +# Optimization +# --------------------------------------------------------------------------- -class QuantumTradingAgent(QuantumAgent): - """Autonomous quantum trading agent for financial markets. +class QuantumOptimizationAgent(QuantumAgent): + """Solve small optimisation problems with QAOA or VQE plus an exact classical check. - This agent combines quantum portfolio optimization, quantum risk analysis, - and quantum-enhanced pattern recognition to make autonomous trading - decisions with potential quantum advantages in complex market scenarios. + * ``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. Args: - backend: Quantum backend for computations - strategy: Trading strategy ('momentum', 'mean_reversion', 'quantum_portfolio') - risk_tolerance: Risk tolerance level (0.0 to 1.0) - quantum_advantage_threshold: Minimum quantum advantage required to use quantum methods - markets: List of markets to trade in ['stocks', 'crypto', 'forex'] - **kwargs: Additional parameters + backend: Quantum backend + problem_type: 'combinatorial' or 'continuous' + p: QAOA layers + **kwargs: Base parameters and extra QAOA/VQE options (``maxiter``, + ``n_restarts`` for QAOA, ``reps`` for VQE) """ def __init__( self, - backend: str | Any = 'auto', - strategy: str = 'quantum_portfolio', - risk_tolerance: float = 0.5, - quantum_advantage_threshold: float = 0.05, - markets: list[str] | None = None, + 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 ) -> None: - super().__init__(backend=backend, **kwargs) - - self.strategy = strategy - self.risk_tolerance = risk_tolerance - self.quantum_advantage_threshold = quantum_advantage_threshold - self.markets = markets or ['stocks'] - - # Initialize quantum algorithms for trading - if strategy in ['quantum_portfolio', 'quantum_momentum']: - self.algorithms['qaoa'] = QAOA(backend=self.backend) - - # For risk analysis - self.algorithms['qsvm'] = QuantumSVM(backend=self.backend) - - self._initialize_agent() - logger.info(f"Initialized QuantumTradingAgent with strategy={strategy}") + if problem_type not in ('combinatorial', 'continuous'): + raise ValueError("problem_type must be 'combinatorial' or 'continuous'") + self.problem_type = problem_type + self.p = p + self.maxiter = maxiter + self.n_restarts = n_restarts + self.reps = reps + self.available_algorithms = algorithms or ( + ['qaoa'] if problem_type == 'combinatorial' else ['vqe']) + super().__init__(backend=backend, agent_config={ + 'problem_type': problem_type, 'p': p, 'algorithms': self.available_algorithms, + }, **kwargs) + self.problem_instance = None def _initialize_agent(self) -> None: - """Initialize the trading agent.""" - self.is_fitted = True # Agents are pre-configured + if 'qaoa' in self.available_algorithms: + self.algorithms['qaoa'] = QAOA(backend=self.backend, p=self.p, shots=self.shots, + maxiter=self.maxiter, n_restarts=self.n_restarts, + seed=self.seed) + if 'vqe' in self.available_algorithms: + self.algorithms['vqe'] = VQE(hamiltonian=None, backend=self.backend, shots=self.shots, + maxiter=self.maxiter, reps=self.reps, seed=self.seed) - def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QuantumTradingAgent': - """Fit the trading agent (optional for pre-configured agents).""" + def fit(self, X: Any, y: np.ndarray | None = None, **kwargs) -> QuantumOptimizationAgent: + """Store the problem: an adjacency matrix or a Hamiltonian.""" + self.problem_instance = X + self.is_fitted = True return self - def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Predict trading decisions based on market data.""" - # Simplified prediction logic - return np.random.choice([0, 1], size=len(X)) - - def solve(self, problem_instance: Any, **kwargs) -> QuantumResult: - """Solve trading optimization problem.""" - return self.deploy(problem_instance, **kwargs) - - def deploy(self, market_data: Any | None = None, **kwargs) -> QuantumResult: - """Deploy the trading agent and return performance metrics.""" - start_time = time.time() - - try: - # Simulate quantum trading logic - if self.strategy == 'quantum_portfolio': - result = self._quantum_portfolio_optimization(market_data, **kwargs) - elif self.strategy == 'momentum': - result = self._quantum_momentum_strategy(market_data, **kwargs) - else: - result = self._basic_trading_strategy(market_data, **kwargs) - - quantum_advantage = self._calculate_quantum_advantage(result) - - return QuantumResult( - result={ - 'strategy': self.strategy, - 'performance': result, - 'quantum_advantage': quantum_advantage, - 'deployed': True, - }, - metadata={ - 'agent_type': 'QuantumTradingAgent', - 'markets': self.markets, - 'risk_tolerance': self.risk_tolerance, - }, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - ) - - except Exception as e: - logger.error(f"Trading agent deployment failed: {e}") - return QuantumResult( - result=None, - metadata={'error': str(e)}, - execution_time=time.time() - start_time, - error=str(e), - ) - - def _quantum_portfolio_optimization(self, market_data: Any, **kwargs) -> dict[str, Any]: - """Perform quantum portfolio optimization.""" - # Placeholder implementation - return { - 'expected_return': 0.12 + np.random.normal(0, 0.02), - 'risk': 0.15 + np.random.normal(0, 0.01), - 'sharpe_ratio': 0.8 + np.random.normal(0, 0.1), - } - - def _quantum_momentum_strategy(self, market_data: Any, **kwargs) -> dict[str, Any]: - """Quantum-enhanced momentum trading strategy.""" - return { - 'expected_return': 0.10 + np.random.normal(0, 0.03), - 'risk': 0.18 + np.random.normal(0, 0.02), - 'sharpe_ratio': 0.6 + np.random.normal(0, 0.1), - } - - def _basic_trading_strategy(self, market_data: Any, **kwargs) -> dict[str, Any]: - """Basic trading strategy fallback.""" - return { - 'expected_return': 0.08 + np.random.normal(0, 0.02), - 'risk': 0.20 + np.random.normal(0, 0.01), - 'sharpe_ratio': 0.4 + np.random.normal(0, 0.05), + def solve(self, problem_instance: Any = None, **kwargs) -> QuantumResult: + """Solve and return the quantum answer with its exact classical check.""" + start = time.time() + if problem_instance is not None: + self.fit(problem_instance) + if self.problem_instance is None: + raise ValueError("Pass an adjacency matrix (combinatorial) or Hamiltonian (continuous)") + + if self.problem_type == 'combinatorial': + out = self.algorithms['qaoa'].solve(np.asarray(self.problem_instance, dtype=float)) + out['matches_classical_optimum'] = bool( + np.isclose(out['cut_value'], out['classical_optimum'])) + return self._result(out, start, problem_type='maxcut', algorithm_used='QAOA', + classical_check='brute force') + + vqe = self.algorithms['vqe'] + vqe.fit(self.problem_instance) + opt = vqe._run_optimization() + out = { + 'ground_energy': opt['ground_energy'], + 'exact_energy': opt['exact_energy'], + 'error': abs(opt['ground_energy'] - opt['exact_energy']), + 'optimal_params': opt['optimal_params'], + 'n_evaluations': opt['n_iterations'], } + return self._result(out, start, problem_type='ground_state', algorithm_used='VQE', + classical_check='exact diagonalisation') - def _calculate_quantum_advantage(self, result: dict[str, Any]) -> float: - """Calculate quantum advantage over classical methods.""" - # Simplified quantum advantage calculation - base_performance = 0.08 # Classical baseline - quantum_performance = result.get('expected_return', base_performance) - return max(0, (quantum_performance - base_performance) / base_performance) + def predict(self, X: Any = None, **kwargs) -> np.ndarray: + """MaxCut partition (combinatorial) or energy (continuous).""" + res = self.solve(X) + if self.problem_type == 'combinatorial': + return np.array([int(b) for b in res.result['bitstring']]) + return np.array([res.result['ground_energy']]) -class QuantumResearchAgent(QuantumAgent): - """Autonomous quantum research agent for scientific discovery. - - This agent combines quantum simulation, quantum machine learning, and - automated hypothesis generation to accelerate scientific research across - domains like materials science, drug discovery, and physics. +# --------------------------------------------------------------------------- +# Experimental agents +# --------------------------------------------------------------------------- - Args: - backend: Quantum backend for simulations - domain: Research domain ('materials_science', 'drug_discovery', 'physics') - hypothesis_generation: Enable automated hypothesis generation - experiment_design: Enable quantum experiment design - literature_synthesis: Enable literature review and synthesis - **kwargs: Additional parameters +class QuantumTradingAgent(QuantumAgent): + """Experimental. Only portfolio selection is implemented. + ``deploy(returns)`` delegates to :class:`QuantumPortfolioAgent` and returns + its result, including the brute-force and Markowitz baselines. There are no + trading signals, backtests or "quantum advantage" numbers: strategies other + than ``'quantum_portfolio'`` raise ``NotImplementedError``. """ def __init__( self, - backend: str | Any = 'auto', - domain: str = 'materials_science', - hypothesis_generation: bool = True, - experiment_design: bool = True, - literature_synthesis: bool = False, + backend: str | Any = 'simulator', + strategy: str = 'quantum_portfolio', + risk_tolerance: float = 0.5, + markets: list[str] | None = None, **kwargs ) -> None: - super().__init__(backend=backend, **kwargs) - - self.domain = domain - self.hypothesis_generation = hypothesis_generation - self.experiment_design = experiment_design - self.literature_synthesis = literature_synthesis - - # Initialize quantum algorithms for research - if domain in ['materials_science', 'drug_discovery']: - # Create a simple H2 hamiltonian for VQE - try: - from ..gates import Hamiltonian - h2_hamiltonian = Hamiltonian.from_dict({ - "ZZ": -1.0523732, - "ZI": -0.39793742, - "IZ": -0.39793742, - }) - self.algorithms['vqe'] = VQE(hamiltonian=h2_hamiltonian, backend=self.backend) - except Exception: - # Skip VQE if hamiltonian creation fails - pass - - # For pattern recognition in research data - self.algorithms['qnn'] = QuantumNN(backend=self.backend) - - self._initialize_agent() - logger.info(f"Initialized QuantumResearchAgent for domain={domain}") + self.strategy = strategy + self.risk_tolerance = risk_tolerance + self.markets = markets or ['stocks'] + kwargs.pop('quantum_advantage_threshold', None) + super().__init__(backend=backend, agent_config={'strategy': strategy}, **kwargs) def _initialize_agent(self) -> None: - """Initialize the research agent.""" - self.is_fitted = True # Agents are pre-configured + # Higher risk tolerance means less weight on variance. + self.algorithms['portfolio'] = QuantumPortfolioAgent( + backend=self.backend, risk_aversion=2.0 * (1.0 - self.risk_tolerance) + 0.1, + seed=self.seed) - def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QuantumResearchAgent': - """Fit the research agent (optional for pre-configured agents).""" + def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> QuantumTradingAgent: + self.algorithms['portfolio'].fit(X) + self.is_fitted = True return self def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Predict research outcomes based on data.""" - # Simplified prediction logic - return np.random.random(len(X)) + raise NotImplementedError("Trading signal prediction is not implemented") def solve(self, problem_instance: Any, **kwargs) -> QuantumResult: - """Solve research problem.""" - return self.investigate(problem_instance, **kwargs) - - def investigate( - self, - research_question: str, - constraints: dict[str, Any] | None = None, - **kwargs - ) -> QuantumResult: - """Investigate a research question and return research plan.""" - start_time = time.time() - - try: - # Simulate research investigation - research_plan = self._generate_research_plan(research_question, constraints) - hypothesis = self._generate_hypothesis(research_question) if self.hypothesis_generation else None - experiments = self._design_experiments(research_question) if self.experiment_design else None - - return QuantumResult( - result={ - 'research_question': research_question, - 'research_plan': research_plan, - 'hypothesis': hypothesis, - 'experiments': experiments, - 'domain': self.domain, - }, - metadata={ - 'agent_type': 'QuantumResearchAgent', - 'capabilities': { - 'hypothesis_generation': self.hypothesis_generation, - 'experiment_design': self.experiment_design, - 'literature_synthesis': self.literature_synthesis, - }, - }, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - ) - - except Exception as e: - logger.error(f"Research investigation failed: {e}") - return QuantumResult( - result=None, - metadata={'error': str(e)}, - execution_time=time.time() - start_time, - error=str(e), - ) - - def _generate_research_plan(self, question: str, constraints: dict[str, Any] | None) -> dict[str, Any]: - """Generate a research plan using quantum-enhanced methods.""" - constraints = constraints or {} - - return { - 'phases': [ - 'Literature Review', - 'Hypothesis Generation', - 'Quantum Simulation', - 'Experimental Validation', - 'Results Analysis' - ], - 'timeline': constraints.get('timeline', '12_months'), - 'budget_estimate': constraints.get('budget', 200000), - 'quantum_simulations_required': True, - 'expected_quantum_advantage': 'Exponential speedup for molecular simulations', - } - - def _generate_hypothesis(self, question: str) -> dict[str, Any]: - """Generate research hypotheses using quantum ML.""" - return { - 'primary_hypothesis': f"Quantum effects in {self.domain} can be leveraged to solve: {question}", - 'secondary_hypotheses': [ - f"Quantum simulation provides exponential advantage for {self.domain}", - f"Quantum ML can discover novel patterns in {self.domain} data" - ], - 'testable_predictions': [ - "Quantum algorithm shows >10x speedup over classical methods", - "Novel materials/compounds discovered through quantum simulation" - ] - } - - def _design_experiments(self, question: str) -> list[dict[str, Any]]: - """Design quantum experiments for research validation.""" - return [ - { - 'experiment_name': f'Quantum Simulation for {self.domain}', - 'methodology': 'VQE-based molecular simulation', - 'expected_duration': '4-6 weeks', - 'quantum_resources_needed': 'Medium-scale quantum processor (20+ qubits)', - 'success_metrics': ['Accuracy vs classical', 'Computation time', 'Resource efficiency'] - }, - { - 'experiment_name': 'Quantum ML Pattern Discovery', - 'methodology': 'Quantum neural networks for data analysis', - 'expected_duration': '2-3 weeks', - 'quantum_resources_needed': 'Near-term quantum devices', - 'success_metrics': ['Pattern recognition accuracy', 'Novel discoveries', 'Quantum advantage'] - } - ] + return self.deploy(problem_instance, **kwargs) -class QuantumOptimizationAgent(QuantumAgent): - """Quantum agent for optimization problems. + def deploy(self, market_data: np.ndarray | None = None, **kwargs) -> QuantumResult: + """Run quantum portfolio selection on a (periods x assets) returns matrix.""" + if self.strategy != 'quantum_portfolio': + raise NotImplementedError( + f"Strategy '{self.strategy}' is not implemented; use 'quantum_portfolio'") + if market_data is None and not self.algorithms['portfolio'].is_fitted: + raise ValueError("deploy() needs a (periods x assets) returns matrix") + return self.algorithms['portfolio'].solve(market_data, **kwargs) - This agent provides a unified interface for solving various - optimization problems using QAOA, VQE, and other quantum - optimization algorithms. - Args: - backend: Quantum backend - problem_type: Type of optimization ('combinatorial', 'continuous', 'mixed') - algorithms: List of algorithms to use - **kwargs: Additional parameters +class QuantumResearchAgent(QuantumAgent): + """Experimental. Only ground-state simulation is implemented. + ``simulate_ground_state(hamiltonian)`` runs VQE and reports the exact + energy next to it (default: H2 in STO-3G at 0.735 Angstrom). Automated + hypothesis generation, literature synthesis and experiment design are not + implemented and raise ``NotImplementedError`` rather than returning + template text. """ def __init__( self, - backend: str | Any, - problem_type: str = 'combinatorial', - algorithms: list[str] | None = None, + backend: str | Any = 'simulator', + domain: str = 'materials_science', **kwargs ) -> None: - agent_config = { - 'problem_type': problem_type, - 'algorithms': algorithms or ['qaoa', 'vqe'], - } - - self.problem_type = problem_type - self.available_algorithms = algorithms or ['qaoa', 'vqe'] - - super().__init__(backend=backend, agent_config=agent_config, **kwargs) + self.domain = domain + for flag in ('hypothesis_generation', 'experiment_design', 'literature_synthesis'): + kwargs.pop(flag, None) + super().__init__(backend=backend, agent_config={'domain': domain}, **kwargs) def _initialize_agent(self) -> None: - """Initialize optimization algorithms.""" - if 'qaoa' in self.available_algorithms: - self.algorithms['qaoa'] = QAOA( - backend=self.backend, - p=3, - shots=self.shots - ) - - if 'vqe' in self.available_algorithms: - self.algorithms['vqe'] = VQE( - backend=self.backend, - hamiltonian=None, # Will be set per problem - shots=self.shots - ) - - def fit(self, X: np.ndarray, y: np.ndarray | None = None, **kwargs) -> 'QuantumOptimizationAgent': - """Fit optimization algorithms to problem.""" - for name, algorithm in self.algorithms.items(): - algorithm.fit(X, y) + self.algorithms['vqe'] = VQE(hamiltonian=dict(H2_STO3G_0735), backend=self.backend, + seed=self.seed) + def fit(self, X: Any = None, y: np.ndarray | None = None, **kwargs) -> QuantumResearchAgent: + if X is not None: + self.algorithms['vqe'].fit(X) self.is_fitted = True return self def predict(self, X: np.ndarray, **kwargs) -> np.ndarray: - """Predict optimal solution.""" - if not self.is_fitted: - raise ValueError("Agent must be fitted before prediction") + raise NotImplementedError("QuantumResearchAgent has no predictive model") + + def solve(self, problem_instance: Any = None, **kwargs) -> QuantumResult: + return self.simulate_ground_state(problem_instance) + + def simulate_ground_state(self, hamiltonian: Any = None) -> QuantumResult: + """VQE ground-state energy with the exact value for comparison.""" + start = time.time() + vqe = self.algorithms['vqe'] + vqe.fit(hamiltonian) + opt = vqe._run_optimization() + return self._result({ + 'ground_energy': opt['ground_energy'], + 'exact_energy': opt['exact_energy'], + 'error': abs(opt['ground_energy'] - opt['exact_energy']), + 'hamiltonian': 'H2 STO-3G 0.735 A' if hamiltonian is None else 'user supplied', + }, start, agent_type='QuantumResearchAgent') + + def investigate(self, research_question: str, constraints: dict[str, Any] | None = None, + **kwargs) -> QuantumResult: + raise NotImplementedError( + "Automated research planning and hypothesis generation are not implemented. " + "Use simulate_ground_state() for a real VQE run with an exact baseline." + ) - # Use the algorithm most suitable for the problem type - if self.problem_type == 'combinatorial' and 'qaoa' in self.algorithms: - return self.algorithms['qaoa'].predict(X) - elif self.problem_type == 'continuous' and 'vqe' in self.algorithms: - return self.algorithms['vqe'].predict(X) - else: - # Use first available algorithm - first_algo = next(iter(self.algorithms.values())) - return first_algo.predict(X) - def solve(self, problem_instance: Any, **kwargs) -> QuantumResult: - """Solve optimization problem.""" - import time - - start_time = time.time() - - try: - # Choose algorithm based on problem type - if self.problem_type == 'combinatorial' and 'qaoa' in self.algorithms: - algorithm = self.algorithms['qaoa'] - result = algorithm.optimize(problem_instance, **kwargs) - elif self.problem_type == 'continuous' and 'vqe' in self.algorithms: - algorithm = self.algorithms['vqe'] - result = algorithm.optimize(**kwargs) - else: - # Use first available algorithm - algorithm = next(iter(self.algorithms.values())) - if hasattr(algorithm, 'optimize'): - result = algorithm.optimize(problem_instance, **kwargs) - else: - raise ValueError("No suitable optimization algorithm available") - - return QuantumResult( - result=result, - metadata={ - 'problem_type': self.problem_type, - 'algorithm_used': algorithm.__class__.__name__, - }, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - ) - - except Exception as e: - logger.error(f"Optimization failed: {e}") - return QuantumResult( - result=None, - metadata={'error': str(e)}, - execution_time=time.time() - start_time, - backend_info=self.get_circuit_info(), - error=str(e), - ) +__all__ = [ + 'QuantumAgent', + 'QuantumPortfolioAgent', + 'QuantumClassificationAgent', + 'QuantumOptimizationAgent', + 'QuantumTradingAgent', + 'QuantumResearchAgent', + 'portfolio_qubo_values', +] + diff --git a/src/superquantx/algorithms/quantum_nn.py b/src/superquantx/algorithms/quantum_nn.py index af6f446..43719ca 100644 --- a/src/superquantx/algorithms/quantum_nn.py +++ b/src/superquantx/algorithms/quantum_nn.py @@ -106,66 +106,6 @@ def _determine_qubits(self, n_features: int) -> int: else: return n_features - def _create_encoding_layer(self, x: np.ndarray) -> Any: - """Create data encoding quantum layer.""" - try: - if hasattr(self.backend, 'create_encoding_layer'): - return self.backend.create_encoding_layer( - data=x, - encoding=self.encoding, - n_qubits=self.n_qubits - ) - else: - return self._fallback_encoding(x) - except Exception as e: - logger.error(f"Failed to create encoding layer: {e}") - return self._fallback_encoding(x) - - def _fallback_encoding(self, x: np.ndarray) -> Any: - """Fallback data encoding implementation.""" - logger.warning("Using fallback data encoding") - return None - - def _create_variational_layer(self, params: np.ndarray, layer_idx: int) -> Any: - """Create parameterized variational quantum layer.""" - try: - if hasattr(self.backend, 'create_variational_layer'): - return self.backend.create_variational_layer( - params=params, - layer_idx=layer_idx, - entanglement=self.entanglement, - n_qubits=self.n_qubits - ) - else: - return self._fallback_variational_layer(params, layer_idx) - except Exception as e: - logger.error(f"Failed to create variational layer {layer_idx}: {e}") - return self._fallback_variational_layer(params, layer_idx) - - def _fallback_variational_layer(self, params: np.ndarray, layer_idx: int) -> Any: - """Fallback variational layer implementation.""" - logger.warning(f"Using fallback variational layer {layer_idx}") - return None - - def _create_measurement_layer(self) -> Any: - """Create measurement layer.""" - try: - if hasattr(self.backend, 'create_measurement_layer'): - return self.backend.create_measurement_layer( - measurement=self.measurement, - n_qubits=self.n_qubits - ) - else: - return self._fallback_measurement() - except Exception as e: - logger.error(f"Failed to create measurement layer: {e}") - return self._fallback_measurement() - - def _fallback_measurement(self) -> Any: - """Fallback measurement implementation.""" - logger.warning("Using fallback measurement layer") - return None - def _build_network(self) -> None: """Build the complete quantum neural network.""" logger.info(f"Building {self.architecture} quantum neural network") @@ -175,7 +115,8 @@ def _build_network(self) -> None: self.n_params = self.n_layers * params_per_layer # Initialize weights - self.weights = np.random.uniform(-np.pi, np.pi, self.n_params) + rng = np.random.default_rng(getattr(self, 'seed', None)) + self.weights = rng.uniform(-np.pi, np.pi, self.n_params) # Build network layers based on architecture if self.architecture == 'pure': @@ -223,78 +164,81 @@ def _build_variational_network(self) -> None: """Build variational quantum circuit network.""" self._build_pure_quantum_network() + _READOUT_SCALE = 3.0 + + def _circuit_outputs(self, x: np.ndarray, weights: np.ndarray) -> np.ndarray: + """Raw circuit outputs: per-qubit (or probabilities) for each sample.""" + return np.asarray(self.backend.execute_qnn( + input_data=x, + weights=weights, + quantum_layers=self.quantum_layers, + classical_layers=[], + encoding=self.encoding, + measurement=self.measurement, + shots=self.shots, + ), dtype=float) + + def _readout(self, z: np.ndarray) -> np.ndarray: + """Map circuit outputs to model outputs. + + Classification: softmax over the first ``n_classes`` outputs (scaled). + Regression: the first output. + """ + if self.task_type == 'classification': + k = self.n_classes_ + if z.shape[1] < k: + z = np.pad(z, ((0, 0), (0, k - z.shape[1]))) + logits = self._READOUT_SCALE * z[:, :k] + logits -= logits.max(axis=1, keepdims=True) + e = np.exp(logits) + return e / e.sum(axis=1, keepdims=True) + return z[:, :1] + def _forward_pass(self, x: np.ndarray, weights: np.ndarray) -> np.ndarray: - """Perform forward pass through the quantum neural network. + """Forward pass. Backend errors propagate; there is no random fallback.""" + return self._readout(self._circuit_outputs(x, weights)) - Args: - x: Input data - weights: Network weights + def _compute_loss(self, y_true: np.ndarray, y_pred: np.ndarray) -> float: + """Compute loss function.""" + if self.task_type == 'classification': + y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15) + y_true_oh = self._one_hot(y_true) + return float(-np.mean(np.sum(y_true_oh * np.log(y_pred), axis=1))) + return float(np.mean((y_true - y_pred.flatten()) ** 2)) + + def _one_hot(self, y: np.ndarray) -> np.ndarray: + y = np.asarray(y) + if y.ndim == 2: + return y + oh = np.zeros((len(y), self.n_classes_)) + oh[np.arange(len(y)), y.astype(int)] = 1 + return oh - Returns: - Network output + def _compute_gradients(self, x: np.ndarray, y_true: np.ndarray, weights: np.ndarray) -> np.ndarray: + """Exact loss gradient: parameter-shift on circuit outputs, chain rule through the readout. + Each weight drives one RY or RZ gate, so d/dฮธ = ((ฮธ+ฯ€/2) - (ฮธ-ฯ€/2)) / 2. """ - try: - if hasattr(self.backend, 'execute_qnn'): - result = self.backend.execute_qnn( - input_data=x, - weights=weights, - quantum_layers=self.quantum_layers, - classical_layers=self.classical_layers, - encoding=self.encoding, - measurement=self.measurement, - shots=self.shots - ) - return result - else: - return self._fallback_forward_pass(x, weights) - except Exception as e: - logger.error(f"Forward pass failed: {e}") - return self._fallback_forward_pass(x, weights) - - def _fallback_forward_pass(self, x: np.ndarray, weights: np.ndarray) -> np.ndarray: - """Fallback forward pass implementation.""" - logger.warning("Using fallback forward pass") - batch_size = x.shape[0] - output_size = self.n_classes_ if self.task_type == 'classification' else 1 - return np.random.random((batch_size, output_size)) - - def _compute_loss(self, y_true: np.ndarray, y_pred: np.ndarray) -> float: - """Compute loss function.""" + z = self._circuit_outputs(x, weights) + n = len(x) if self.task_type == 'classification': - # Cross-entropy loss - y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15) # Avoid log(0) - if len(y_true.shape) == 1: - # Convert to one-hot if needed - y_true_oh = np.zeros((len(y_true), self.n_classes_)) - y_true_oh[np.arange(len(y_true)), y_true.astype(int)] = 1 - y_true = y_true_oh - return -np.mean(np.sum(y_true * np.log(y_pred), axis=1)) + p = self._readout(z) + dL_dz = np.zeros_like(z) + k = min(self.n_classes_, z.shape[1]) + dL_dz[:, :k] = (self._READOUT_SCALE * (p - self._one_hot(y_true)) / n)[:, :k] else: - # Mean squared error for regression - return np.mean((y_true - y_pred.flatten()) ** 2) + dL_dz = np.zeros_like(z) + dL_dz[:, 0] = 2.0 * (z[:, 0] - np.asarray(y_true, dtype=float)) / n - def _compute_gradients(self, x: np.ndarray, y_true: np.ndarray, weights: np.ndarray) -> np.ndarray: - """Compute gradients using parameter-shift rule.""" gradients = np.zeros_like(weights) shift = np.pi / 2 - for i in range(len(weights)): - # Forward shift - weights_plus = weights.copy() - weights_plus[i] += shift - y_pred_plus = self._forward_pass(x, weights_plus) - loss_plus = self._compute_loss(y_true, y_pred_plus) - - # Backward shift - weights_minus = weights.copy() - weights_minus[i] -= shift - y_pred_minus = self._forward_pass(x, weights_minus) - loss_minus = self._compute_loss(y_true, y_pred_minus) - - # Gradient via parameter-shift rule - gradients[i] = 0.5 * (loss_plus - loss_minus) - + w_plus = weights.copy() + w_plus[i] += shift + w_minus = weights.copy() + w_minus[i] -= shift + dz = 0.5 * (self._circuit_outputs(x, w_plus) - self._circuit_outputs(x, w_minus)) + gradients[i] = float(np.sum(dL_dz * dz)) return gradients def _update_weights(self, gradients: np.ndarray) -> None: diff --git a/src/superquantx/algorithms/quantum_svm.py b/src/superquantx/algorithms/quantum_svm.py index a5a0e44..6e9e278 100644 --- a/src/superquantx/algorithms/quantum_svm.py +++ b/src/superquantx/algorithms/quantum_svm.py @@ -35,7 +35,10 @@ class QuantumSVM(SupervisedQuantumAlgorithm): feature_map: Type of quantum feature map ('ZZFeatureMap', 'PauliFeatureMap', etc.) feature_map_reps: Number of repetitions in the feature map C: Regularization parameter for SVM - gamma: Kernel coefficient (for RBF-like quantum kernels) + gamma: Quantum kernel bandwidth. Features are multiplied by ``gamma`` + before encoding (after standardisation). Tuning it matters: small + bandwidths avoid exponential kernel concentration (Shaydulin and + Wild, 2022). ``None`` means 1.0. quantum_kernel: Custom quantum kernel function shots: Number of measurement shots **kwargs: Additional parameters @@ -83,26 +86,12 @@ def __init__( logger.info(f"Initialized QuantumSVM with feature_map={feature_map}, reps={feature_map_reps}") def _create_feature_map(self, n_features: int) -> Any: - """Create quantum feature map circuit.""" - try: - if hasattr(self.backend, 'create_feature_map'): - return self.backend.create_feature_map( - n_features=n_features, - feature_map=self.feature_map, - reps=self.feature_map_reps - ) - else: - # Fallback implementation - return self._default_feature_map(n_features) - except Exception as e: - logger.error(f"Failed to create feature map: {e}") - return self._default_feature_map(n_features) - - def _default_feature_map(self, n_features: int) -> Any: - """Create default feature map when backend doesn't provide one.""" - # This would be implemented based on the backend - logger.warning("Using default feature map - results may vary") - return None + """Create the feature-map specification on the backend.""" + return self.backend.create_feature_map( + n_features=n_features, + feature_map=self.feature_map, + reps=self.feature_map_reps, + ) def _compute_quantum_kernel(self, X1: np.ndarray, X2: np.ndarray | None = None) -> np.ndarray: """Compute quantum kernel matrix between data points. @@ -117,6 +106,9 @@ def _compute_quantum_kernel(self, X1: np.ndarray, X2: np.ndarray | None = None) """ if X2 is None: X2 = X1 + if self.gamma is not None: + X1 = np.asarray(X1) * self.gamma + X2 = np.asarray(X2) * self.gamma n1, n2 = len(X1), len(X2) kernel_matrix = np.zeros((n1, n2)) @@ -127,20 +119,13 @@ def _compute_quantum_kernel(self, X1: np.ndarray, X2: np.ndarray | None = None) for j in range(n2): kernel_matrix[i, j] = self.quantum_kernel(X1[i], X2[j]) else: - # Use backend's kernel computation - try: - kernel_matrix = self.backend.compute_kernel_matrix( - X1, X2, - feature_map=self.feature_map_circuit_, - shots=self.shots - ) - except Exception as e: - logger.error(f"Quantum kernel computation failed: {e}") - # Fallback to classical RBF kernel - from sklearn.metrics.pairwise import rbf_kernel - gamma = self.gamma if self.gamma else 1.0 / X1.shape[1] - kernel_matrix = rbf_kernel(X1, X2, gamma=gamma) - logger.warning("Using classical RBF kernel as fallback") + # Fidelity kernel from the backend. Errors propagate: there is + # deliberately no silent classical fallback. + kernel_matrix = self.backend.compute_kernel_matrix( + X1, X2, + feature_map=self.feature_map_circuit_, + shots=self.shots + ) return kernel_matrix @@ -182,8 +167,8 @@ def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'QuantumSVM': self.svm.fit(self.kernel_matrix_, y) self.is_fitted = True - # Compute training accuracy - train_predictions = self.predict(X) + # Training accuracy straight from the training kernel (X is already scaled) + train_predictions = self.svm.predict(self.kernel_matrix_) train_accuracy = accuracy_score(y, train_predictions) self.training_history.append({ @@ -244,7 +229,7 @@ def predict_proba(self, X: np.ndarray, **kwargs) -> np.ndarray: # Need to recreate SVM with probability=True for probabilities if not hasattr(self.svm, 'predict_proba'): logger.warning("Probability prediction not available, returning decision scores") - return self.decision_function(X) + return self.svm.decision_function(test_kernel) return self.svm.predict_proba(test_kernel) diff --git a/src/superquantx/algorithms/vqe.py b/src/superquantx/algorithms/vqe.py index 029648d..63dc6b8 100644 --- a/src/superquantx/algorithms/vqe.py +++ b/src/superquantx/algorithms/vqe.py @@ -11,6 +11,7 @@ import numpy as np from scipy.optimize import minimize +from ..backends.base_backend import hamiltonian_to_matrix from .base_algorithm import OptimizationQuantumAlgorithm @@ -59,9 +60,11 @@ def __init__( initial_params: np.ndarray | None = None, include_custom_gates: bool = False, client = None, + reps: int = 1, **kwargs ) -> None: super().__init__(backend=backend, shots=shots, **kwargs) + self.reps = reps self.hamiltonian = hamiltonian self.ansatz = ansatz @@ -76,6 +79,7 @@ def __init__( self.n_params = None self.ansatz_circuit = None self.hamiltonian_terms = None + self.hamiltonian_matrix = None # Convergence tracking self.energy_history = [] @@ -87,107 +91,49 @@ def __init__( logger.info(f"Initialized VQE with ansatz={ansatz}, optimizer={optimizer}") def _initialize_hamiltonian(self) -> None: - """Initialize and validate Hamiltonian.""" - if isinstance(self.hamiltonian, np.ndarray): - if len(self.hamiltonian.shape) != 2 or self.hamiltonian.shape[0] != self.hamiltonian.shape[1]: - raise ValueError("Hamiltonian must be a square matrix") - self.n_qubits = int(np.log2(self.hamiltonian.shape[0])) - if 2**self.n_qubits != self.hamiltonian.shape[0]: - raise ValueError("Hamiltonian dimension must be a power of 2") - - # Decompose Hamiltonian into Pauli strings if needed - self.hamiltonian_terms = self._decompose_hamiltonian() - else: - # Assume it's already in the correct format for the backend - self.hamiltonian_terms = self.hamiltonian - self.n_qubits = self._infer_qubits_from_hamiltonian() - - def _decompose_hamiltonian(self) -> list[tuple[float, str]]: - """Decompose Hamiltonian into Pauli string representation.""" - if hasattr(self.backend, 'decompose_hamiltonian'): - return self.backend.decompose_hamiltonian(self.hamiltonian) - else: - return self._fallback_decomposition() - - def _fallback_decomposition(self) -> list[tuple[float, str]]: - """Fallback Hamiltonian decomposition.""" - logger.warning("Using fallback Hamiltonian decomposition") - # Simple placeholder - would need proper Pauli decomposition - return [(1.0, 'Z0'), (0.5, 'Z1')] - - def _infer_qubits_from_hamiltonian(self) -> int: - """Infer number of qubits from Hamiltonian representation.""" - if hasattr(self.hamiltonian_terms, '__len__'): - return 2 # Default fallback - return 2 - - def _create_ansatz_circuit(self, params: np.ndarray) -> Any: - """Create ansatz circuit with given parameters. - - Args: - params: Circuit parameters - - Returns: - Parameterized quantum circuit + """Convert the Hamiltonian to a dense matrix and infer the qubit count. + Accepted formats: square numpy matrix, ``superquantx.gates.Hamiltonian``, + a dict such as ``{"ZZ": 1.0, "XI": 0.5}``, a list of ``(coeff, "ZZ")`` + pairs, or a PennyLane / Qiskit operator. Pauli label character i acts + on qubit i. ``None`` defers setup until ``fit(hamiltonian)``. """ - try: - if hasattr(self.backend, 'create_ansatz'): - return self.backend.create_ansatz( - ansatz_type=self.ansatz, - n_qubits=self.n_qubits, - params=params, - include_custom_gates=self.include_custom_gates - ) - else: - return self._fallback_ansatz(params) - except Exception as e: - logger.error(f"Failed to create ansatz circuit: {e}") - return self._fallback_ansatz(params) + if self.hamiltonian is None: + return + matrix = hamiltonian_to_matrix(self.hamiltonian) + dim = matrix.shape[0] + self.n_qubits = int(round(np.log2(dim))) + if 2 ** self.n_qubits != dim: + raise ValueError("Hamiltonian dimension must be a power of 2") + if not np.allclose(matrix, matrix.conj().T, atol=1e-10): + raise ValueError("Hamiltonian must be Hermitian") + self.hamiltonian_matrix = matrix + self.hamiltonian_terms = matrix + + def exact_ground_energy(self) -> float: + """Classical baseline: lowest eigenvalue from exact diagonalisation.""" + return float(np.linalg.eigvalsh(self.hamiltonian_matrix)[0]) - def _fallback_ansatz(self, params: np.ndarray) -> Any: - """Fallback ansatz implementation.""" - logger.warning("Using fallback ansatz implementation") - return None + def _create_ansatz_circuit(self, params: np.ndarray) -> Any: + """Build the ansatz circuit on the backend for the given parameters.""" + if callable(self.ansatz): + return self.ansatz(self.backend, self.n_qubits, params) + return self.backend.create_ansatz( + ansatz_type=self.ansatz, + n_qubits=self.n_qubits, + params=params, + include_custom_gates=self.include_custom_gates, + reps=self.reps, + ) def _compute_expectation_value(self, params: np.ndarray) -> float: - """Compute expectation value โŸจฯˆ(ฮธ)|H|ฯˆ(ฮธ)โŸฉ. - - Args: - params: Circuit parameters - - Returns: - Hamiltonian expectation value - - """ - try: - # Create ansatz circuit - circuit = self._create_ansatz_circuit(params) - - # Compute expectation value - if hasattr(self.backend, 'compute_expectation'): - expectation = self.backend.compute_expectation( - circuit=circuit, - hamiltonian=self.hamiltonian_terms, - shots=self.shots - ) - else: - expectation = self._fallback_expectation(circuit, params) - - # Store energy history - self.energy_history.append(expectation) - - return float(expectation) - - except Exception as e: - logger.error(f"Error computing expectation value: {e}") - return float('inf') - - def _fallback_expectation(self, circuit: Any, params: np.ndarray) -> float: - """Fallback expectation value computation.""" - logger.warning("Using fallback expectation computation") - # Simple placeholder - would compute โŸจฯˆ|H|ฯˆโŸฉ classically - return np.random.random() - 0.5 + """Exact expectation value on the backend's statevector.""" + circuit = self._create_ansatz_circuit(params) + expectation = float(self.backend.compute_expectation( + circuit=circuit, hamiltonian=self.hamiltonian_matrix, shots=self.shots + )) + self.energy_history.append(expectation) + return expectation def _compute_gradient(self, params: np.ndarray) -> np.ndarray: """Compute parameter gradients using parameter-shift rule. @@ -223,7 +169,7 @@ def fit(self, X: np.ndarray | None = None, y: np.ndarray | None = None, **kwargs """Fit VQE (setup for optimization). Args: - X: Not used in VQE + X: Optional Hamiltonian, if none was given to the constructor y: Not used in VQE **kwargs: Additional parameters @@ -231,6 +177,11 @@ def fit(self, X: np.ndarray | None = None, y: np.ndarray | None = None, **kwargs Self for method chaining """ + if X is not None: + self.hamiltonian = X + self._initialize_hamiltonian() + if self.hamiltonian_matrix is None: + raise ValueError("VQE needs a Hamiltonian: pass it to the constructor or fit()") logger.info(f"Setting up VQE for {self.n_qubits} qubits") # Determine number of parameters based on ansatz @@ -249,49 +200,24 @@ def fit(self, X: np.ndarray | None = None, y: np.ndarray | None = None, **kwargs return self def _get_ansatz_param_count(self) -> int: - """Get number of parameters for the ansatz.""" - if hasattr(self.backend, 'get_ansatz_param_count'): - return self.backend.get_ansatz_param_count(self.ansatz, self.n_qubits) - else: - # Default parameter counts for common ansatzes - param_counts = { - 'RealAmplitudes': 2 * self.n_qubits, - 'UCCSD': 4 * self.n_qubits, # Simplified estimate - 'EfficientSU2': 3 * self.n_qubits, - 'TwoLocal': 2 * self.n_qubits, - } - return param_counts.get(self.ansatz, 2 * self.n_qubits) + """Number of parameters for the ansatz.""" + if callable(self.ansatz): + if self.initial_params is None: + raise ValueError("A callable ansatz needs initial_params to fix the parameter count") + return len(self.initial_params) + return self.backend.ansatz_param_count(self.ansatz, self.n_qubits, self.reps) def _generate_initial_params(self) -> np.ndarray: - """Generate random initial parameters.""" - return np.random.uniform(-np.pi, np.pi, self.n_params) + """Generate random initial parameters (seeded when ``seed`` is set).""" + rng = np.random.default_rng(self.seed) + return rng.uniform(-np.pi, np.pi, self.n_params) def predict(self, X: np.ndarray | None = None, **kwargs) -> np.ndarray: - """Get ground state wavefunction coefficients. - - Args: - X: Not used - **kwargs: Additional parameters - - Returns: - Ground state wavefunction - - """ - if not self.optimal_params_: + """Return the optimised state vector (qubit 0 most significant).""" + if self.optimal_params_ is None: raise ValueError("VQE must be optimized before prediction") - - # Create circuit with optimal parameters circuit = self._create_ansatz_circuit(self.optimal_params_) - - # Get state vector - if hasattr(self.backend, 'get_statevector'): - statevector = self.backend.get_statevector(circuit) - else: - # Fallback: return random normalized state - statevector = np.random.random(2**self.n_qubits) + 1j * np.random.random(2**self.n_qubits) - statevector /= np.linalg.norm(statevector) - - return np.array(statevector) + return self.backend.statevector_big_endian(circuit) def _run_optimization(self, objective_function=None, initial_params: np.ndarray | None = None, **kwargs): """Run VQE optimization. @@ -335,7 +261,7 @@ def objective(params): method=self.optimizer, options={ 'maxiter': self.maxiter, - 'disp': True + 'disp': False }, jac=self._compute_gradient if self.optimizer in ['L-BFGS-B', 'SLSQP'] else None ) @@ -348,6 +274,7 @@ def objective(params): return { 'optimal_params': self.optimal_params_, 'ground_energy': self.optimal_value_, + 'exact_energy': self.exact_ground_energy(), 'success': result.success, 'message': result.message, 'n_iterations': result.nfev, @@ -373,7 +300,7 @@ def get_energy_landscape(self, param_indices: list[int], param_ranges: list[tupl if len(param_indices) != 2: raise ValueError("Energy landscape visualization supports only 2 parameters") - if not self.optimal_params_: + if self.optimal_params_ is None: raise ValueError("VQE must be optimized to compute landscape") param1_range = np.linspace(*param_ranges[0], resolution) @@ -458,7 +385,7 @@ def compare_with_exact(self, exact_ground_energy: float) -> dict[str, Any]: Comparison analysis """ - if not self.optimal_value_: + if self.optimal_value_ is None: raise ValueError("VQE must be optimized for comparison") error = abs(self.optimal_value_ - exact_ground_energy) @@ -495,13 +422,13 @@ def set_params(self, **params) -> 'VQE': def find_ground_state(self) -> float: """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: Ground state energy - + Example: >>> vqe = VQE(backend='simulator', hamiltonian=hamiltonian) >>> ground_energy = vqe.find_ground_state() @@ -509,69 +436,56 @@ def find_ground_state(self) -> float: # Fit if not already fitted if not self.is_fitted: self.fit() - + # Run optimization self._run_optimization() - + # Return the optimal energy return self.optimal_value_ +# Two-qubit H2 Hamiltonian in STO-3G at 0.735 Angstrom after parity mapping +# with two-qubit reduction (electronic energy only; the exact ground energy is +# -1.857275 Ha, add 0.719969 Ha nuclear repulsion for the total -1.137306 Ha). +H2_STO3G_0735 = { + "II": -1.052373245772859, + "IZ": 0.39793742484318045, + "ZI": -0.39793742484318045, + "ZZ": -0.01128010425623538, + "XX": 0.18093119978423156, +} + + def create_vqe_for_molecule( molecule_name: str, - bond_distance: float = None, + bond_distance: float | None = None, backend: str = 'simulator', - ansatz: str = 'UCCSD', + ansatz: str = 'RealAmplitudes', optimizer: str = 'COBYLA', - client = None + client = None, + **kwargs, ) -> VQE: - """Create a VQE instance pre-configured for molecular simulation. - - Args: - molecule_name: Name of the molecule (e.g., 'H2', 'LiH') - bond_distance: Bond distance for the molecule (uses default if None) - backend: Quantum backend to use - ansatz: Ansatz circuit type - optimizer: Classical optimizer - client: Optional client for quantum execution - - Returns: - Configured VQE instance + """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. """ - # Import molecular data utilities - try: - from ..datasets.molecular import get_molecular_hamiltonian - hamiltonian = get_molecular_hamiltonian(molecule_name, bond_distance) - except ImportError: - # Fallback: create simple hamiltonian for testing - from ..gates import Hamiltonian - - if molecule_name.upper() == 'H2': - # Simple H2 Hamiltonian approximation as Pauli strings - hamiltonian_dict = { - "ZZ": -1.0523732, - "ZI": -0.39793742, - "IZ": -0.39793742, - "XX": -0.01128010, - "YY": 0.01128010 - } - hamiltonian = Hamiltonian.from_dict(hamiltonian_dict) - elif molecule_name.upper() in ['LIH', 'H2O', 'NH3']: - # Generic 2-qubit Hamiltonian for other molecules - hamiltonian_dict = { - "ZI": -1.0, - "IZ": 0.5, - "XX": 0.2 - } - hamiltonian = Hamiltonian.from_dict(hamiltonian_dict) - else: - raise ValueError(f"Unknown molecule: {molecule_name}") - + if molecule_name.upper() != 'H2': + raise NotImplementedError( + f"No built-in Hamiltonian for {molecule_name}. Build one with a chemistry " + "package and pass it to VQE(hamiltonian=...)." + ) + if bond_distance is not None and abs(bond_distance - 0.735) > 0.02: + raise NotImplementedError( + "Only the H2 equilibrium geometry (0.735 Angstrom) is built in." + ) return VQE( - hamiltonian=hamiltonian, + hamiltonian=dict(H2_STO3G_0735), ansatz=ansatz, backend=backend, optimizer=optimizer, - client=client + client=client, + **kwargs, ) diff --git a/src/superquantx/backends/__init__.py b/src/superquantx/backends/__init__.py index 2946351..0b04e0e 100644 --- a/src/superquantx/backends/__init__.py +++ b/src/superquantx/backends/__init__.py @@ -180,6 +180,7 @@ def list_available_backends() -> dict[str, dict[str, Any]]: 'class': backend_class.__name__, 'description': getattr(backend_class, '__doc__', '').split('\n')[0] if backend_class.__doc__ else '', 'capabilities': getattr(test_instance, 'capabilities', {}), + 'gate_model': getattr(test_instance, 'gate_model', True), } except ImportError: backend_info[name] = { diff --git a/src/superquantx/backends/base_backend.py b/src/superquantx/backends/base_backend.py index 44505b9..5724e2e 100644 --- a/src/superquantx/backends/base_backend.py +++ b/src/superquantx/backends/base_backend.py @@ -6,6 +6,8 @@ import logging from abc import ABC, abstractmethod +from dataclasses import dataclass +from functools import reduce from typing import Any import numpy as np @@ -13,6 +15,128 @@ logger = logging.getLogger(__name__) +FEATURE_MAPS = ('ZZFeatureMap', 'ZFeatureMap', 'PauliFeatureMap', 'AngleEncoding') + +_PAULI = { + 'I': np.eye(2, dtype=complex), + 'X': np.array([[0, 1], [1, 0]], dtype=complex), + 'Y': np.array([[0, -1j], [1j, 0]], dtype=complex), + 'Z': np.array([[1, 0], [0, -1]], dtype=complex), +} + + +@dataclass(frozen=True) +class FeatureMapSpec: + """Backend-independent description of a data-encoding feature map.""" + + name: str + n_features: int + reps: int = 2 + + +def _pauli_label_to_dense(label: str, n_qubits: int) -> str: + """Normalise 'ZI' or indexed forms like 'Z0 X2' to a dense label.""" + label = label.strip().upper() + if any(ch.isdigit() for ch in label): + dense = ['I'] * n_qubits + token = '' + for ch in label.replace('*', ' ') + ' ': + if ch.isalpha(): + if token: + dense[int(token[1:])] = token[0] + token = ch + elif ch.isdigit(): + token += ch + elif token: + dense[int(token[1:])] = token[0] + token = '' + return ''.join(dense) + return label + + +def pauli_string_matrix(label: str) -> np.ndarray: + """Dense matrix of a Pauli label; character i acts on qubit i (np.kron order).""" + return reduce(np.kron, [_PAULI[c] for c in label.upper()]) + + +def hamiltonian_to_matrix(hamiltonian: Any, n_qubits: int | None = None) -> np.ndarray: + """Convert supported Hamiltonian formats to a dense matrix. + + The convention is big-endian: in a label such as ``"ZI"`` the first + character acts on qubit 0, which is the most significant bit. + """ + if isinstance(hamiltonian, np.ndarray): + H = np.asarray(hamiltonian, dtype=complex) + if H.ndim != 2 or H.shape[0] != H.shape[1]: + raise ValueError("Hamiltonian matrix must be square") + return H + + terms: list[tuple[complex, str]] | None = None + if isinstance(hamiltonian, dict): + terms = [(c, k) for k, c in hamiltonian.items()] + elif isinstance(hamiltonian, (list, tuple)) and hamiltonian and all( + isinstance(t, (list, tuple)) and len(t) == 2 for t in hamiltonian + ): + terms = [(a, b) if isinstance(b, str) else (b, a) for a, b in hamiltonian] + elif hasattr(hamiltonian, 'pauli_strings'): # superquantx.gates.Hamiltonian + terms = [(p.coefficient, p.pauli_ops) for p in hamiltonian.pauli_strings] + elif hasattr(hamiltonian, 'to_list') and hasattr(hamiltonian, 'num_qubits'): + # qiskit SparsePauliOp labels are little-endian; reverse them + terms = [(c, lbl[::-1]) for lbl, c in hamiltonian.to_list()] + elif hasattr(hamiltonian, 'wires') and hasattr(hamiltonian, 'terms'): + import pennylane as qml # PennyLane operator + n = n_qubits if n_qubits is not None else len(hamiltonian.wires) + return np.asarray(qml.matrix(hamiltonian, wire_order=list(range(n))), dtype=complex) + + if terms is None: + raise TypeError( + f"Unsupported Hamiltonian type {type(hamiltonian).__name__}. Use a matrix, " + "a dict of Pauli labels, a list of (coeff, label) pairs or gates.Hamiltonian." + ) + + if n_qubits is None: + import re + if any(ch.isdigit() for _, lbl in terms for ch in lbl): + n_qubits = 1 + max(int(m) for _, lbl in terms for m in re.findall(r'\d+', lbl)) + else: + n_qubits = len(terms[0][1].strip()) + H = np.zeros((2 ** n_qubits, 2 ** n_qubits), dtype=complex) + for coeff, lbl in terms: + dense = _pauli_label_to_dense(lbl, n_qubits) + if len(dense) != n_qubits: + raise ValueError(f"Pauli label '{lbl}' does not act on {n_qubits} qubits") + H += complex(coeff) * pauli_string_matrix(dense) + return H + + +def hamiltonian_num_qubits(hamiltonian: Any) -> int: + """Infer the number of qubits a Hamiltonian acts on.""" + if isinstance(hamiltonian, np.ndarray): + n = int(round(np.log2(hamiltonian.shape[0]))) + if 2 ** n != hamiltonian.shape[0]: + raise ValueError("Hamiltonian dimension must be a power of 2") + return n + return int(round(np.log2(hamiltonian_to_matrix(hamiltonian).shape[0]))) + + +def _as_weight_matrix(problem_instance: Any, n_qubits: int) -> np.ndarray: + W = np.asarray(problem_instance, dtype=float) + if W.ndim != 2 or W.shape != (n_qubits, n_qubits): + raise NotImplementedError( + "The built-in QAOA circuit supports weighted MaxCut only: pass an " + f"{n_qubits}x{n_qubits} adjacency matrix as the problem instance." + ) + return W + + +def maxcut_values(W: np.ndarray) -> np.ndarray: + """Cut value of every bitstring (big-endian index) for weight matrix W.""" + n = W.shape[0] + idx = np.arange(2 ** n) + bits = (idx[:, None] >> (n - 1 - np.arange(n))[None, :]) & 1 + diff = bits[:, :, None] != bits[:, None, :] + return 0.5 * np.einsum('kij,ij->k', diff, np.triu(W, 1) + np.triu(W, 1).T) + class BaseBackend(ABC): """Abstract base class for quantum computing backends. @@ -27,6 +151,9 @@ class BaseBackend(ABC): """ + #: False for backends that are not gate-model devices (e.g. annealers). + gate_model: bool = True + def __init__(self, device: str | None = None, shots: int = 1024, **kwargs): self.device = device self.shots = shots @@ -71,52 +198,246 @@ def get_statevector(self, circuit: Any) -> np.ndarray: pass # ======================================================================== - # Quantum Algorithm Support + # Qubit ordering helpers # ======================================================================== + # + # Different SDKs order qubits differently in bitstrings and statevectors. + # Qiskit and the built-in simulator are little-endian (qubit 0 is the + # rightmost bit); Cirq, PennyLane, Braket and TKET are big-endian (qubit 0 + # is the leftmost bit). The generic algorithm code below always works in a + # big-endian convention (qubit i is bit i from the left, matching + # np.kron ordering of Pauli strings such as "ZI"). The convention of each + # backend is detected once, empirically, by preparing |1> on qubit 0. + + def _bit_order(self, kind: str) -> str: + """Return 'big' or 'little' for this backend's counts or statevectors.""" + cache = self.__dict__.setdefault('_sqx_bit_order', {}) + if kind in cache: + return cache[kind] + + circuit = self.create_circuit(2) + circuit = self.add_gate(circuit, 'X', 0) + if kind == 'statevector': + sv = np.asarray(self.get_statevector(circuit)).ravel() + idx = int(np.argmax(np.abs(sv))) + order = 'little' if idx == 1 else 'big' + elif kind == 'counts': + circuit = self.add_measurement(circuit) + counts = self.execute_circuit(circuit, shots=8).get('counts', {}) + if not counts: + raise RuntimeError( + f"{self.__class__.__name__} returned no counts while probing qubit order" + ) + key = str(max(counts, key=counts.get)).replace(' ', '') + order = 'little' if key == '01' else 'big' + else: + raise ValueError(f"Unknown ordering kind: {kind}") + + cache[kind] = order + return order + + def counts_big_endian(self, counts: dict[str, int]) -> dict[str, int]: + """Return counts re-keyed so that character i is the value of qubit i.""" + if self._bit_order('counts') == 'big': + return {str(k).replace(' ', ''): int(v) for k, v in counts.items()} + return {str(k).replace(' ', '')[::-1]: int(v) for k, v in counts.items()} + + def statevector_big_endian(self, circuit: Any) -> np.ndarray: + """Statevector of ``circuit`` with qubit 0 as the most significant bit.""" + sv = np.asarray(self.get_statevector(circuit), dtype=complex).ravel() + n = int(round(np.log2(len(sv)))) + if 2 ** n != len(sv): + raise RuntimeError(f"Statevector length {len(sv)} is not a power of two") + if self._bit_order('statevector') == 'little' and n > 1: + sv = sv.reshape([2] * n).transpose(list(range(n))[::-1]).reshape(-1) + return sv - def create_feature_map(self, n_features: int, feature_map: str, reps: int = 1) -> Any: - """Create quantum feature map for data encoding.""" - logger.warning(f"Feature map '{feature_map}' not implemented in {self.__class__.__name__}") - return self.create_circuit(n_features) + # ======================================================================== + # Quantum Algorithm Support (generic, built on the primitives above) + # ======================================================================== + + def create_feature_map(self, n_features: int, feature_map: str = 'ZZFeatureMap', + reps: int = 2) -> 'FeatureMapSpec': + """Return a feature-map specification used by :meth:`compute_kernel_matrix`. + + Supported maps: ``ZZFeatureMap`` (Havlicek et al. 2019, linear + entanglement), ``ZFeatureMap`` (the same without entanglement), + ``PauliFeatureMap`` (RX/RY/RZ plus CNOT chain) and + ``AngleEncoding`` (one RY per feature). + """ + if feature_map not in FEATURE_MAPS: + raise ValueError( + f"Unknown feature map '{feature_map}'. Supported: {sorted(FEATURE_MAPS)}" + ) + return FeatureMapSpec(name=feature_map, n_features=n_features, reps=reps) + + def build_feature_map_circuit(self, x: np.ndarray, spec: 'FeatureMapSpec') -> Any: + """Build the backend-native circuit that encodes ``x`` with ``spec``.""" + n = spec.n_features + x = np.asarray(x, dtype=float).ravel() + if len(x) != n: + raise ValueError(f"Feature map expects {n} features, got {len(x)}") + circuit = self.create_circuit(n) + for _ in range(spec.reps): + if spec.name == 'ZZFeatureMap': + for i in range(n): + circuit = self.add_gate(circuit, 'H', i) + circuit = self.add_gate(circuit, 'RZ', i, [2.0 * x[i]]) + for i in range(n - 1): + phi = 2.0 * (np.pi - x[i]) * (np.pi - x[i + 1]) + circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) + circuit = self.add_gate(circuit, 'RZ', i + 1, [phi]) + circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) + elif spec.name == 'ZFeatureMap': + for i in range(n): + circuit = self.add_gate(circuit, 'H', i) + circuit = self.add_gate(circuit, 'RZ', i, [2.0 * x[i]]) + elif spec.name == 'PauliFeatureMap': + for i in range(n): + circuit = self.add_gate(circuit, 'RX', i, [x[i]]) + circuit = self.add_gate(circuit, 'RY', i, [x[i]]) + circuit = self.add_gate(circuit, 'RZ', i, [x[i]]) + for i in range(n - 1): + circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) + else: # AngleEncoding + for i in range(n): + circuit = self.add_gate(circuit, 'RY', i, [x[i]]) + return circuit def compute_kernel_matrix(self, X1: np.ndarray, X2: np.ndarray, - feature_map: Any, shots: int | None = None) -> np.ndarray: - """Compute quantum kernel matrix between data points.""" - logger.warning(f"Kernel matrix computation not implemented in {self.__class__.__name__}") - # Fallback to RBF kernel - from sklearn.metrics.pairwise import rbf_kernel - return rbf_kernel(X1, X2) + feature_map: Any = None, shots: int | None = None) -> np.ndarray: + """Fidelity quantum kernel K[i, j] = ||^2. + + Each data point is encoded with the feature map and simulated on this + backend; the kernel is computed exactly from the resulting statevectors + (``shots`` is accepted for API compatibility and ignored). This is a + real quantum-circuit kernel, but it is classically simulated, so it says + nothing about quantum advantage. + """ + X1 = np.atleast_2d(np.asarray(X1, dtype=float)) + X2 = np.atleast_2d(np.asarray(X2, dtype=float)) + if feature_map is None: + spec = self.create_feature_map(X1.shape[1]) + elif isinstance(feature_map, str): + spec = self.create_feature_map(X1.shape[1], feature_map) + elif isinstance(feature_map, FeatureMapSpec): + spec = feature_map + else: + raise TypeError( + "feature_map must be a FeatureMapSpec, a feature map name, or None; " + f"got {type(feature_map).__name__}" + ) + + def states(X: np.ndarray) -> np.ndarray: + return np.array([ + self.statevector_big_endian(self.build_feature_map_circuit(x, spec)) + for x in X + ]) + + S1 = states(X1) + S2 = S1 if X2 is X1 or (X2.shape == X1.shape and np.array_equal(X1, X2)) else states(X2) + return np.abs(S1.conj() @ S2.T) ** 2 + + def ansatz_param_count(self, ansatz_type: str, n_qubits: int, reps: int = 1) -> int: + """Number of parameters used by :meth:`create_ansatz`.""" + if ansatz_type == 'EfficientSU2': + return 2 * n_qubits * (reps + 1) + if ansatz_type in ('RealAmplitudes', 'TwoLocal'): + return n_qubits * (reps + 1) + raise ValueError( + f"Ansatz '{ansatz_type}' is not implemented. Use 'RealAmplitudes', " + "'EfficientSU2' or 'TwoLocal', or pass a callable ansatz." + ) def create_ansatz(self, ansatz_type: str, n_qubits: int, params: np.ndarray, - include_custom_gates: bool = False) -> Any: - """Create parameterized ansatz circuit.""" - logger.warning(f"Ansatz '{ansatz_type}' not implemented in {self.__class__.__name__}") - return self.create_circuit(n_qubits) + include_custom_gates: bool = False, reps: int | None = None) -> Any: + """Build a hardware-efficient ansatz with this backend's own gates. + + ``RealAmplitudes``/``TwoLocal``: ``reps`` layers of RY on every qubit + followed by a linear CNOT chain, plus a final RY layer. + ``EfficientSU2``: the same structure with RY and RZ rotations. + """ + params = np.asarray(params, dtype=float).ravel() + per_layer = 2 * n_qubits if ansatz_type == 'EfficientSU2' else n_qubits + if reps is None: + reps = max(len(params) // per_layer - 1, 0) + expected = self.ansatz_param_count(ansatz_type, n_qubits, reps) + if len(params) != expected: + raise ValueError( + f"{ansatz_type} with {n_qubits} qubits and reps={reps} needs " + f"{expected} parameters, got {len(params)}" + ) + + circuit = self.create_circuit(n_qubits) + idx = 0 + for layer in range(reps + 1): + for q in range(n_qubits): + circuit = self.add_gate(circuit, 'RY', q, [params[idx]]) + idx += 1 + if ansatz_type == 'EfficientSU2': + circuit = self.add_gate(circuit, 'RZ', q, [params[idx]]) + idx += 1 + if layer < reps: + for q in range(n_qubits - 1): + circuit = self.add_gate(circuit, 'CNOT', [q, q + 1]) + return circuit def compute_expectation(self, circuit: Any, hamiltonian: Any, - shots: int | None = None) -> float: - """Compute expectation value of Hamiltonian.""" - logger.warning(f"Expectation computation not implemented in {self.__class__.__name__}") - return 0.0 + shots: int | None = None) -> float: + """Exact expectation value from this backend's statevector. + + ``hamiltonian`` may be a dense matrix (qubit 0 most significant), a + ``superquantx.gates.Hamiltonian``, a dict like ``{"ZI": -0.4}``, a list + of ``(coeff, "ZI")`` pairs, or a PennyLane / Qiskit operator. + ``shots`` is accepted for API compatibility and ignored. + """ + sv = self.statevector_big_endian(circuit) + n = int(round(np.log2(len(sv)))) + H = hamiltonian_to_matrix(hamiltonian, n) + return float(np.real(np.vdot(sv, H @ sv))) def create_qaoa_circuit(self, n_qubits: int, gammas: np.ndarray, betas: np.ndarray, - problem_hamiltonian: Any, mixer_hamiltonian: Any, - initial_state: Any, problem_instance: Any) -> Any: - """Create QAOA circuit with given parameters.""" - logger.warning(f"QAOA circuit not implemented in {self.__class__.__name__}") - return self.create_circuit(n_qubits) + problem_hamiltonian: Any, mixer_hamiltonian: Any, + initial_state: Any, problem_instance: Any) -> Any: + """QAOA circuit for weighted MaxCut given an adjacency matrix. + + Cost layer: exp(-i gamma w_ij Z_i Z_j / 2) per edge (CNOT, RZ, CNOT); + mixer layer: RX(2 beta) on every qubit; initial state |+>^n. + """ + W = _as_weight_matrix(problem_instance, n_qubits) + circuit = self.create_circuit(n_qubits) + for q in range(n_qubits): + circuit = self.add_gate(circuit, 'H', q) + for gamma, beta in zip(gammas, betas, strict=True): + for i in range(n_qubits): + for j in range(i + 1, n_qubits): + if W[i, j] != 0: + circuit = self.add_gate(circuit, 'CNOT', [i, j]) + circuit = self.add_gate(circuit, 'RZ', j, [float(gamma * W[i, j])]) + circuit = self.add_gate(circuit, 'CNOT', [i, j]) + for q in range(n_qubits): + circuit = self.add_gate(circuit, 'RX', q, [float(2 * beta)]) + return circuit def execute_qaoa(self, circuit: Any, problem_hamiltonian: Any, problem_instance: Any, - shots: int | None = None) -> float: - """Execute QAOA circuit and return expectation value.""" - logger.warning(f"QAOA execution not implemented in {self.__class__.__name__}") - return 0.0 + shots: int | None = None) -> float: + """Expected MaxCut value of the QAOA state (exact, from the statevector).""" + probs = np.abs(self.statevector_big_endian(circuit)) ** 2 + n = int(round(np.log2(len(probs)))) + W = _as_weight_matrix(problem_instance, n) + return float(probs @ maxcut_values(W)) def sample_circuit(self, circuit: Any, shots: int | None = None) -> np.ndarray: - """Sample bit strings from quantum circuit.""" + """Sample bitstrings; row k column i is the measured value of qubit i.""" + circuit = self.add_measurement(circuit) result = self.execute_circuit(circuit, shots) - # Convert result to bit string array - return self._result_to_bitstrings(result) + if not result.get('counts'): + raise RuntimeError(f"{self.__class__.__name__} returned no counts: {result}") + counts = self.counts_big_endian(result['counts']) + rows = [] + for bitstring, count in counts.items(): + rows.extend([[int(b) for b in bitstring]] * int(count)) + return np.array(rows, dtype=int) # ======================================================================== # Data Encoding and Processing @@ -138,16 +459,9 @@ def encode_data_point(self, data: np.ndarray, encoding: str, n_qubits: int) -> A def _amplitude_encoding(self, circuit: Any, data: np.ndarray) -> Any: """Amplitude encoding of data.""" - # Normalize data - norm = np.linalg.norm(data) - if norm > 0: - data / norm - else: - pass - - # Simple implementation - would need proper state preparation - logger.warning("Amplitude encoding not fully implemented") - return circuit + raise NotImplementedError( + "Amplitude encoding is not implemented; use 'angle' or 'basis' encoding" + ) def _angle_encoding(self, circuit: Any, data: np.ndarray) -> Any: """Angle encoding of data into rotation gates.""" @@ -171,13 +485,17 @@ def _basis_encoding(self, circuit: Any, data: np.ndarray) -> Any: def compute_quantum_distance(self, x1: np.ndarray, x2: np.ndarray, metric: str, encoding: str, n_qubits: int, shots: int) -> float: - """Compute quantum distance between two data points.""" - # Encode both data points - self.encode_data_point(x1, encoding, n_qubits) - self.encode_data_point(x2, encoding, n_qubits) - - # Simple distance approximation using overlap - # This is a placeholder - actual implementation would use swap test or similar + """Distance between two data points. + + Only ``metric='fidelity'`` uses quantum states: it angle-encodes both + points and returns sqrt(1 - ||^2) computed from statevectors. + ``'euclidean'`` and ``'manhattan'`` are plain classical distances. + """ + if metric == 'fidelity': + spec = FeatureMapSpec(name='AngleEncoding', n_features=len(x1), reps=1) + s1 = self.statevector_big_endian(self.build_feature_map_circuit(x1, spec)) + s2 = self.statevector_big_endian(self.build_feature_map_circuit(x2, spec)) + return float(np.sqrt(max(0.0, 1.0 - abs(np.vdot(s1, s2)) ** 2))) if metric == 'euclidean': return np.linalg.norm(x1 - x2) elif metric == 'manhattan': @@ -189,8 +507,8 @@ def execute_qnn(self, input_data: np.ndarray, weights: np.ndarray, quantum_layers: list[dict], classical_layers: list[dict], encoding: str, measurement: str, shots: int) -> np.ndarray: """Execute quantum neural network.""" - input_data.shape[0] - n_qubits = len(weights) // len(quantum_layers) if quantum_layers else 1 + # Each variational layer holds an RY and an RZ angle per qubit. + n_qubits = len(weights) // (2 * len(quantum_layers)) if quantum_layers else input_data.shape[1] # Get expected output size from classical layers expected_output_size = None @@ -203,10 +521,7 @@ def execute_qnn(self, input_data: np.ndarray, weights: np.ndarray, outputs = [] for sample in input_data: - # Create circuit - circuit = self.create_circuit(n_qubits) - - # Encode input data + # Encode input data into a fresh circuit circuit = self.encode_data_point(sample, encoding, n_qubits) # Add variational layers @@ -226,7 +541,6 @@ def execute_qnn(self, input_data: np.ndarray, weights: np.ndarray, result = self._result_to_probabilities(result) # Apply classical layers if present - len(result) if classical_layers and expected_output_size: # Simple linear transformation to get desired output size if len(result) != expected_output_size: @@ -281,8 +595,7 @@ def _result_to_bitstrings(self, result: dict[str, Any]) -> np.ndarray: for _ in range(count): bitstrings.append([int(b) for b in bitstring]) return np.array(bitstrings) - else: - return np.array([[0, 1]]) # Placeholder + raise ValueError(f"Result has no 'counts' entry: {sorted(result)}") def _result_to_probabilities(self, result: dict[str, Any]) -> np.ndarray: """Convert execution result to probability array.""" @@ -293,13 +606,19 @@ def _result_to_probabilities(self, result: dict[str, Any]) -> np.ndarray: for bitstring in sorted(counts.keys()): probs.append(counts[bitstring] / total_shots) return np.array(probs) - else: - return np.array([0.5, 0.5]) # Placeholder + raise ValueError(f"Result has no 'counts' entry: {sorted(result)}") def _compute_pauli_expectation(self, circuit: Any, pauli_strings: list[str]) -> np.ndarray: - """Compute expectation values of Pauli strings.""" - # Placeholder implementation - return np.random.random(len(pauli_strings)) * 2 - 1 + """Exact single-qubit Pauli expectations; ``pauli_strings[i]`` acts on qubit i.""" + sv = self.statevector_big_endian(circuit) + n = int(round(np.log2(len(sv)))) + values = [] + for i, p in enumerate(pauli_strings[:n]): + label = ['I'] * n + label[i] = p.upper() + H = hamiltonian_to_matrix({''.join(label): 1.0}, n) + values.append(float(np.real(np.vdot(sv, H @ sv)))) + return np.array(values) def get_version_info(self) -> dict[str, Any]: """Get backend version information.""" diff --git a/src/superquantx/backends/braket_backend.py b/src/superquantx/backends/braket_backend.py index 67ff39c..6844286 100644 --- a/src/superquantx/backends/braket_backend.py +++ b/src/superquantx/backends/braket_backend.py @@ -17,8 +17,8 @@ # Try to import AWS Braket try: from braket.circuits import Circuit as BraketCircuit - from braket.circuits import Gate, Instruction - from braket.circuits.gates import * + from braket.circuits import Instruction, Measure + from braket.circuits import gates as bg from braket.devices import LocalSimulator try: from braket.aws import AwsDevice @@ -83,7 +83,10 @@ def _initialize_backend(self) -> None: try: if self.device_name.startswith('local:'): # Local simulator - simulator_name = self.device_name.split('local:')[1] + # Accept 'local:braket_sv' and the documented 'local:braket/braket_sv' + simulator_name = self.device_name.split('local:', 1)[1] + if simulator_name.startswith('braket/'): + simulator_name = simulator_name[len('braket/'):] self._device = LocalSimulator(simulator_name) logger.info(f"Initialized Braket local simulator: {simulator_name}") @@ -149,133 +152,86 @@ def _get_native_gates(self) -> list[str]: # ======================================================================== def create_circuit(self, n_qubits: int) -> BraketCircuit: - """Create a Braket quantum circuit.""" + """Create a Braket circuit on ``n_qubits`` qubits. + + Braket circuits only know about qubits that carry an instruction, so an + identity is placed on every qubit to fix the register size. + """ if n_qubits > self._get_max_qubits(): - logger.warning(f"Requested {n_qubits} qubits exceeds device limit") + raise ValueError( + f"Requested {n_qubits} qubits exceeds the device limit of {self._get_max_qubits()}" + ) + circuit = BraketCircuit() + for q in range(n_qubits): + circuit.add_instruction(Instruction(bg.I(), q)) + return circuit - return BraketCircuit() + _GATES = { + 'i': 'I', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 'hadamard': 'H', + 's': 'S', 'sdg': 'Si', 't': 'T', 'tdg': 'Ti', + 'rx': 'Rx', 'ry': 'Ry', 'rz': 'Rz', 'p': 'PhaseShift', 'phase': 'PhaseShift', + 'phaseshift': 'PhaseShift', 'cphaseshift': 'CPhaseShift', + 'cnot': 'CNot', 'cx': 'CNot', 'cz': 'CZ', 'cy': 'CY', + 'swap': 'Swap', 'iswap': 'ISwap', + 'ccnot': 'CCNot', 'ccx': 'CCNot', 'toffoli': 'CCNot', + 'cswap': 'CSwap', 'fredkin': 'CSwap', + } + _PARAMETRIC = {'Rx', 'Ry', 'Rz', 'PhaseShift', 'CPhaseShift'} def add_gate(self, circuit: BraketCircuit, gate: str, qubits: int | list[int], params: list[float] | None = None) -> BraketCircuit: """Add a quantum gate to the circuit.""" if isinstance(qubits, int): qubits = [qubits] - - params = params or [] - - # Map gate names to Braket gates - gate_mapping = { - 'i': I, 'x': X, 'y': Y, 'z': Z, 'h': H, - 's': S, 'sdg': Si, 't': T, 'tdg': Ti, - 'rx': RX, 'ry': RY, 'rz': RZ, - 'cnot': CNot, 'cx': CNot, 'cz': CZ, 'cy': CY, - 'swap': Swap, 'iswap': ISwap, - 'ccnot': CCNot, 'toffoli': CCNot, - 'cswap': CSwap, 'fredkin': CSwap - } - - gate_lower = gate.lower() - if gate_lower not in gate_mapping: + name = self._GATES.get(gate.lower()) + if name is None: raise ValueError(f"Gate '{gate}' not supported in Braket backend") - - gate_class = gate_mapping[gate_lower] - - try: - if len(params) == 0: - # Parameter-less gates - if len(qubits) == 1: - circuit.add_instruction(Instruction(gate_class(), qubits[0])) - elif len(qubits) == 2: - circuit.add_instruction(Instruction(gate_class(), qubits)) - elif len(qubits) == 3: - circuit.add_instruction(Instruction(gate_class(), qubits)) - else: - raise ValueError(f"Too many qubits for gate {gate}") - - else: - # Parameterized gates - if gate_lower in ['rx', 'ry', 'rz']: - circuit.add_instruction(Instruction(gate_class(params[0]), qubits[0])) - elif gate_lower == 'phaseshift': - circuit.add_instruction(Instruction(PhaseShift(params[0]), qubits[0])) - elif gate_lower == 'cphaseshift': - circuit.add_instruction(Instruction(CPhaseShift(params[0]), qubits)) - else: - raise ValueError(f"Parameters not supported for gate {gate}") - - except Exception as e: - logger.error(f"Failed to add gate {gate} to circuit: {e}") - raise - + gate_class = getattr(bg, name) + if name in self._PARAMETRIC: + if not params: + raise ValueError(f"Gate '{gate}' needs a rotation angle") + op = gate_class(float(params[0])) + else: + op = gate_class() + target = qubits[0] if len(qubits) == 1 else list(qubits) + circuit.add_instruction(Instruction(op, target)) return circuit - def add_measurement(self, circuit: BraketCircuit, qubits: int | list[int]) -> BraketCircuit: - """Add measurement instructions to specified qubits.""" - if isinstance(qubits, int): + def add_measurement(self, circuit: BraketCircuit, qubits: int | list[int] | None = None) -> BraketCircuit: + """Record which qubits to measure (all qubits when ``qubits`` is None).""" + if qubits is None: + qubits = list(range(circuit.qubit_count)) + elif isinstance(qubits, int): qubits = [qubits] - - # Braket doesn't use explicit measurement instructions in circuits - # Measurements are handled during task submission - # Store measurement info for later use if not hasattr(circuit, '_measurement_qubits'): circuit._measurement_qubits = set() circuit._measurement_qubits.update(qubits) - return circuit def execute_circuit(self, circuit: BraketCircuit, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" + """Sample the circuit. Counts are big-endian (qubit 0 is the leftmost bit).""" shots = shots or self.shots + measure_qubits = sorted(getattr(circuit, '_measurement_qubits', range(circuit.qubit_count))) - try: - # Get measurement qubits (all qubits if not specified) - if hasattr(circuit, '_measurement_qubits'): - measure_qubits = sorted(circuit._measurement_qubits) - else: - # Measure all qubits that have gates applied - measure_qubits = list(range(circuit.qubit_count)) - - # Add measurement to circuit copy - measured_circuit = circuit.copy() - for qubit in measure_qubits: - measured_circuit.add_instruction(Instruction(Measure(), qubit)) - - # Execute task - if self.s3_folder and hasattr(self._device, 'run'): - # AWS device with S3 storage - task = self._device.run(measured_circuit, shots=shots, s3_destination_folder=self.s3_folder) - result = task.result() - else: - # Local simulator - task = self._device.run(measured_circuit, shots=shots) - result = task.result() - - # Process measurement results - measurement_counts = result.measurement_counts - - # Convert to standard format - counts = {} - for bitstring, count in measurement_counts.items(): - counts[bitstring] = count - - return { - 'counts': counts, - 'shots': shots, - 'success': True, - 'measurement_qubits': measure_qubits, - 'task_arn': getattr(task, 'id', 'local'), - 'device': self.device_name, - } + measured_circuit = circuit.copy() + if measure_qubits != list(range(circuit.qubit_count)): + measured_circuit.measure(measure_qubits) - except Exception as e: - logger.error(f"Circuit execution failed: {e}") - return { - 'counts': {}, - 'shots': shots, - 'success': False, - 'error': str(e), - 'device': self.device_name, - } + if self.s3_folder and not self.device_name.startswith('local:'): + task = self._device.run(measured_circuit, shots=shots, s3_destination_folder=self.s3_folder) + else: + task = self._device.run(measured_circuit, shots=shots) + result = task.result() + counts = {str(k): int(v) for k, v in result.measurement_counts.items()} + + return { + 'counts': counts, + 'shots': shots, + 'success': True, + 'measurement_qubits': measure_qubits, + 'task_arn': getattr(task, 'id', 'local'), + 'device': self.device_name, + } # ======================================================================== # Algorithm-Specific Operations @@ -294,55 +250,6 @@ def create_parameterized_circuit(self, n_qubits: int, n_params: int) -> tuple[Br return circuit, param_names - def bind_parameters(self, circuit: BraketCircuit, param_values: dict[str, float]) -> BraketCircuit: - """Bind parameter values to parameterized circuit.""" - # Braket handles parameterization differently - would need custom implementation - # For now, create a new circuit with bound parameters - bound_circuit = circuit.copy() - - # This is a simplified implementation - # In practice, you'd need to track parameterized gates and substitute values - logger.warning("Parameter binding in Braket backend is simplified") - - return bound_circuit - - def expectation_value(self, circuit: BraketCircuit, observable: str | np.ndarray, - shots: int | None = None) -> float: - """Calculate expectation value of observable.""" - shots = shots or self.shots - - try: - # Simple implementation for Pauli observables - if isinstance(observable, str): - if observable.upper() == 'Z': - # Measure in Z basis - result = self.execute_circuit(circuit, shots) - counts = result['counts'] - - # Calculate expectation - expectation = 0.0 - total_counts = sum(counts.values()) - - for bitstring, count in counts.items(): - # Z expectation: +1 for |0>, -1 for |1> - prob = count / total_counts - if bitstring == '0' or (len(bitstring) > 0 and bitstring[0] == '0'): - expectation += prob - else: - expectation -= prob - - return expectation - else: - logger.warning(f"Observable {observable} not fully implemented") - return 0.0 - else: - logger.warning("Matrix observables not implemented") - return 0.0 - - except Exception as e: - logger.error(f"Expectation value calculation failed: {e}") - return 0.0 - # ======================================================================== # Backend Information # ======================================================================== @@ -373,11 +280,12 @@ def get_backend_info(self) -> dict[str, Any]: def get_version_info(self) -> dict[str, str]: """Get version information for Braket dependencies.""" - import braket - return { - 'braket_sdk': getattr(braket, '__version__', 'unknown'), - 'backend_version': '1.0.0', - } + from importlib.metadata import PackageNotFoundError, version + try: + sdk = version('amazon-braket-sdk') + except PackageNotFoundError: + sdk = 'unknown' + return {'braket_sdk': sdk, 'backend_version': '1.0.0'} def is_available(self) -> bool: """Check if the backend is available and properly configured.""" @@ -398,23 +306,11 @@ def _get_n_qubits(self, circuit: BraketCircuit) -> int: return circuit.qubit_count def get_statevector(self, circuit: BraketCircuit) -> np.ndarray: - """Get statevector from Braket circuit.""" - try: - # Use local simulator for statevector - from braket.devices import LocalSimulator - sv_device = LocalSimulator("braket_sv") - - # Execute without measurements for statevector - task = sv_device.run(circuit, shots=0) - result = task.result() - - if hasattr(result, 'get_value_by_result_type'): - from braket.circuits.result_types import StateVector - return result.get_value_by_result_type(StateVector()) - else: - logger.warning("Statevector not available") - return np.zeros(2**circuit.qubit_count, dtype=complex) - - except Exception as e: - logger.error(f"Failed to get statevector: {e}") - return np.zeros(2**circuit.qubit_count, dtype=complex) + """Exact statevector (big-endian) from Braket's local state-vector simulator.""" + sv_circuit = BraketCircuit() + for instr in circuit.instructions: + if not isinstance(instr.operator, Measure): + sv_circuit.add_instruction(instr) + sv_circuit.state_vector() + result = LocalSimulator('braket_sv').run(sv_circuit, shots=0).result() + return np.asarray(result.values[0], dtype=complex) diff --git a/src/superquantx/backends/cirq_backend.py b/src/superquantx/backends/cirq_backend.py index 4a9c6e2..0fdfd6d 100644 --- a/src/superquantx/backends/cirq_backend.py +++ b/src/superquantx/backends/cirq_backend.py @@ -1,23 +1,19 @@ """Cirq backend implementation for SuperQuantX. -This module provides integration with Google's Cirq for quantum computing -operations and access to Google Quantum AI hardware. +Local execution uses ``cirq.Simulator``. Google Quantum AI hardware via +``cirq_google`` is wired up but untested (it requires processor access). """ import logging -from typing import TYPE_CHECKING, Any +from typing import Any import numpy as np from .base_backend import BaseBackend -if TYPE_CHECKING: - import cirq - logger = logging.getLogger(__name__) -# Try to import Cirq try: import cirq CIRQ_AVAILABLE = True @@ -25,30 +21,29 @@ CIRQ_AVAILABLE = False cirq = None + class CirqBackend(BaseBackend): - """Cirq backend for quantum computing operations. + """Cirq backend. - This backend provides access to Cirq simulators and Google Quantum AI - hardware for quantum algorithm execution. + Circuits are ``(cirq.Circuit, [LineQubit, ...])`` tuples. Counts and + statevectors are big-endian (qubit 0 is the leftmost bit). Args: - device: Cirq device name ('simulator', 'sycamore', etc.) - processor_id: Google Quantum AI processor ID - shots: Number of measurement shots - **kwargs: Additional backend parameters + device: ``'simulator'`` (default). + processor_id: Google Quantum AI processor id (hardware, untested). + shots: Number of measurement shots. """ def __init__(self, device: str = 'simulator', processor_id: str | None = None, shots: int = 1024, **kwargs): if not CIRQ_AVAILABLE: - raise ImportError("Cirq is required for CirqBackend. Install with: pip install cirq") - - super().__init__(device=device, shots=shots, **kwargs) - + raise ImportError("Cirq is required for CirqBackend. Install with: pip install 'superquantx[cirq]'") + # These must exist before BaseBackend.__init__ calls _initialize_backend(). self.processor_id = processor_id self.simulator = None self.quantum_engine = None + super().__init__(device=device, shots=shots, **kwargs) self.capabilities = { 'supports_gradient': False, 'supports_parameter_shift': True, @@ -58,409 +53,87 @@ def __init__(self, device: str = 'simulator', processor_id: str | None = None, } def _initialize_backend(self) -> None: - """Initialize Cirq backend.""" - try: - if self.device == 'simulator': - self.simulator = cirq.Simulator() - logger.info("Initialized Cirq Simulator") - - elif self.processor_id: - try: - import cirq_google - # Initialize Google Quantum Engine - self.quantum_engine = cirq_google.get_engine() - logger.info(f"Initialized Google Quantum Engine with processor {self.processor_id}") - except ImportError: - logger.error("cirq-google required for hardware access") - self.simulator = cirq.Simulator() - logger.warning("Falling back to simulator") - - else: - self.simulator = cirq.Simulator() - logger.info("Initialized default Cirq Simulator") - - except Exception as e: - logger.error(f"Failed to initialize Cirq backend: {e}") + if self.processor_id: + import cirq_google # raises ImportError with a clear message if missing + self.quantum_engine = cirq_google.get_engine() + else: self.simulator = cirq.Simulator() - logger.warning("Falling back to default simulator") - def create_circuit(self, n_qubits: int) -> Any: - """Create a quantum circuit with n qubits.""" - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() - return circuit, qubits # Return both circuit and qubits for convenience + @staticmethod + def _unpack(circuit_info: Any) -> tuple[Any, list]: + if isinstance(circuit_info, tuple): + return circuit_info + return circuit_info, sorted(circuit_info.all_qubits()) + + def create_circuit(self, n_qubits: int) -> tuple[Any, list]: + return cirq.Circuit(), [cirq.LineQubit(i) for i in range(n_qubits)] def add_gate(self, circuit_info: tuple[Any, list], gate: str, qubits: int | list[int], params: list[float] | None = None) -> tuple[Any, list]: - """Add a quantum gate to the circuit.""" circuit, qubit_list = circuit_info - if isinstance(qubits, int): qubits = [qubits] - - params = params or [] - - try: - if gate.upper() == 'H' or gate.upper() == 'HADAMARD': - circuit.append(cirq.H(qubit_list[qubits[0]])) - elif gate.upper() == 'X' or gate.upper() == 'PAULI_X': - circuit.append(cirq.X(qubit_list[qubits[0]])) - elif gate.upper() == 'Y' or gate.upper() == 'PAULI_Y': - circuit.append(cirq.Y(qubit_list[qubits[0]])) - elif gate.upper() == 'Z' or gate.upper() == 'PAULI_Z': - circuit.append(cirq.Z(qubit_list[qubits[0]])) - elif gate.upper() == 'RX': - circuit.append(cirq.rx(params[0] if params else 0)(qubit_list[qubits[0]])) - elif gate.upper() == 'RY': - circuit.append(cirq.ry(params[0] if params else 0)(qubit_list[qubits[0]])) - elif gate.upper() == 'RZ': - circuit.append(cirq.rz(params[0] if params else 0)(qubit_list[qubits[0]])) - elif gate.upper() == 'CNOT' or gate.upper() == 'CX': - circuit.append(cirq.CNOT(qubit_list[qubits[0]], qubit_list[qubits[1]])) - elif gate.upper() == 'CZ': - circuit.append(cirq.CZ(qubit_list[qubits[0]], qubit_list[qubits[1]])) - elif gate.upper() == 'SWAP': - circuit.append(cirq.SWAP(qubit_list[qubits[0]], qubit_list[qubits[1]])) - elif gate.upper() == 'CCX' or gate.upper() == 'TOFFOLI': - circuit.append(cirq.CCX(qubit_list[qubits[0]], qubit_list[qubits[1]], qubit_list[qubits[2]])) - else: - logger.warning(f"Unknown gate: {gate}") - - except Exception as e: - logger.error(f"Failed to add gate {gate}: {e}") - + q = [qubit_list[i] for i in qubits] + params = list(params) if params is not None else [] + name = gate.upper() + fixed = {'H': cirq.H, 'HADAMARD': cirq.H, 'X': cirq.X, 'PAULI_X': cirq.X, + 'Y': cirq.Y, 'PAULI_Y': cirq.Y, 'Z': cirq.Z, 'PAULI_Z': cirq.Z, + 'S': cirq.S, 'T': cirq.T, 'I': cirq.I, 'CNOT': cirq.CNOT, 'CX': cirq.CNOT, + 'CZ': cirq.CZ, 'SWAP': cirq.SWAP, 'CCX': cirq.CCX, 'TOFFOLI': cirq.CCX} + rot = {'RX': cirq.rx, 'RY': cirq.ry, 'RZ': cirq.rz} + if name in fixed: + circuit.append(fixed[name](*q)) + elif name in rot: + circuit.append(rot[name](float(params[0]))(*q)) + elif name in ('P', 'PHASE'): + circuit.append(cirq.ZPowGate(exponent=float(params[0]) / np.pi)(*q)) + elif name in ('CRX', 'CRY', 'CRZ'): + circuit.append(rot['R' + name[2]](float(params[0])).controlled()(*q)) + else: + raise ValueError(f"Unsupported gate for CirqBackend: {gate}") return circuit, qubit_list def add_measurement(self, circuit_info: tuple[Any, list], - qubits: list[int] | None = None) -> tuple[Any, list]: - """Add measurement operations to the circuit.""" + qubits: list[int] | None = None) -> tuple[Any, list]: circuit, qubit_list = circuit_info - if qubits is None: qubits = list(range(len(qubit_list))) - - measurement_qubits = [qubit_list[i] for i in qubits] - circuit.append(cirq.measure(*measurement_qubits, key='result')) - + circuit.append(cirq.measure(*[qubit_list[i] for i in qubits], key='result')) return circuit, qubit_list - def execute_circuit(self, circuit_info: Any | tuple, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" - if isinstance(circuit_info, tuple): - circuit, qubit_list = circuit_info - else: - circuit = circuit_info - qubit_list = sorted(circuit.all_qubits()) - + def execute_circuit(self, circuit_info: Any, shots: int | None = None) -> dict[str, Any]: + """Sample the circuit; unmeasured circuits get all qubits measured on a copy.""" + circuit, qubit_list = self._unpack(circuit_info) shots = shots or self.shots - - try: - if self.simulator: - # Run on simulator - result = self.simulator.run(circuit, repetitions=shots) - - # Convert to counts format - if 'result' in result.measurements: - measurements = result.measurements['result'] - counts = {} - for measurement in measurements: - bitstring = ''.join(str(bit) for bit in measurement) - counts[bitstring] = counts.get(bitstring, 0) + 1 - else: - counts = {'0' * len(qubit_list): shots} - - return { - 'counts': counts, - 'shots': shots, - 'backend': 'cirq_simulator', - } - - elif self.quantum_engine and self.processor_id: - # Run on Google Quantum AI hardware - processor = self.quantum_engine.get_processor(self.processor_id) - job = processor.run(circuit, repetitions=shots) - result = job.results()[0] - - # Convert to counts format - measurements = result.measurements['result'] - counts = {} - for measurement in measurements: - bitstring = ''.join(str(bit) for bit in measurement) - counts[bitstring] = counts.get(bitstring, 0) + 1 - - return { - 'counts': counts, - 'shots': shots, - 'backend': f'google_quantum_{self.processor_id}', - 'job_id': job.id(), - } - - else: - raise ValueError("No execution backend available") - - except Exception as e: - logger.error(f"Circuit execution failed: {e}") - raise - - def get_statevector(self, circuit_info: Any | tuple) -> np.ndarray: - """Get the statevector from a quantum circuit.""" - if isinstance(circuit_info, tuple): - circuit, qubit_list = circuit_info - else: - circuit = circuit_info - qubit_list = sorted(circuit.all_qubits()) - - try: - # Remove measurements for statevector simulation - circuit_copy = circuit.copy() - circuit_copy = cirq.Circuit([op for op in circuit_copy.all_operations() - if not isinstance(op.gate, cirq.MeasurementGate)]) - - # Simulate - result = self.simulator.simulate(circuit_copy) - statevector = result.final_state_vector - - return np.array(statevector) - - except Exception as e: - logger.error(f"Statevector computation failed: {e}") - n_qubits = len(qubit_list) - return np.array([1.0] + [0.0] * (2**n_qubits - 1)) - - def _get_n_qubits(self, circuit_info: Any | tuple) -> int: - """Get number of qubits in circuit.""" - if isinstance(circuit_info, tuple): - circuit, qubit_list = circuit_info - return len(qubit_list) - else: - return len(circuit_info.all_qubits()) - - # ======================================================================== - # Enhanced Cirq-specific implementations - # ======================================================================== - - def create_feature_map(self, n_features: int, feature_map: str, reps: int = 1) -> tuple[Any, list]: - """Create quantum feature map for data encoding.""" - [cirq.LineQubit(i) for i in range(n_features)] - cirq.Circuit() - - if feature_map == 'ZZFeatureMap': - circuit_info = self._create_zz_feature_map(n_features, reps) - elif feature_map == 'PauliFeatureMap': - circuit_info = self._create_pauli_feature_map(n_features, reps) - elif feature_map == 'AmplitudeMap': - circuit_info = self._create_amplitude_map(n_features) - else: - logger.warning(f"Unknown feature map '{feature_map}', using angle encoding") - circuit_info = self._create_angle_encoding_map(n_features) - - return circuit_info - - def _create_zz_feature_map(self, n_features: int, reps: int) -> tuple[Any, list]: - """Create ZZ feature map circuit.""" - qubits = [cirq.LineQubit(i) for i in range(n_features)] - circuit = cirq.Circuit() - - for r in range(reps): - # Hadamard layer - circuit.append([cirq.H(q) for q in qubits]) - - # Parameterized rotations (placeholders) - for i, q in enumerate(qubits): - circuit.append(cirq.rz(cirq.Symbol(f'x_{i}'))(q)) - - # ZZ interactions - for i in range(n_features - 1): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - circuit.append(cirq.rz(cirq.Symbol(f'x_{i}_x_{i+1}'))(qubits[i + 1])) - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - - return circuit, qubits - - def _create_pauli_feature_map(self, n_features: int, reps: int) -> tuple[Any, list]: - """Create Pauli feature map circuit.""" - qubits = [cirq.LineQubit(i) for i in range(n_features)] - circuit = cirq.Circuit() - - for r in range(reps): - # Pauli rotations - for i, q in enumerate(qubits): - circuit.append(cirq.rx(cirq.Symbol(f'x_{i}_rx_{r}'))(q)) - circuit.append(cirq.ry(cirq.Symbol(f'x_{i}_ry_{r}'))(q)) - circuit.append(cirq.rz(cirq.Symbol(f'x_{i}_rz_{r}'))(q)) - - # Entangling layer - for i in range(n_features - 1): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - - return circuit, qubits - - def _create_amplitude_map(self, n_features: int) -> tuple[Any, list]: - """Create amplitude encoding map.""" - n_qubits = int(np.ceil(np.log2(n_features))) - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() - - # Amplitude encoding would require state preparation - # This is a simplified placeholder - logger.warning("Amplitude encoding not fully implemented") - - return circuit, qubits - - def _create_angle_encoding_map(self, n_features: int) -> tuple[Any, list]: - """Create angle encoding map.""" - qubits = [cirq.LineQubit(i) for i in range(n_features)] - circuit = cirq.Circuit() - - for i, q in enumerate(qubits): - circuit.append(cirq.ry(cirq.Symbol(f'x_{i}'))(q)) - - return circuit, qubits - - def create_ansatz(self, ansatz_type: str, n_qubits: int, params: np.ndarray, - include_custom_gates: bool = False) -> tuple[Any, list]: - """Create parameterized ansatz circuit.""" - if ansatz_type == 'RealAmplitudes': - return self._create_real_amplitudes_ansatz(n_qubits, params) - elif ansatz_type == 'EfficientSU2': - return self._create_efficient_su2_ansatz(n_qubits, params) - elif ansatz_type == 'TwoLocal': - return self._create_two_local_ansatz(n_qubits, params) - elif ansatz_type == 'UCCSD': - return self._create_uccsd_ansatz(n_qubits, params) + if not circuit.has_measurements(): + circuit = circuit + cirq.Circuit(cirq.measure(*qubit_list, key='result')) + + if self.quantum_engine is not None: + processor = self.quantum_engine.get_processor(self.processor_id) + job = processor.run(circuit, repetitions=shots) + result = job.results()[0] + backend_name = f'google_quantum_{self.processor_id}' else: - logger.warning(f"Unknown ansatz '{ansatz_type}', using RealAmplitudes") - return self._create_real_amplitudes_ansatz(n_qubits, params) - - def _create_real_amplitudes_ansatz(self, n_qubits: int, params: np.ndarray) -> tuple[Any, list]: - """Create RealAmplitudes ansatz.""" - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() + result = self.simulator.run(circuit, repetitions=shots) + backend_name = 'cirq_simulator' - n_layers = len(params) // (n_qubits * 2) - param_idx = 0 + keys = list(result.measurements) + bits = np.concatenate([result.measurements[k] for k in keys], axis=1) + values, freq = np.unique(bits, axis=0, return_counts=True) + counts = {''.join(str(int(b)) for b in row): int(c) for row, c in zip(values, freq, strict=True)} + return {'counts': counts, 'shots': shots, 'backend': backend_name} - for layer in range(n_layers): - # RY rotations - for i, q in enumerate(qubits): - if param_idx < len(params): - circuit.append(cirq.ry(params[param_idx])(q)) - param_idx += 1 + def get_statevector(self, circuit_info: Any) -> np.ndarray: + circuit, qubit_list = self._unpack(circuit_info) + clean = cirq.drop_terminal_measurements(circuit) if circuit.has_measurements() else circuit + simulator = self.simulator or cirq.Simulator() + result = simulator.simulate(clean, qubit_order=qubit_list) + return np.asarray(result.final_state_vector, dtype=complex) - # Entangling layer - for i in range(n_qubits - 1): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - - # RZ rotations - for i, q in enumerate(qubits): - if param_idx < len(params): - circuit.append(cirq.rz(params[param_idx])(q)) - param_idx += 1 - - return circuit, qubits - - def _create_efficient_su2_ansatz(self, n_qubits: int, params: np.ndarray) -> tuple[Any, list]: - """Create EfficientSU2 ansatz.""" - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() - - n_layers = len(params) // (n_qubits * 3) - param_idx = 0 - - for layer in range(n_layers): - # SU(2) rotations - for i, q in enumerate(qubits): - if param_idx + 2 < len(params): - circuit.append(cirq.ry(params[param_idx])(q)) - circuit.append(cirq.rz(params[param_idx + 1])(q)) - circuit.append(cirq.ry(params[param_idx + 2])(q)) - param_idx += 3 - - # Entangling layer - for i in range(n_qubits - 1): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - - return circuit, qubits - - def _create_two_local_ansatz(self, n_qubits: int, params: np.ndarray) -> tuple[Any, list]: - """Create TwoLocal ansatz.""" - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() - - n_layers = len(params) // (n_qubits * 2) - param_idx = 0 - - for layer in range(n_layers): - # Local rotations - for i, q in enumerate(qubits): - if param_idx + 1 < len(params): - circuit.append(cirq.ry(params[param_idx])(q)) - circuit.append(cirq.rz(params[param_idx + 1])(q)) - param_idx += 2 - - # Two-qubit gates - for i in range(0, n_qubits - 1, 2): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - for i in range(1, n_qubits - 1, 2): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - - return circuit, qubits - - def _create_uccsd_ansatz(self, n_qubits: int, params: np.ndarray) -> tuple[Any, list]: - """Create UCCSD ansatz (simplified).""" - qubits = [cirq.LineQubit(i) for i in range(n_qubits)] - circuit = cirq.Circuit() - - param_idx = 0 - - # Single excitations - for i in range(0, n_qubits, 2): - for j in range(1, n_qubits, 2): - if param_idx < len(params) and i != j: - circuit.append(cirq.CNOT(qubits[i], qubits[j])) - circuit.append(cirq.ry(params[param_idx])(qubits[j])) - circuit.append(cirq.CNOT(qubits[i], qubits[j])) - param_idx += 1 - - # Double excitations (simplified) - for i in range(0, n_qubits - 3, 2): - if param_idx < len(params): - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - circuit.append(cirq.CNOT(qubits[i + 2], qubits[i + 3])) - circuit.append(cirq.ry(params[param_idx])(qubits[i + 1])) - circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) - circuit.append(cirq.CNOT(qubits[i + 2], qubits[i + 3])) - param_idx += 1 - - return circuit, qubits - - def compute_expectation(self, circuit_info: Any | tuple, hamiltonian: Any, - shots: int | None = None) -> float: - """Compute expectation value of Hamiltonian.""" - try: - if isinstance(hamiltonian, np.ndarray): - # Compute expectation using statevector - statevector = self.get_statevector(circuit_info) - expectation = np.real(np.conj(statevector) @ hamiltonian @ statevector) - return float(expectation) - else: - logger.warning("Hamiltonian expectation not fully implemented") - return 0.0 - - except Exception as e: - logger.error(f"Expectation computation failed: {e}") - return 0.0 + def _get_n_qubits(self, circuit_info: Any) -> int: + return len(self._unpack(circuit_info)[1]) def get_version_info(self) -> dict[str, Any]: - """Get Cirq version information.""" info = super().get_version_info() - - try: - info.update({ - 'cirq_version': cirq.__version__, - 'processor_id': self.processor_id, - }) - except Exception as e: - info['version_error'] = str(e) - + info['cirq_version'] = cirq.__version__ return info diff --git a/src/superquantx/backends/ocean_backend.py b/src/superquantx/backends/ocean_backend.py index 76e0699..775d86d 100644 --- a/src/superquantx/backends/ocean_backend.py +++ b/src/superquantx/backends/ocean_backend.py @@ -83,6 +83,7 @@ def __init__( self.num_reads = shots self._sampler = None self._is_quantum_annealing = True # This backend is for annealing, not gates + self.gate_model = False super().__init__(device=device, shots=shots, **kwargs) @@ -168,7 +169,7 @@ def solve_qubo(self, Q: dict[tuple[int, int], float], **kwargs) -> dict[str, Any """ try: - num_reads = kwargs.get('num_reads', self.num_reads) + num_reads = kwargs.pop('num_reads', self.num_reads) # Create BQM from QUBO bqm = dimod.BinaryQuadraticModel.from_qubo(Q) @@ -217,7 +218,7 @@ def solve_ising(self, h: dict[int, float], J: dict[tuple[int, int], float], **kw """ try: - num_reads = kwargs.get('num_reads', self.num_reads) + num_reads = kwargs.pop('num_reads', self.num_reads) # Create BQM from Ising model bqm = dimod.BinaryQuadraticModel.from_ising(h, J) @@ -319,41 +320,29 @@ def _convert_sampleset(self, sampleset, problem_type: str) -> dict[str, Any]: # Gate Model Compatibility (Limited Support) # ======================================================================== - def create_circuit(self, n_qubits: int) -> dict[str, Any]: - """Limited circuit support for compatibility. + _NOT_GATE_MODEL = ( + "OceanBackend targets D-Wave quantum annealers (and the classical simulated " + "annealer), not gate-model circuits. Use solve_qubo(), solve_ising() or " + "solve_max_cut() instead, or pick a gate-model backend such as 'simulator', " + "'qiskit', 'pennylane', 'cirq', 'braket' or 'tket'." + ) - Note: D-Wave is not a gate-model quantum computer. - This returns a placeholder for optimization problems. - """ - logger.warning("D-Wave Ocean backend does not support gate-model circuits") - return { - 'type': 'optimization_placeholder', - 'n_variables': n_qubits, - 'backend': 'ocean', - 'problem': None - } + def create_circuit(self, n_qubits: int) -> dict[str, Any]: + """Not supported: annealers do not run gate-model circuits.""" + raise NotImplementedError(self._NOT_GATE_MODEL) def add_gate(self, circuit: dict, gate: str, qubits: int | list[int], params: list[float] | None = None) -> dict: - """Limited gate support - not applicable for annealing.""" - logger.warning("Gate operations not supported on D-Wave annealing backend") - return circuit + """Not supported: annealers do not run gate-model circuits.""" + raise NotImplementedError(self._NOT_GATE_MODEL) - def add_measurement(self, circuit: dict, qubits: int | list[int]) -> dict: - """Limited measurement support - not applicable for annealing.""" - logger.warning("Measurements not applicable for D-Wave annealing backend") - return circuit + def add_measurement(self, circuit: dict, qubits: int | list[int] | None = None) -> dict: + """Not supported: annealers do not run gate-model circuits.""" + raise NotImplementedError(self._NOT_GATE_MODEL) def execute_circuit(self, circuit: dict, shots: int | None = None) -> dict[str, Any]: - """Limited circuit execution - redirects to optimization solving.""" - logger.warning("Circuit execution not supported - use solve_qubo() or solve_ising() instead") - return { - 'counts': {}, - 'shots': shots or self.shots, - 'success': False, - 'error': 'Use optimization problem methods instead of circuit execution', - 'backend': 'ocean' - } + """Not supported: annealers do not run gate-model circuits.""" + raise NotImplementedError(self._NOT_GATE_MODEL) # ======================================================================== # Backend Information @@ -431,9 +420,8 @@ def _get_n_qubits(self, circuit: dict) -> int: return 0 def get_statevector(self, circuit: dict) -> np.ndarray: - """Get statevector (not applicable for annealing backend).""" - logger.warning("Statevector not applicable for quantum annealing backend") - return np.array([1.0 + 0j]) # Dummy statevector + """Not supported: annealers have no gate-model statevector.""" + raise NotImplementedError(self._NOT_GATE_MODEL) # ======================================================================== # Convenience Methods for Common Optimization Problems @@ -452,40 +440,29 @@ def solve_max_cut(self, graph: Any | list[tuple], **kwargs) -> dict[str, Any]: else: G = graph - # Convert to QUBO formulation + # cut(x) = sum_ij w_ij (x_i + x_j - 2 x_i x_j); samplers minimise energy, + # so the QUBO is -cut(x) and the lowest energy is the maximum cut. Q = {} - for i, j in G.edges(): - Q[(i, i)] = Q.get((i, i), 0) + 1 - Q[(j, j)] = Q.get((j, j), 0) + 1 - Q[(i, j)] = Q.get((i, j), 0) - 2 - - return self.solve_qubo(Q, **kwargs) + for i, j, data in G.edges(data=True): + w = data.get('weight', 1.0) + Q[(i, i)] = Q.get((i, i), 0) - w + Q[(j, j)] = Q.get((j, j), 0) - w + Q[(i, j)] = Q.get((i, j), 0) + 2 * w + + result = self.solve_qubo(Q, **kwargs) + if result.get('success') and result['energies']: + best = int(np.argmin(result['energies'])) + result['best_sample'] = result['samples'][best] + result['best_cut_value'] = -float(result['energies'][best]) + return result except Exception as e: logger.error(f"Max Cut solving failed: {e}") return {'success': False, 'error': str(e)} def solve_tsp(self, distance_matrix: np.ndarray, **kwargs) -> dict[str, Any]: - """Solve Traveling Salesman Problem (simplified formulation).""" - try: - n_cities = len(distance_matrix) - - # This is a simplified TSP formulation - # Full TSP requires more complex constraints - logger.warning("TSP formulation is simplified - may not give valid tours") - - Q = {} - # Add distance costs - for i in range(n_cities): - for j in range(i+1, n_cities): - for t in range(n_cities): - # Variable x_it means city i is visited at time t - var_i = i * n_cities + t - var_j = j * n_cities + ((t + 1) % n_cities) - Q[(var_i, var_j)] = distance_matrix[i, j] - - return self.solve_qubo(Q, **kwargs) - - except Exception as e: - logger.error(f"TSP solving failed: {e}") - return {'success': False, 'error': str(e)} + """Not implemented: a correct TSP QUBO needs one-hot constraints (planned).""" + raise NotImplementedError( + "TSP is not implemented yet; formulate it as a QUBO with one-hot " + "penalties and call solve_qubo()." + ) diff --git a/src/superquantx/backends/pennylane_backend.py b/src/superquantx/backends/pennylane_backend.py index 3ce4df6..620cad0 100644 --- a/src/superquantx/backends/pennylane_backend.py +++ b/src/superquantx/backends/pennylane_backend.py @@ -1,7 +1,8 @@ """PennyLane backend implementation for SuperQuantX. -This module provides integration with PennyLane for quantum machine learning -and variational quantum algorithms. +Circuits are recorded as a list of PennyLane operations and executed by +building a QNode on demand, so the unified ``create_circuit`` / ``add_gate`` / +``execute_circuit`` API works the same way as on the other backends. """ import logging @@ -15,405 +16,149 @@ logger = logging.getLogger(__name__) -# Try to import PennyLane try: import pennylane as qml - from pennylane import numpy as pnp PENNYLANE_AVAILABLE = True except ImportError: PENNYLANE_AVAILABLE = False qml = None - pnp = None -class PennyLaneBackend(BaseBackend): - """PennyLane backend for quantum computing operations. - This backend provides access to PennyLane's quantum devices and - automatic differentiation capabilities for variational quantum - algorithms. +class PennyLaneCircuit: + """A recorded PennyLane circuit: ``n_qubits`` wires plus a list of operations.""" + + def __init__(self, n_qubits: int): + self.n_qubits = n_qubits + self.ops: list[tuple[str, tuple[float, ...], tuple[int, ...]]] = [] + self.measured: list[int] | None = None + + def copy(self) -> 'PennyLaneCircuit': + new = PennyLaneCircuit(self.n_qubits) + new.ops = list(self.ops) + new.measured = None if self.measured is None else list(self.measured) + return new + + def apply(self) -> None: + """Queue the recorded operations inside a QNode.""" + for name, params, wires in self.ops: + getattr(qml, name)(*params, wires=list(wires)) + + def __call__(self) -> None: # allows use as a plain quantum function + self.apply() + + def __repr__(self) -> str: + return f"PennyLaneCircuit(n_qubits={self.n_qubits}, ops={len(self.ops)})" + + +_GATES = { + 'H': 'Hadamard', 'HADAMARD': 'Hadamard', 'X': 'PauliX', 'PAULI_X': 'PauliX', + 'Y': 'PauliY', 'PAULI_Y': 'PauliY', 'Z': 'PauliZ', 'PAULI_Z': 'PauliZ', + 'S': 'S', 'T': 'T', 'I': 'Identity', 'RX': 'RX', 'RY': 'RY', 'RZ': 'RZ', + 'P': 'PhaseShift', 'PHASE': 'PhaseShift', 'CNOT': 'CNOT', 'CX': 'CNOT', + 'CZ': 'CZ', 'SWAP': 'SWAP', 'CRX': 'CRX', 'CRY': 'CRY', 'CRZ': 'CRZ', + 'CCX': 'Toffoli', 'TOFFOLI': 'Toffoli', +} +_PARAMETRIC = {'RX', 'RY', 'RZ', 'PhaseShift', 'CRX', 'CRY', 'CRZ'} + + +class PennyLaneBackend(BaseBackend): + """PennyLane backend. Args: - device: PennyLane device name ('default.qubit', 'qiskit.aer', etc.) - wires: Number of qubits/wires - shots: Number of measurement shots - **kwargs: Additional device parameters + device: PennyLane device name (``'default.qubit'``, ``'lightning.qubit'``, ...). + wires: Maximum number of wires a circuit may use. + shots: Default number of shots for sampled execution. + **kwargs: Extra keyword arguments passed to ``qml.device``. """ - def __init__(self, device: str = 'default.qubit', wires: int = 4, shots: int = 1024, **kwargs): + def __init__(self, device: str = 'default.qubit', wires: int = 16, shots: int = 1024, **kwargs): if not PENNYLANE_AVAILABLE: - raise ImportError("PennyLane is required for PennyLaneBackend. Install with: pip install pennylane") - + raise ImportError( + "PennyLane is required for PennyLaneBackend. Install with: pip install 'superquantx[pennylane]'" + ) self.wires = wires + self._devices: dict[int, Any] = {} super().__init__(device=device, shots=shots, **kwargs) - self.dev = None self.capabilities = { 'supports_gradient': True, 'supports_parameter_shift': True, 'supports_finite_diff': True, - 'supports_backprop': device in ['default.qubit'], - 'supports_adjoint': device in ['default.qubit'], + 'supports_backprop': device == 'default.qubit', + 'supports_adjoint': device in ('default.qubit', 'lightning.qubit'), } def _initialize_backend(self) -> None: - """Initialize PennyLane device.""" - try: - device_kwargs = self.config.copy() - device_kwargs.pop('wires', None) # Remove wires from kwargs if present - - # Create PennyLane device - if self.shots is not None and self.shots > 0: - self.dev = qml.device(self.device, wires=self.wires, shots=self.shots, **device_kwargs) - else: - # Exact simulation (no shots) - self.dev = qml.device(self.device, wires=self.wires, **device_kwargs) - - logger.info(f"Initialized PennyLane device: {self.device} with {self.wires} wires") - - except Exception as e: - logger.error(f"Failed to initialize PennyLane device: {e}") - raise - - def create_circuit(self, n_qubits: int) -> Callable: - """Create a PennyLane quantum function template.""" - if n_qubits > self.wires: - logger.warning(f"Requested {n_qubits} qubits, but device only has {self.wires} wires") - n_qubits = self.wires + # Validate the device name eagerly so misconfiguration fails fast. + self.dev = self._device(1) - def circuit_template(): - """Empty circuit template.""" - return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)] + def _device(self, n_wires: int) -> Any: + if n_wires not in self._devices: + kwargs = {k: v for k, v in self.config.items() if k != 'wires'} + self._devices[n_wires] = qml.device(self.device, wires=n_wires, **kwargs) + return self._devices[n_wires] - return circuit_template + # ------------------------------------------------------------------ + # Primitives + # ------------------------------------------------------------------ - def add_gate(self, circuit: Callable, gate: str, qubits: int | list[int], - params: list[float] | None = None) -> Callable: - """Add a quantum gate to the circuit (conceptual - PennyLane uses functions).""" - # In PennyLane, gates are added within quantum functions - # This method is more for compatibility with the base interface - logger.debug(f"Gate {gate} would be added to qubits {qubits} with params {params}") + def create_circuit(self, n_qubits: int) -> PennyLaneCircuit: + if n_qubits > self.wires: + raise ValueError(f"Requested {n_qubits} qubits, but backend allows {self.wires} wires") + return PennyLaneCircuit(n_qubits) + + def add_gate(self, circuit: PennyLaneCircuit, gate: str, qubits: int | list[int], + params: list[float] | None = None) -> PennyLaneCircuit: + if isinstance(qubits, int): + qubits = [qubits] + name = _GATES.get(gate.upper()) + if name is None: + raise ValueError(f"Unsupported gate for PennyLaneBackend: {gate}") + values = tuple(float(p) for p in (params or []))[:1] if name in _PARAMETRIC else () + if name in _PARAMETRIC and not values: + raise ValueError(f"Gate {gate} needs a rotation angle") + circuit.ops.append((name, values, tuple(int(q) for q in qubits))) return circuit - def add_measurement(self, circuit: Callable, qubits: list[int] | None = None) -> Callable: - """Add measurement operations (conceptual in PennyLane).""" + def add_measurement(self, circuit: PennyLaneCircuit, qubits: list[int] | None = None) -> PennyLaneCircuit: + circuit.measured = list(range(circuit.n_qubits)) if qubits is None else list(qubits) return circuit - def execute_circuit(self, circuit: Callable, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" - try: - # Create QNode - if shots is not None: - dev = qml.device(self.device, wires=self.wires, shots=shots) - qnode = qml.QNode(circuit, dev) - else: - qnode = qml.QNode(circuit, self.dev) - - # Execute - result = qnode() - - return { - 'result': result, - 'shots': shots or self.shots, - 'device': self.device, - } - - except Exception as e: - logger.error(f"Circuit execution failed: {e}") - raise - - def get_statevector(self, circuit: Callable) -> np.ndarray: - """Get the statevector from a quantum circuit.""" - # Create a statevector device - dev_statevector = qml.device('default.qubit', wires=self.wires) - - @qml.qnode(dev_statevector) - def statevector_circuit(): + def execute_circuit(self, circuit: PennyLaneCircuit | Callable, shots: int | None = None) -> dict[str, Any]: + """Sample the circuit and return counts (big-endian: wire 0 is the leftmost bit). + + A plain quantum function (legacy API) is also accepted; it is run as a + QNode and its return value is passed back under ``'result'``. + """ + shots = shots or self.shots + if not isinstance(circuit, PennyLaneCircuit): + qnode = qml.set_shots(qml.QNode(circuit, self._device(self.wires)), shots=shots) + return {'result': qnode(), 'shots': shots, 'device': self.device} + + wires = circuit.measured if circuit.measured is not None else list(range(circuit.n_qubits)) + + def qfunc(): + circuit.apply() + return qml.counts(wires=wires) + + qnode = qml.set_shots(qml.QNode(qfunc, self._device(circuit.n_qubits)), shots=shots) + counts = {str(k): int(v) for k, v in qnode().items()} + return {'counts': counts, 'shots': shots, 'device': self.device} + + def get_statevector(self, circuit: PennyLaneCircuit | Callable) -> np.ndarray: + """Exact statevector (big-endian, wire 0 most significant).""" + n = circuit.n_qubits if isinstance(circuit, PennyLaneCircuit) else self.wires + + def qfunc(): circuit() return qml.state() - return np.array(statevector_circuit()) + return np.asarray(qml.QNode(qfunc, self._device(n))()) def _get_n_qubits(self, circuit: Any) -> int: - """Get number of qubits in circuit.""" - return self.wires - - # ======================================================================== - # Enhanced PennyLane-specific implementations - # ======================================================================== - - def create_feature_map(self, n_features: int, feature_map: str, reps: int = 1) -> Callable: - """Create quantum feature map for data encoding.""" - if feature_map == 'ZZFeatureMap': - return self._create_zz_feature_map(n_features, reps) - elif feature_map == 'PauliFeatureMap': - return self._create_pauli_feature_map(n_features, reps) - elif feature_map == 'AmplitudeMap': - return self._create_amplitude_map(n_features) - else: - logger.warning(f"Unknown feature map '{feature_map}', using angle encoding") - return self._create_angle_encoding_map(n_features) - - def _create_zz_feature_map(self, n_features: int, reps: int) -> Callable: - """Create ZZ feature map circuit.""" - def zz_feature_map(x): - for r in range(reps): - # Single-qubit rotations - for i in range(min(n_features, self.wires)): - qml.Hadamard(wires=i) - qml.RZ(x[i], wires=i) - - # Two-qubit interactions - for i in range(min(n_features - 1, self.wires - 1)): - qml.CNOT(wires=[i, i + 1]) - qml.RZ(x[i] * x[i + 1], wires=i + 1) - qml.CNOT(wires=[i, i + 1]) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_features, self.wires))] - - return zz_feature_map - - def _create_pauli_feature_map(self, n_features: int, reps: int) -> Callable: - """Create Pauli feature map circuit.""" - def pauli_feature_map(x): - for r in range(reps): - for i in range(min(n_features, self.wires)): - qml.RX(x[i], wires=i) - qml.RY(x[i], wires=i) - qml.RZ(x[i], wires=i) - - # Entangling layer - for i in range(min(n_features - 1, self.wires - 1)): - qml.CNOT(wires=[i, i + 1]) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_features, self.wires))] - - return pauli_feature_map - - def _create_amplitude_map(self, n_features: int) -> Callable: - """Create amplitude encoding map.""" - def amplitude_map(x): - # Normalize input - norm = np.linalg.norm(x) - if norm > 0: - normalized_x = x / norm - else: - normalized_x = x - - # Pad to power of 2 - n_qubits = int(np.ceil(np.log2(len(normalized_x)))) - padded_x = np.pad(normalized_x, (0, 2**n_qubits - len(normalized_x))) - - # Amplitude encoding (simplified) - qml.QubitStateVector(padded_x, wires=range(min(n_qubits, self.wires))) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_qubits, self.wires))] - - return amplitude_map - - def _create_angle_encoding_map(self, n_features: int) -> Callable: - """Create angle encoding map.""" - def angle_encoding_map(x): - for i in range(min(n_features, self.wires)): - qml.RY(x[i], wires=i) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_features, self.wires))] - - return angle_encoding_map - - def compute_kernel_matrix(self, X1: np.ndarray, X2: np.ndarray, - feature_map: Callable, shots: int | None = None) -> np.ndarray: - """Compute quantum kernel matrix using PennyLane.""" - n1, n2 = len(X1), len(X2) - kernel_matrix = np.zeros((n1, n2)) - - # Create kernel evaluation circuit - def kernel_circuit(x1, x2): - # Encode first data point - for i in range(min(len(x1), self.wires)): - qml.RY(x1[i], wires=i) - - # Encode second data point with inverse - for i in range(min(len(x2), self.wires)): - qml.RY(-x2[i], wires=i) - - # Measure probability of |00...0โŸฉ state - return qml.probs(wires=range(min(len(x1), self.wires))) - - # Create QNode - dev = qml.device(self.device, wires=self.wires, shots=shots) if shots else self.dev - kernel_qnode = qml.QNode(kernel_circuit, dev) - - # Compute kernel matrix - for i in range(n1): - for j in range(n2): - try: - probs = kernel_qnode(X1[i], X2[j]) - kernel_matrix[i, j] = probs[0] # Probability of |00...0โŸฉ - except Exception as e: - logger.warning(f"Kernel computation failed for ({i},{j}): {e}") - kernel_matrix[i, j] = 0.0 - - return kernel_matrix - - def create_ansatz(self, ansatz_type: str, n_qubits: int, params: np.ndarray, - include_custom_gates: bool = False) -> Callable: - """Create parameterized ansatz circuit.""" - if ansatz_type == 'RealAmplitudes': - return self._create_real_amplitudes_ansatz(n_qubits, params) - elif ansatz_type == 'EfficientSU2': - return self._create_efficient_su2_ansatz(n_qubits, params) - elif ansatz_type == 'TwoLocal': - return self._create_two_local_ansatz(n_qubits, params) - elif ansatz_type == 'UCCSD': - return self._create_uccsd_ansatz(n_qubits, params) - else: - logger.warning(f"Unknown ansatz '{ansatz_type}', using RealAmplitudes") - return self._create_real_amplitudes_ansatz(n_qubits, params) - - def _create_real_amplitudes_ansatz(self, n_qubits: int, params: np.ndarray) -> Callable: - """Create RealAmplitudes ansatz.""" - def real_amplitudes_circuit(): - n_layers = len(params) // (n_qubits * 2) - param_idx = 0 - - for layer in range(n_layers): - # Rotation layer - for i in range(min(n_qubits, self.wires)): - if param_idx < len(params): - qml.RY(params[param_idx], wires=i) - param_idx += 1 - - # Entangling layer - for i in range(min(n_qubits - 1, self.wires - 1)): - qml.CNOT(wires=[i, i + 1]) - - # Second rotation layer - for i in range(min(n_qubits, self.wires)): - if param_idx < len(params): - qml.RZ(params[param_idx], wires=i) - param_idx += 1 - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_qubits, self.wires))] - - return real_amplitudes_circuit - - def _create_efficient_su2_ansatz(self, n_qubits: int, params: np.ndarray) -> Callable: - """Create EfficientSU2 ansatz.""" - def efficient_su2_circuit(): - n_layers = len(params) // (n_qubits * 3) - param_idx = 0 - - for layer in range(n_layers): - # SU(2) rotations - for i in range(min(n_qubits, self.wires)): - if param_idx + 2 < len(params): - qml.RY(params[param_idx], wires=i) - qml.RZ(params[param_idx + 1], wires=i) - qml.RY(params[param_idx + 2], wires=i) - param_idx += 3 - - # Entangling layer - for i in range(min(n_qubits - 1, self.wires - 1)): - qml.CNOT(wires=[i, i + 1]) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_qubits, self.wires))] - - return efficient_su2_circuit - - def _create_two_local_ansatz(self, n_qubits: int, params: np.ndarray) -> Callable: - """Create TwoLocal ansatz.""" - def two_local_circuit(): - n_layers = len(params) // (n_qubits * 2) - param_idx = 0 - - for layer in range(n_layers): - # Local rotations - for i in range(min(n_qubits, self.wires)): - if param_idx + 1 < len(params): - qml.RY(params[param_idx], wires=i) - qml.RZ(params[param_idx + 1], wires=i) - param_idx += 2 - - # Two-qubit gates - for i in range(0, min(n_qubits - 1, self.wires - 1), 2): - qml.CNOT(wires=[i, i + 1]) - for i in range(1, min(n_qubits - 1, self.wires - 1), 2): - qml.CNOT(wires=[i, i + 1]) - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_qubits, self.wires))] - - return two_local_circuit - - def _create_uccsd_ansatz(self, n_qubits: int, params: np.ndarray) -> Callable: - """Create UCCSD ansatz (simplified).""" - def uccsd_circuit(): - # Simplified UCCSD - full implementation would require molecular geometry - param_idx = 0 - - # Singles excitations - for i in range(0, min(n_qubits, self.wires), 2): - for j in range(1, min(n_qubits, self.wires), 2): - if param_idx < len(params) and i != j: - # Simplified single excitation - qml.CNOT(wires=[i, j]) - qml.RY(params[param_idx], wires=j) - qml.CNOT(wires=[i, j]) - param_idx += 1 - - # Doubles excitations (simplified) - for i in range(0, min(n_qubits - 3, self.wires - 3), 2): - if param_idx < len(params): - # Simplified double excitation - qml.CNOT(wires=[i, i + 1]) - qml.CNOT(wires=[i + 2, i + 3]) - qml.RY(params[param_idx], wires=i + 1) - qml.CNOT(wires=[i, i + 1]) - qml.CNOT(wires=[i + 2, i + 3]) - param_idx += 1 - - return [qml.expval(qml.PauliZ(i)) for i in range(min(n_qubits, self.wires))] - - return uccsd_circuit - - def compute_expectation(self, circuit: Callable, hamiltonian: Any, - shots: int | None = None) -> float: - """Compute expectation value of Hamiltonian.""" - try: - # If hamiltonian is a PennyLane Hamiltonian - if hasattr(hamiltonian, 'coeffs') and hasattr(hamiltonian, 'ops'): - @qml.qnode(self.dev if shots is None else qml.device(self.device, wires=self.wires, shots=shots)) - def expectation_circuit(): - circuit() - return qml.expval(hamiltonian) - - return float(expectation_circuit()) - - # If hamiltonian is a matrix, decompose it - elif isinstance(hamiltonian, np.ndarray): - return self._compute_matrix_expectation(circuit, hamiltonian, shots) - - else: - logger.warning("Unknown Hamiltonian format, returning 0") - return 0.0 - - except Exception as e: - logger.error(f"Expectation computation failed: {e}") - return 0.0 - - def _compute_matrix_expectation(self, circuit: Callable, H: np.ndarray, shots: int | None) -> float: - """Compute expectation value for matrix Hamiltonian.""" - # Get statevector - statevector = self.get_statevector(circuit) - - # Compute โŸจฯˆ|H|ฯˆโŸฉ - expectation = np.real(np.conj(statevector) @ H @ statevector) - return float(expectation) + return circuit.n_qubits if isinstance(circuit, PennyLaneCircuit) else self.wires def get_version_info(self) -> dict[str, Any]: - """Get PennyLane version information.""" info = super().get_version_info() - info.update({ - 'pennylane_version': qml.version() if qml else 'Not available', - 'available_devices': qml.plugin_devices if qml else [], - }) + info['pennylane_version'] = qml.__version__ return info diff --git a/src/superquantx/backends/qiskit_backend.py b/src/superquantx/backends/qiskit_backend.py index e463c4c..11b703d 100644 --- a/src/superquantx/backends/qiskit_backend.py +++ b/src/superquantx/backends/qiskit_backend.py @@ -1,489 +1,185 @@ """Qiskit backend implementation for SuperQuantX. -This module provides integration with IBM's Qiskit for quantum computing -operations and access to IBM Quantum hardware. +Local execution uses Qiskit Aer. IBM Quantum hardware is reached through +``qiskit-ibm-runtime`` (``QiskitRuntimeService`` with ``SamplerV2``); the +hardware path is untested in CI because it needs an IBM Quantum account. """ import logging -from typing import TYPE_CHECKING, Any +from typing import Any import numpy as np from .base_backend import BaseBackend -if TYPE_CHECKING: - from qiskit import QuantumCircuit - logger = logging.getLogger(__name__) -# Try to import Qiskit with modern structure try: - from qiskit import ( - ClassicalRegister, - QuantumCircuit, - QuantumRegister, - transpile, - ) - from qiskit_aer import AerSimulator + from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile from qiskit.quantum_info import Statevector + from qiskit_aer import AerSimulator QISKIT_AVAILABLE = True - - # Try to import algorithms and circuit library - try: - from qiskit_algorithms.optimizers import COBYLA, L_BFGS_B - QISKIT_ALGORITHMS_AVAILABLE = True - except ImportError: - QISKIT_ALGORITHMS_AVAILABLE = False - COBYLA = None - L_BFGS_B = None - - try: - from qiskit.circuit.library import EfficientSU2, RealAmplitudes, ZZFeatureMap - QISKIT_CIRCUIT_LIBRARY_AVAILABLE = True - except ImportError: - QISKIT_CIRCUIT_LIBRARY_AVAILABLE = False - EfficientSU2 = None - RealAmplitudes = None - ZZFeatureMap = None - - # Try to import IBM Quantum provider (deprecated) - try: - from qiskit_ibm_provider import IBMProvider - IBM_PROVIDER_AVAILABLE = True - IBMQ = None # IBMQ is deprecated - IBMQBackend = None - except ImportError: - IBM_PROVIDER_AVAILABLE = False - IBMProvider = None - IBMQ = None - IBMQBackend = None - except ImportError: QISKIT_AVAILABLE = False QuantumCircuit = None AerSimulator = None Statevector = None - QISKIT_ALGORITHMS_AVAILABLE = False - QISKIT_CIRCUIT_LIBRARY_AVAILABLE = False - IBM_PROVIDER_AVAILABLE = False -class QiskitBackend(BaseBackend): - """Qiskit backend for quantum computing operations. +try: + from qiskit_ibm_runtime import QiskitRuntimeService + from qiskit_ibm_runtime import SamplerV2 as RuntimeSampler + IBM_RUNTIME_AVAILABLE = True +except ImportError: + QiskitRuntimeService = None + RuntimeSampler = None + IBM_RUNTIME_AVAILABLE = False - This backend provides access to Qiskit simulators and IBM Quantum - hardware for quantum algorithm execution. +_AER_DEVICES = ('aer_simulator', 'qasm_simulator', 'statevector_simulator', 'simulator') +_AER_METHODS = ('automatic', 'statevector', 'density_matrix', 'stabilizer', + 'matrix_product_state', 'extended_stabilizer', 'unitary', 'superop') + + +class QiskitBackend(BaseBackend): + """Qiskit backend (Aer simulator locally, IBM Quantum via qiskit-ibm-runtime). Args: - device: Qiskit backend name ('aer_simulator', 'ibmq_qasm_simulator', etc.) - provider: IBM Quantum provider (if using IBMQ) - shots: Number of measurement shots - **kwargs: Additional backend parameters + device: ``'aer_simulator'`` (default), an Aer method name such as + ``'statevector'``, or an IBM backend name such as ``'ibm_brisbane'``. + provider: Optional dict of ``QiskitRuntimeService`` keyword arguments + (``channel``, ``token``, ``instance``) for IBM hardware. + shots: Number of measurement shots. """ - def __init__(self, device: str = 'aer_simulator', provider: str | None = None, + def __init__(self, device: str = 'aer_simulator', provider: dict | None = None, shots: int = 1024, **kwargs): if not QISKIT_AVAILABLE: - raise ImportError("Qiskit is required for QiskitBackend. Install with: pip install qiskit") - - super().__init__(device=device, shots=shots, **kwargs) - + raise ImportError( + "Qiskit is required for QiskitBackend. Install with: pip install 'superquantx[qiskit]'" + ) self.provider = provider self.backend = None + self.service = None + self.is_hardware = False + super().__init__(device=device, shots=shots, **kwargs) self.capabilities = { 'supports_gradient': False, 'supports_parameter_shift': True, 'supports_finite_diff': True, - 'supports_hardware': IBM_PROVIDER_AVAILABLE, + 'supports_hardware': IBM_RUNTIME_AVAILABLE, 'supports_noise_models': True, } - - # Initialize the backend - self._initialize_backend() def _initialize_backend(self) -> None: - """Initialize Qiskit backend.""" - try: - if self.device == 'aer_simulator': - self.backend = AerSimulator() - logger.info("Initialized Qiskit AerSimulator") - - elif self.device.startswith('ibmq_') or self.provider: - if not IBM_PROVIDER_AVAILABLE: - raise ImportError("IBM Quantum provider not available") - - # Load IBMQ account - if not IBMQ.active_account(): - try: - IBMQ.load_account() - except Exception as e: - logger.error(f"Failed to load IBMQ account: {e}") - raise - - # Get provider - if self.provider: - provider = IBMQ.get_provider(hub=self.provider.get('hub', 'ibm-q'), - group=self.provider.get('group', 'open'), - project=self.provider.get('project', 'main')) - else: - provider = IBMQ.get_provider() - - # Get backend - self.backend = provider.get_backend(self.device) - logger.info(f"Initialized IBM Quantum backend: {self.device}") - - else: - # Prefer AerSimulator; device string may be an Aer method name - try: - self.backend = AerSimulator(method=self.device) if self.device not in ( - 'aer_simulator', 'qasm_simulator', 'statevector_simulator' - ) else AerSimulator() - except Exception: - self.backend = AerSimulator() - logger.info(f"Initialized Aer backend: {self.device}") - - except Exception as e: - logger.error(f"Failed to initialize Qiskit backend: {e}") - # Fallback to simulator + device = self.device or 'aer_simulator' + if device in _AER_DEVICES: self.backend = AerSimulator() - logger.warning("Falling back to AerSimulator") + elif device in _AER_METHODS: + self.backend = AerSimulator(method=device) + elif device.startswith('ibm') or self.provider: + if not IBM_RUNTIME_AVAILABLE: + raise ImportError( + "qiskit-ibm-runtime is required for IBM Quantum hardware. " + "Install with: pip install 'qiskit-ibm-runtime>=0.50'" + ) + self.service = QiskitRuntimeService(**(self.provider or {})) + self.backend = self.service.backend(device) + self.is_hardware = True + logger.info("Using IBM Quantum backend %s (untested in CI)", device) + else: + raise ValueError( + f"Unknown Qiskit device '{device}'. Use 'aer_simulator', an Aer method " + "name, or an IBM backend name such as 'ibm_brisbane'." + ) + + # ------------------------------------------------------------------ + # Primitives + # ------------------------------------------------------------------ def create_circuit(self, n_qubits: int) -> Any: - """Create a quantum circuit with n qubits.""" - qreg = QuantumRegister(n_qubits, 'q') - creg = ClassicalRegister(n_qubits, 'c') - circuit = QuantumCircuit(qreg, creg) - return circuit + return QuantumCircuit(QuantumRegister(n_qubits, 'q'), ClassicalRegister(n_qubits, 'c')) def add_gate(self, circuit: Any, gate: str, qubits: int | list[int], params: list[float] | None = None) -> Any: - """Add a quantum gate to the circuit.""" if isinstance(qubits, int): qubits = [qubits] - - params = params or [] - - try: - if gate.upper() == 'H' or gate.upper() == 'HADAMARD': - circuit.h(qubits[0]) - elif gate.upper() == 'X' or gate.upper() == 'PAULI_X': - circuit.x(qubits[0]) - elif gate.upper() == 'Y' or gate.upper() == 'PAULI_Y': - circuit.y(qubits[0]) - elif gate.upper() == 'Z' or gate.upper() == 'PAULI_Z': - circuit.z(qubits[0]) - elif gate.upper() == 'RX': - circuit.rx(params[0] if params else 0, qubits[0]) - elif gate.upper() == 'RY': - circuit.ry(params[0] if params else 0, qubits[0]) - elif gate.upper() == 'RZ': - circuit.rz(params[0] if params else 0, qubits[0]) - elif gate.upper() == 'CNOT' or gate.upper() == 'CX': - circuit.cx(qubits[0], qubits[1]) - elif gate.upper() == 'CZ': - circuit.cz(qubits[0], qubits[1]) - elif gate.upper() == 'SWAP': - circuit.swap(qubits[0], qubits[1]) - elif gate.upper() == 'CCX' or gate.upper() == 'TOFFOLI': - circuit.ccx(qubits[0], qubits[1], qubits[2]) - else: - logger.warning(f"Unknown gate: {gate}") - - except Exception as e: - logger.error(f"Failed to add gate {gate}: {e}") - + params = list(params) if params is not None else [] + name = gate.upper() + single = {'H': 'h', 'HADAMARD': 'h', 'X': 'x', 'PAULI_X': 'x', 'Y': 'y', + 'PAULI_Y': 'y', 'Z': 'z', 'PAULI_Z': 'z', 'S': 's', 'SDG': 'sdg', + 'T': 't', 'TDG': 'tdg', 'I': 'id'} + rot = {'RX': 'rx', 'RY': 'ry', 'RZ': 'rz', 'P': 'p', 'PHASE': 'p', + 'CRX': 'crx', 'CRY': 'cry', 'CRZ': 'crz'} + multi = {'CNOT': 'cx', 'CX': 'cx', 'CZ': 'cz', 'SWAP': 'swap', + 'CCX': 'ccx', 'TOFFOLI': 'ccx'} + if name in single: + getattr(circuit, single[name])(qubits[0]) + elif name in rot: + getattr(circuit, rot[name])(float(params[0]), *qubits) + elif name in multi: + getattr(circuit, multi[name])(*qubits) + else: + raise ValueError(f"Unsupported gate for QiskitBackend: {gate}") return circuit def add_measurement(self, circuit: Any, qubits: list[int] | None = None) -> Any: - """Add measurement operations to the circuit.""" if qubits is None: qubits = list(range(circuit.num_qubits)) - + if circuit.num_clbits < len(qubits): + circuit.add_register(ClassicalRegister(len(qubits) - circuit.num_clbits, 'meas')) for i, qubit in enumerate(qubits): - if i < circuit.num_clbits: - circuit.measure(qubit, i) - + circuit.measure(qubit, i) return circuit - def execute_circuit(self, circuit: Any, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" - shots = shots or self.shots - - try: - # Add measurements if not present - has_measurements = circuit.num_clbits > 0 and any( - hasattr(instr.operation, 'name') and instr.operation.name == 'measure' - for instr in circuit.data - ) - - if not has_measurements: - # create_circuit already adds ClassicalRegister('c'); avoid duplicate name - if circuit.num_clbits < circuit.num_qubits: - circuit.add_register( - ClassicalRegister(circuit.num_qubits - circuit.num_clbits, 'meas') - ) - circuit.measure(range(circuit.num_qubits), range(circuit.num_qubits)) - - # Transpile circuit - transpiled = transpile(circuit, self.backend) + @staticmethod + def _has_measurements(circuit: Any) -> bool: + return any(instr.operation.name == 'measure' for instr in circuit.data) - # Execute using modern Qiskit API - job = self.backend.run(transpiled, shots=shots) - result = job.result() - - # Get counts - counts = result.get_counts() - - return { - 'counts': counts, - 'shots': shots, - 'backend': self.device, - 'job_id': job.job_id(), - } + def execute_circuit(self, circuit: Any, shots: int | None = None) -> dict[str, Any]: + """Run the circuit and return counts (little-endian: qubit 0 is the rightmost bit). - except Exception as e: - logger.error(f"Circuit execution failed: {e}") - raise + If the circuit has no measurements, all qubits are measured on a copy. + """ + shots = shots or self.shots + if not self._has_measurements(circuit): + circuit = self.add_measurement(circuit.copy()) + + if self.is_hardware: + from qiskit.transpiler import generate_preset_pass_manager + pm = generate_preset_pass_manager(backend=self.backend, optimization_level=1) + isa = pm.run(circuit) + job = RuntimeSampler(mode=self.backend).run([isa], shots=shots) + pub = job.result()[0] + counts: dict[str, int] = {} + for reg in isa.cregs: + data = getattr(pub.data, reg.name) + for k, v in data.get_counts().items(): + counts[k] = counts.get(k, 0) + v + break + return {'counts': counts, 'shots': shots, 'backend': self.device, + 'job_id': job.job_id()} + + job = self.backend.run(transpile(circuit, self.backend), shots=shots) + counts = job.result().get_counts() + return {'counts': dict(counts), 'shots': shots, 'backend': self.device, + 'job_id': job.job_id()} def get_statevector(self, circuit: Any) -> np.ndarray: - """Get the statevector from a quantum circuit.""" - try: - # Use statevector simulator - backend = AerSimulator(method='statevector') - - # Create circuit copy without measurements - circuit_copy = circuit.copy() - circuit_copy.remove_final_measurements() - - # Execute with BackendV2.run (qiskit.execute removed in Qiskit 2.x) - job = backend.run(circuit_copy, shots=1) - result = job.result() - - # Prefer quantum_info.Statevector when available - try: - statevector = Statevector.from_instruction(circuit_copy) - return np.array(statevector.data) - except Exception: - statevector = result.get_statevector() - data = getattr(statevector, 'data', statevector) - return np.array(data) - - except Exception as e: - logger.error(f"Statevector computation failed: {e}") - return np.array([1.0] + [0.0] * (2**circuit.num_qubits - 1)) + """Exact statevector (little-endian), computed with qiskit.quantum_info.""" + clean = circuit.remove_final_measurements(inplace=False) + return np.asarray(Statevector.from_instruction(clean).data) def _get_n_qubits(self, circuit: Any) -> int: - """Get number of qubits in circuit.""" return circuit.num_qubits - # ======================================================================== - # Enhanced Qiskit-specific implementations - # ======================================================================== - - def create_feature_map(self, n_features: int, feature_map: str, reps: int = 1) -> Any: - """Create quantum feature map for data encoding.""" - if feature_map == 'ZZFeatureMap': - return ZZFeatureMap(n_features, reps=reps) - elif feature_map == 'PauliFeatureMap': - return self._create_pauli_feature_map(n_features, reps) - elif feature_map == 'AmplitudeMap': - return self._create_amplitude_map(n_features) - else: - logger.warning(f"Unknown feature map '{feature_map}', using angle encoding") - return self._create_angle_encoding_map(n_features) - - def _create_pauli_feature_map(self, n_features: int, reps: int) -> Any: - """Create Pauli feature map circuit.""" - circuit = QuantumCircuit(n_features) - - for r in range(reps): - # Pauli rotations - for i in range(n_features): - circuit.rx(circuit.parameters[0], i) # Placeholder parameter - circuit.ry(circuit.parameters[0], i) - circuit.rz(circuit.parameters[0], i) - - # Entangling layer - for i in range(n_features - 1): - circuit.cx(i, i + 1) - - return circuit - - def _create_amplitude_map(self, n_features: int) -> Any: - """Create amplitude encoding map.""" - n_qubits = int(np.ceil(np.log2(n_features))) - circuit = QuantumCircuit(n_qubits) - - # Amplitude encoding would require state initialization - # This is a simplified placeholder - logger.warning("Amplitude encoding not fully implemented") - - return circuit - - def _create_angle_encoding_map(self, n_features: int) -> Any: - """Create angle encoding map.""" - circuit = QuantumCircuit(n_features) - - for i in range(n_features): - circuit.ry(circuit.parameters[0], i) # Placeholder parameter - - return circuit - - def compute_kernel_matrix(self, X1: np.ndarray, X2: np.ndarray, - feature_map: QuantumCircuit, shots: int | None = None) -> np.ndarray: - """Compute quantum kernel matrix using Qiskit.""" - n1, n2 = len(X1), len(X2) - kernel_matrix = np.zeros((n1, n2)) - - for i in range(n1): - for j in range(n2): - try: - # Create kernel evaluation circuit - circuit = QuantumCircuit(feature_map.num_qubits, feature_map.num_qubits) - - # Encode first data point - circuit.compose(feature_map.assign_parameters(X1[i]), inplace=True) - - # Encode second data point with inverse - inverse_map = feature_map.assign_parameters(-X2[j]).inverse() - circuit.compose(inverse_map, inplace=True) - - # Measure - circuit.measure_all() - - # Execute - result = self.execute_circuit(circuit, shots) - counts = result['counts'] - - # Kernel value is probability of measuring |00...0โŸฉ - zero_state = '0' * feature_map.num_qubits - kernel_matrix[i, j] = counts.get(zero_state, 0) / sum(counts.values()) - - except Exception as e: - logger.warning(f"Kernel computation failed for ({i},{j}): {e}") - kernel_matrix[i, j] = 0.0 - - return kernel_matrix - - def create_ansatz(self, ansatz_type: str, n_qubits: int, params: np.ndarray, - include_custom_gates: bool = False) -> Any: - """Create parameterized ansatz circuit.""" - if ansatz_type == 'RealAmplitudes': - return RealAmplitudes(n_qubits, reps=len(params) // (n_qubits * 2)) - elif ansatz_type == 'EfficientSU2': - return EfficientSU2(n_qubits, reps=len(params) // (n_qubits * 3)) - elif ansatz_type == 'TwoLocal': - return self._create_two_local_ansatz(n_qubits, params) - elif ansatz_type == 'UCCSD': - return self._create_uccsd_ansatz(n_qubits, params) - else: - logger.warning(f"Unknown ansatz '{ansatz_type}', using RealAmplitudes") - return RealAmplitudes(n_qubits, reps=len(params) // (n_qubits * 2)) - - def _create_two_local_ansatz(self, n_qubits: int, params: np.ndarray) -> Any: - """Create TwoLocal ansatz.""" - from qiskit.circuit.library import TwoLocal - return TwoLocal(n_qubits, 'ry', 'cx', 'linear', reps=len(params) // (n_qubits * 2)) - - def _create_uccsd_ansatz(self, n_qubits: int, params: np.ndarray) -> Any: - """Create UCCSD ansatz (simplified).""" - circuit = QuantumCircuit(n_qubits) - - # Simplified UCCSD implementation - param_idx = 0 - - # Single excitations - for i in range(0, n_qubits, 2): - for j in range(1, n_qubits, 2): - if param_idx < len(params) and i != j: - circuit.cx(i, j) - circuit.ry(params[param_idx], j) - circuit.cx(i, j) - param_idx += 1 - - # Double excitations (simplified) - for i in range(0, n_qubits - 3, 2): - if param_idx < len(params): - circuit.cx(i, i + 1) - circuit.cx(i + 2, i + 3) - circuit.ry(params[param_idx], i + 1) - circuit.cx(i, i + 1) - circuit.cx(i + 2, i + 3) - param_idx += 1 - - return circuit - - def compute_expectation(self, circuit: Any, hamiltonian: Any, - shots: int | None = None) -> float: - """Compute expectation value of Hamiltonian.""" - try: - # For Qiskit, we need to decompose Hamiltonian into Pauli terms - if isinstance(hamiltonian, np.ndarray): - # Compute expectation using statevector - statevector = self.get_statevector(circuit) - expectation = np.real(np.conj(statevector) @ hamiltonian @ statevector) - return float(expectation) - else: - logger.warning("Hamiltonian expectation not fully implemented") - return 0.0 - - except Exception as e: - logger.error(f"Expectation computation failed: {e}") - return 0.0 - - def create_qaoa_circuit(self, n_qubits: int, gammas: np.ndarray, betas: np.ndarray, - problem_hamiltonian: Any, mixer_hamiltonian: Any, - initial_state: Any, problem_instance: Any) -> Any: - """Create QAOA circuit with given parameters.""" - circuit = QuantumCircuit(n_qubits) - - # Initial state (uniform superposition) - for i in range(n_qubits): - circuit.h(i) - - # QAOA layers - for gamma, beta in zip(gammas, betas, strict=False): - # Problem Hamiltonian layer - self._apply_problem_hamiltonian(circuit, gamma, problem_instance) - - # Mixer Hamiltonian layer - self._apply_mixer_hamiltonian(circuit, beta) - - return circuit - - def _apply_problem_hamiltonian(self, circuit: Any, gamma: float, problem_instance: Any) -> None: - """Apply problem Hamiltonian to circuit.""" - # Simplified implementation for Max-Cut type problems - n_qubits = circuit.num_qubits - - if hasattr(problem_instance, 'shape') and len(problem_instance.shape) == 2: - # Assume adjacency matrix - for i in range(n_qubits): - for j in range(i + 1, n_qubits): - if problem_instance[i, j] != 0: - circuit.cx(i, j) - circuit.rz(gamma * problem_instance[i, j], j) - circuit.cx(i, j) - - def _apply_mixer_hamiltonian(self, circuit: Any, beta: float) -> None: - """Apply mixer Hamiltonian to circuit.""" - # Standard X-mixer - for i in range(circuit.num_qubits): - circuit.rx(2 * beta, i) - def get_version_info(self) -> dict[str, Any]: - """Get Qiskit version information.""" info = super().get_version_info() - - try: - import qiskit - info.update({ - 'qiskit_version': qiskit.__version__, - 'backend_name': (self.backend.name if hasattr(self.backend, 'name') else str(self.backend)) if self.backend else 'Unknown', - 'backend_version': getattr(self.backend, 'version', 'Unknown'), - }) - except Exception as e: - info['version_error'] = str(e) - + from importlib.metadata import PackageNotFoundError, version + for pkg in ('qiskit', 'qiskit-aer', 'qiskit-ibm-runtime'): + try: + info[f"{pkg.replace('-', '_')}_version"] = version(pkg) + except PackageNotFoundError: + pass + info['backend_name'] = getattr(self.backend, 'name', str(self.backend)) return info diff --git a/src/superquantx/backends/simulator_backend.py b/src/superquantx/backends/simulator_backend.py index 99467d8..f01acc5 100644 --- a/src/superquantx/backends/simulator_backend.py +++ b/src/superquantx/backends/simulator_backend.py @@ -5,7 +5,6 @@ """ import logging -from collections.abc import Callable from typing import Any, Union import numpy as np @@ -34,77 +33,30 @@ def __init__(self, n_qubits: int): self.state[0] = 1.0 # |00...0โŸฉ state def apply_gate(self, gate_matrix: np.ndarray, qubits: list[int]) -> None: - """Apply gate matrix to specified qubits.""" - if len(qubits) == 1: - self._apply_single_qubit_gate(gate_matrix, qubits[0]) - elif len(qubits) == 2: - self._apply_two_qubit_gate(gate_matrix, qubits) - else: - logger.warning("Gates with more than 2 qubits not implemented") - - def _apply_single_qubit_gate(self, gate: np.ndarray, qubit: int) -> None: - """Apply single qubit gate.""" - # Create full gate matrix - n = 2**self.n_qubits - full_gate = np.eye(n, dtype=complex) - - # Tensor product to create full gate - for i in range(n): - # Extract qubit states - bit_string = format(i, f'0{self.n_qubits}b') - qubit_state = int(bit_string[-(qubit+1)]) - - for j in range(n): - bit_string_j = format(j, f'0{self.n_qubits}b') - qubit_state_j = int(bit_string_j[-(qubit+1)]) - - # Check if other qubits are the same - if self._other_qubits_same(i, j, qubit): - full_gate[i, j] = gate[qubit_state, qubit_state_j] - else: - full_gate[i, j] = 0 - - # Apply gate - self.state = full_gate @ self.state - - def _apply_two_qubit_gate(self, gate: np.ndarray, qubits: list[int]) -> None: - """Apply two qubit gate.""" - # Simplified implementation for CNOT and other 2-qubit gates - q1, q2 = qubits - n = 2**self.n_qubits - new_state = np.zeros_like(self.state) - - for i in range(n): - bit_string = format(i, f'0{self.n_qubits}b') - q1_bit = int(bit_string[-(q1+1)]) - q2_bit = int(bit_string[-(q2+1)]) - - # Apply gate to these two qubits - input_state = q1_bit * 2 + q2_bit # Convert to gate input basis - - for output_state in range(4): - output_q1 = output_state // 2 - output_q2 = output_state % 2 - - # Create output bit string - output_bits = list(bit_string) - output_bits[-(q1+1)] = str(output_q1) - output_bits[-(q2+1)] = str(output_q2) - output_idx = int(''.join(output_bits), 2) - - new_state[output_idx] += gate[output_state, input_state] * self.state[i] - - self.state = new_state - - def _other_qubits_same(self, i: int, j: int, exclude_qubit: int) -> bool: - """Check if all qubits except exclude_qubit are the same in states i and j.""" - bit_i = format(i, f'0{self.n_qubits}b') - bit_j = format(j, f'0{self.n_qubits}b') - - for q in range(self.n_qubits): - if q != exclude_qubit and bit_i[-(q+1)] != bit_j[-(q+1)]: - return False - return True + """Apply a k-qubit gate matrix to ``qubits``. + + The gate matrix is written in the basis |q_0 q_1 ...> of the listed + qubits (first listed qubit is the most significant), e.g. CNOT with + ``qubits=[control, target]``. The state index uses little-endian + ordering: qubit q is bit q of the index. + """ + k = len(qubits) + if len(set(qubits)) != k: + raise ValueError(f"Gate qubits must be distinct, got {qubits}") + if gate_matrix.shape != (2 ** k, 2 ** k): + raise ValueError( + f"Gate of shape {gate_matrix.shape} cannot act on {k} qubit(s)" + ) + n = self.n_qubits + for q in qubits: + if not 0 <= q < n: + raise ValueError(f"Qubit {q} out of range for {n}-qubit circuit") + axes = [n - 1 - q for q in qubits] + psi = self.state.reshape([2] * n) + gate = gate_matrix.reshape([2] * (2 * k)) + psi = np.tensordot(gate, psi, axes=(list(range(k, 2 * k)), axes)) + psi = np.moveaxis(psi, list(range(k)), axes) + self.state = psi.reshape(-1) def measure(self, qubit_or_shots=None, classical_bit=None, shots: int = 1024) -> Union[dict[str, int], "QuantumState"]: """Measure quantum state or add measurement to circuit.""" @@ -303,121 +255,87 @@ def _define_gates(self) -> dict[str, np.ndarray]: return { 'I': identity, 'X': X, 'Y': Y, 'Z': Z, 'H': H, 'S': S, 'T': T, + 'SDG': S.conj().T, 'TDG': T.conj().T, 'CNOT': CNOT, 'CX': CNOT, 'CZ': CZ, 'SWAP': SWAP, 'PAULI_X': X, 'PAULI_Y': Y, 'PAULI_Z': Z, 'HADAMARD': H } def _rotation_gate(self, axis: str, angle: float) -> np.ndarray: """Create rotation gate matrix.""" - if axis.upper() == 'X': - return np.array([ - [np.cos(angle/2), -1j*np.sin(angle/2)], - [-1j*np.sin(angle/2), np.cos(angle/2)] - ], dtype=complex) - elif axis.upper() == 'Y': - return np.array([ - [np.cos(angle/2), -np.sin(angle/2)], - [np.sin(angle/2), np.cos(angle/2)] - ], dtype=complex) - elif axis.upper() == 'Z': - return np.array([ - [np.exp(-1j*angle/2), 0], - [0, np.exp(1j*angle/2)] - ], dtype=complex) - else: - return np.eye(2, dtype=complex) + c, s_ = np.cos(angle / 2), np.sin(angle / 2) + if axis == 'X': + return np.array([[c, -1j * s_], [-1j * s_, c]], dtype=complex) + if axis == 'Y': + return np.array([[c, -s_], [s_, c]], dtype=complex) + if axis == 'Z': + return np.array([[np.exp(-1j * angle / 2), 0], + [0, np.exp(1j * angle / 2)]], dtype=complex) + raise ValueError(f"Unknown rotation axis: {axis}") + + @staticmethod + def _controlled(u: np.ndarray) -> np.ndarray: + d = u.shape[0] + m = np.eye(2 * d, dtype=complex) + m[d:, d:] = u + return m def create_circuit(self, n_qubits: int) -> QuantumState: """Create a quantum circuit with n qubits.""" if n_qubits > self.max_qubits: - logger.warning(f"Requested {n_qubits} qubits, but max is {self.max_qubits}") - n_qubits = self.max_qubits - + raise ValueError( + f"Requested {n_qubits} qubits, but this simulator is limited to " + f"{self.max_qubits} (pass max_qubits=... to raise the limit)" + ) return QuantumState(n_qubits) def add_gate(self, circuit: QuantumState, gate: str, qubits: int | list[int], params: list[float] | None = None) -> QuantumState: - """Add a quantum gate to the circuit.""" - if isinstance(qubits, int): - qubits = [qubits] - - params = params or [] + """Apply a quantum gate to the circuit state. - try: - # Rotation gates - if gate.upper().startswith('R'): - axis = gate.upper()[1:] - angle = params[0] if params else 0 - gate_matrix = self._rotation_gate(axis, angle) - circuit.apply_gate(gate_matrix, qubits) + Raises: + ValueError: for unknown gates or invalid qubits. - # Fixed gates - elif gate.upper() in self.gates: - gate_matrix = self.gates[gate.upper()] - circuit.apply_gate(gate_matrix, qubits) - - # Special cases - elif gate.upper() == 'CCX' or gate.upper() == 'TOFFOLI': - # Simplified Toffoli implementation - if len(qubits) >= 3: - self._apply_toffoli(circuit, qubits[:3]) - - else: - logger.warning(f"Unknown gate: {gate}") - - except Exception as e: - logger.error(f"Failed to add gate {gate}: {e}") + """ + if isinstance(qubits, int): + qubits = [qubits] + qubits = [int(q) for q in qubits] + params = list(params) if params is not None else [] + name = gate.upper() + + if name in ('RX', 'RY', 'RZ'): + matrix = self._rotation_gate(name[1], float(params[0])) + elif name in ('P', 'PHASE', 'U1'): + matrix = np.diag([1, np.exp(1j * float(params[0]))]).astype(complex) + elif name in ('CRX', 'CRY', 'CRZ'): + matrix = self._controlled(self._rotation_gate(name[2], float(params[0]))) + elif name in ('CCX', 'TOFFOLI'): + matrix = self._controlled(self.gates['CNOT']) + elif name in self.gates: + matrix = self.gates[name] + else: + raise ValueError(f"Unsupported gate for SimulatorBackend: {gate}") + circuit.apply_gate(matrix, qubits) return circuit - def _apply_toffoli(self, circuit: QuantumState, qubits: list[int]) -> None: - """Apply Toffoli gate (simplified implementation).""" - # This is a simplified implementation - # Full implementation would require proper 3-qubit gate matrix - logger.warning("Toffoli gate implementation simplified") - - # Apply CNOT(q2, q3) controlled by q1 - # This is not the correct Toffoli implementation - cnot_matrix = self.gates['CNOT'] - circuit.apply_gate(cnot_matrix, qubits[1:3]) - def add_measurement(self, circuit: QuantumState, qubits: list[int] | None = None) -> QuantumState: """Add measurement operations (no-op in this implementation).""" # Measurements are handled in execute_circuit return circuit def execute_circuit(self, circuit: QuantumState, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" + """Sample all qubits. Bitstrings are little-endian (qubit 0 rightmost), like Qiskit.""" shots = shots or self.shots - - try: - # Measure the circuit - probabilities = np.abs(circuit.state)**2 - - # Sample outcomes - outcomes = np.random.choice(len(circuit.state), size=shots, p=probabilities) - - # Convert to bit strings and count - counts = {} - for outcome in outcomes: - bit_string = format(outcome, f'0{circuit.n_qubits}b') - counts[bit_string] = counts.get(bit_string, 0) + 1 - - return { - 'counts': counts, - 'shots': shots, - 'backend': 'python_simulator', - } - - except Exception as e: - logger.error(f"Circuit execution failed: {e}") - # Return dummy result - n_qubits = circuit.n_qubits - return { - 'counts': {'0' * n_qubits: shots}, - 'shots': shots, - 'backend': 'python_simulator', - } + probabilities = np.abs(circuit.state) ** 2 + probabilities = probabilities / probabilities.sum() + outcomes = np.random.choice(len(circuit.state), size=shots, p=probabilities) + values, freq = np.unique(outcomes, return_counts=True) + counts = {format(int(v), f'0{circuit.n_qubits}b'): int(c) for v, c in zip(values, freq, strict=True)} + return { + 'counts': counts, + 'shots': shots, + 'backend': 'python_simulator', + } def get_statevector(self, circuit: QuantumState) -> np.ndarray: """Get the statevector from a quantum circuit.""" @@ -427,141 +345,6 @@ def _get_n_qubits(self, circuit: QuantumState) -> int: """Get number of qubits in circuit.""" return circuit.n_qubits - # ======================================================================== - # Enhanced simulator implementations - # ======================================================================== - - def compute_kernel_matrix(self, X1: np.ndarray, X2: np.ndarray, - feature_map: Any, shots: int | None = None) -> np.ndarray: - """Compute quantum kernel matrix using simulator.""" - n1, n2 = len(X1), len(X2) - kernel_matrix = np.zeros((n1, n2)) - - for i in range(n1): - for j in range(n2): - try: - # Simple kernel computation based on data similarity - # This is a placeholder - actual implementation would use feature maps - similarity = np.exp(-np.linalg.norm(X1[i] - X2[j])**2 / 2) - kernel_matrix[i, j] = similarity - - except Exception as e: - logger.warning(f"Kernel computation failed for ({i},{j}): {e}") - kernel_matrix[i, j] = 0.0 - - return kernel_matrix - - def create_feature_map(self, n_features: int, feature_map: str, reps: int = 1) -> Callable: - """Create quantum feature map for data encoding.""" - def feature_map_circuit(x): - circuit = self.create_circuit(n_features) - - for r in range(reps): - if feature_map == 'ZZFeatureMap': - # ZZ feature map implementation - for i in range(n_features): - circuit = self.add_gate(circuit, 'H', i) - circuit = self.add_gate(circuit, 'RZ', i, [x[i]]) - - # ZZ interactions - for i in range(n_features - 1): - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - circuit = self.add_gate(circuit, 'RZ', i + 1, [x[i] * x[i + 1]]) - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - - elif feature_map == 'PauliFeatureMap': - # Pauli feature map implementation - for i in range(n_features): - circuit = self.add_gate(circuit, 'RX', i, [x[i]]) - circuit = self.add_gate(circuit, 'RY', i, [x[i]]) - circuit = self.add_gate(circuit, 'RZ', i, [x[i]]) - - # Entangling - for i in range(n_features - 1): - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - - else: # Default angle encoding - for i in range(n_features): - circuit = self.add_gate(circuit, 'RY', i, [x[i]]) - - return circuit - - return feature_map_circuit - - def create_ansatz(self, ansatz_type: str, n_qubits: int, params: np.ndarray, - include_custom_gates: bool = False) -> Callable: - """Create parameterized ansatz circuit.""" - def ansatz_circuit(): - circuit = self.create_circuit(n_qubits) - param_idx = 0 - - if ansatz_type == 'RealAmplitudes': - n_layers = len(params) // (n_qubits * 2) - - for layer in range(n_layers): - # RY rotations - for i in range(n_qubits): - if param_idx < len(params): - circuit = self.add_gate(circuit, 'RY', i, [params[param_idx]]) - param_idx += 1 - - # Entangling - for i in range(n_qubits - 1): - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - - # RZ rotations - for i in range(n_qubits): - if param_idx < len(params): - circuit = self.add_gate(circuit, 'RZ', i, [params[param_idx]]) - param_idx += 1 - - elif ansatz_type == 'EfficientSU2': - n_layers = len(params) // (n_qubits * 3) - - for layer in range(n_layers): - # SU(2) rotations - for i in range(n_qubits): - if param_idx + 2 < len(params): - circuit = self.add_gate(circuit, 'RY', i, [params[param_idx]]) - circuit = self.add_gate(circuit, 'RZ', i, [params[param_idx + 1]]) - circuit = self.add_gate(circuit, 'RY', i, [params[param_idx + 2]]) - param_idx += 3 - - # Entangling - for i in range(n_qubits - 1): - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - - else: # Default to simple parameterized circuit - for i in range(n_qubits): - if param_idx < len(params): - circuit = self.add_gate(circuit, 'RY', i, [params[param_idx]]) - param_idx += 1 - - for i in range(n_qubits - 1): - circuit = self.add_gate(circuit, 'CNOT', [i, i + 1]) - - return circuit - - return ansatz_circuit - - def compute_expectation(self, circuit: QuantumState, hamiltonian: Any, - shots: int | None = None) -> float: - """Compute expectation value of Hamiltonian.""" - try: - if isinstance(hamiltonian, np.ndarray): - # Compute โŸจฯˆ|H|ฯˆโŸฉ - statevector = circuit.get_statevector() - expectation = np.real(np.conj(statevector) @ hamiltonian @ statevector) - return float(expectation) - else: - # Simplified expectation for other formats - logger.warning("Simplified Hamiltonian expectation") - return np.random.random() * 2 - 1 # Random value between -1 and 1 - - except Exception as e: - logger.error(f"Expectation computation failed: {e}") - return 0.0 - def get_version_info(self) -> dict[str, Any]: """Get simulator version information.""" info = super().get_version_info() diff --git a/src/superquantx/backends/tket_backend.py b/src/superquantx/backends/tket_backend.py index 8646ee7..c72ea77 100644 --- a/src/superquantx/backends/tket_backend.py +++ b/src/superquantx/backends/tket_backend.py @@ -17,34 +17,34 @@ # Try to import TKET/pytket try: from pytket import Circuit, OpType - from pytket.backends import Backend - from pytket.backends.simulator import AerBackend - from pytket.circuit import Bit, Qubit - - # Try to import Quantinuum backend - try: - from pytket.extensions.quantinuum import QuantinuumBackend - QUANTINUUM_AVAILABLE = True - except ImportError: - QUANTINUUM_AVAILABLE = False - - # Try to import other TKET backends - try: - from pytket.extensions.cirq import CirqBackend as TKETCirqBackend - from pytket.extensions.qiskit import AerStateBackend - TKET_EXTENSIONS_AVAILABLE = True - except ImportError: - TKET_EXTENSIONS_AVAILABLE = False - TKET_AVAILABLE = True - except ImportError: TKET_AVAILABLE = False - QUANTINUUM_AVAILABLE = False - TKET_EXTENSIONS_AVAILABLE = False Circuit = None OpType = None +# Local shot-based simulation goes through pytket-qiskit's AerBackend. +try: + from pytket.extensions.qiskit import AerBackend + TKET_EXTENSIONS_AVAILABLE = True +except ImportError: + AerBackend = None + TKET_EXTENSIONS_AVAILABLE = False + +try: + from pytket.extensions.quantinuum import QuantinuumBackend + QUANTINUUM_AVAILABLE = True +except ImportError: + QuantinuumBackend = None + QUANTINUUM_AVAILABLE = False + +try: + from pytket.extensions.cirq import CirqStateSampleBackend as TKETCirqBackend + TKET_CIRQ_AVAILABLE = True +except ImportError: + TKETCirqBackend = None + TKET_CIRQ_AVAILABLE = False + class TKETBackend(BaseBackend): """TKET (Quantum Toolkit) backend for quantum computing operations. @@ -92,56 +92,36 @@ def __init__( def _initialize_backend(self) -> None: """Initialize TKET backend and device.""" - try: - if self.device_name in ['aer_simulator', 'simulator']: - # Use TKET Aer simulator - if TKET_EXTENSIONS_AVAILABLE: - from pytket.extensions.qiskit import AerBackend - self._backend = AerBackend() - else: - # Fallback to basic simulator - logger.warning("TKET extensions not available, using basic simulator") - self._backend = None - - elif self.device_name.startswith('H') and '-' in self.device_name: - # Quantinuum hardware (H1-1E, H1-2E, H2-1, etc.) - if not QUANTINUUM_AVAILABLE: - raise ImportError("Quantinuum backend not available. Install with: pip install pytket-quantinuum") - - if not self.api_key: - raise ValueError("API key required for Quantinuum hardware") - - self._backend = QuantinuumBackend( - device_name=self.machine, - api_key=self.api_key + if self.device_name in ('aer_simulator', 'simulator'): + if not TKET_EXTENSIONS_AVAILABLE: + raise ImportError( + "Local TKET simulation needs pytket-qiskit. Install with: pip install pytket-qiskit" ) - logger.info(f"Initialized Quantinuum backend: {self.machine}") - - elif self.device_name in ['cirq', 'cirq_simulator']: - # TKET Cirq integration - if TKET_EXTENSIONS_AVAILABLE: - self._backend = TKETCirqBackend() - else: - raise ImportError("TKET Cirq extension not available") - - else: - # Try to create generic backend - logger.warning(f"Unknown device {self.device_name}, using simulator fallback") - self._backend = None - - self.capabilities = { - 'supports_measurements': True, - 'supports_parameterized_circuits': True, - 'supports_classical_control': True, - 'supports_mid_circuit_measurement': True, - 'max_qubits': self._get_max_qubits(), - 'native_gates': self._get_native_gates(), - 'supports_optimization': True, # TKET's key feature - } + self._backend = AerBackend() + elif self.device_name.startswith('H') and '-' in self.device_name: + # Quantinuum hardware or emulators (untested: needs a Quantinuum account) + if not QUANTINUUM_AVAILABLE: + raise ImportError("Quantinuum backend not available. Install with: pip install pytket-quantinuum") + self._backend = QuantinuumBackend(device_name=self.machine) + elif self.device_name in ('cirq', 'cirq_simulator'): + if not TKET_CIRQ_AVAILABLE: + raise ImportError("TKET Cirq extension not available. Install with: pip install pytket-cirq") + self._backend = TKETCirqBackend() + else: + raise ValueError( + f"Unknown TKET device '{self.device_name}'. Use 'aer_simulator', " + "'cirq_simulator' or a Quantinuum device name such as 'H1-1E'." + ) - except Exception as e: - logger.error(f"Failed to initialize TKET backend: {e}") - raise + self.capabilities = { + 'supports_measurements': True, + 'supports_parameterized_circuits': True, + 'supports_classical_control': True, + 'supports_mid_circuit_measurement': True, + 'max_qubits': self._get_max_qubits(), + 'native_gates': self._get_native_gates(), + 'supports_optimization': True, + } def _get_max_qubits(self) -> int: """Get maximum number of qubits for the device.""" @@ -187,131 +167,64 @@ def create_circuit(self, n_qubits: int) -> Circuit: circuit = Circuit(n_qubits) return circuit + _GATES = { + 'i': 'noop', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 'hadamard': 'H', + 's': 'S', 'sdg': 'Sdg', 't': 'T', 'tdg': 'Tdg', + 'rx': 'Rx', 'ry': 'Ry', 'rz': 'Rz', 'p': 'U1', 'phase': 'U1', 'u1': 'U1', + 'cnot': 'CX', 'cx': 'CX', 'cz': 'CZ', 'cy': 'CY', 'ch': 'CH', 'swap': 'SWAP', + 'crx': 'CRx', 'cry': 'CRy', 'crz': 'CRz', + 'ccnot': 'CCX', 'ccx': 'CCX', 'toffoli': 'CCX', 'cswap': 'CSWAP', 'fredkin': 'CSWAP', + } + def add_gate(self, circuit: Circuit, gate: str, qubits: int | list[int], params: list[float] | None = None) -> Circuit: - """Add a quantum gate to the circuit.""" + """Add a gate. Angles are given in radians (converted to TKET half-turns).""" if isinstance(qubits, int): qubits = [qubits] - - params = params or [] - - # Map gate names to TKET OpTypes - gate_mapping = { - 'i': OpType.noop, # Identity - 'x': OpType.X, 'y': OpType.Y, 'z': OpType.Z, 'h': OpType.H, - 's': OpType.S, 'sdg': OpType.Sdg, 't': OpType.T, 'tdg': OpType.Tdg, - 'rx': OpType.Rx, 'ry': OpType.Ry, 'rz': OpType.Rz, - 'cnot': OpType.CX, 'cx': OpType.CX, 'cz': OpType.CZ, 'cy': OpType.CY, - 'ch': OpType.CH, 'swap': OpType.SWAP, - 'ccnot': OpType.CCX, 'ccx': OpType.CCX, 'toffoli': OpType.CCX, - 'cswap': OpType.CSWAP, 'fredkin': OpType.CSWAP, - 'iswap': OpType.ISWAPMax, - 'u1': OpType.U1, 'u2': OpType.U2, 'u3': OpType.U3, - } - - gate_upper = gate.upper() - gate_lower = gate.lower() - - # Try exact match first, then case variations - op_type = None - if hasattr(OpType, gate_upper): - op_type = getattr(OpType, gate_upper) - elif gate_lower in gate_mapping: - op_type = gate_mapping[gate_lower] - - if op_type is None: + name = self._GATES.get(gate.lower()) + if name is None: raise ValueError(f"Gate '{gate}' not supported in TKET backend") - - try: - # Convert qubit indices to TKET Qubit objects - tket_qubits = [circuit.qubits[q] for q in qubits] - - if len(params) == 0: - # Parameter-less gates - circuit.add_gate(op_type, tket_qubits) - else: - # Parameterized gates - circuit.add_gate(op_type, tket_qubits, params) - - except Exception as e: - logger.error(f"Failed to add gate {gate} to TKET circuit: {e}") - raise - + op_type = getattr(OpType, name) + tket_qubits = [circuit.qubits[q] for q in qubits] + if params: + circuit.add_gate(op_type, [float(p) / np.pi for p in params], tket_qubits) + else: + circuit.add_gate(op_type, tket_qubits) return circuit - def add_measurement(self, circuit: Circuit, qubits: int | list[int]) -> Circuit: - """Add measurement instructions to specified qubits.""" - if isinstance(qubits, int): + def add_measurement(self, circuit: Circuit, qubits: int | list[int] | None = None) -> Circuit: + """Measure ``qubits`` (all qubits by default) into classical bits 0..k-1.""" + if qubits is None: + qubits = list(range(circuit.n_qubits)) + elif isinstance(qubits, int): qubits = [qubits] - - # TKET requires explicit bit allocation for measurements - n_bits = len(qubits) - if circuit.n_bits < n_bits: - circuit.add_c_register("c", n_bits - circuit.n_bits) - + if circuit.n_bits < len(qubits): + circuit.add_c_register("c", len(qubits) - circuit.n_bits) for i, qubit in enumerate(qubits): circuit.Measure(circuit.qubits[qubit], circuit.bits[i]) - return circuit def execute_circuit(self, circuit: Circuit, shots: int | None = None) -> dict[str, Any]: - """Execute quantum circuit and return results.""" - shots = shots or self.shots + """Compile and run the circuit. Counts are big-endian (bit 0 is the leftmost character). - try: - if self._backend is None: - # Simple simulation fallback - logger.warning("No TKET backend available, using simulation fallback") - n_qubits = circuit.n_qubits - n_bits = circuit.n_bits or n_qubits - - # Generate random results for fallback - counts = {} - for _ in range(shots): - bitstring = ''.join([str(np.random.randint(0, 2)) for _ in range(n_bits)]) - counts[bitstring] = counts.get(bitstring, 0) + 1 - - return { - 'counts': counts, - 'shots': shots, - 'success': True, - 'backend': 'tket_fallback', - } - - # Compile circuit for backend - compiled_circuit = self._backend.get_compiled_circuit(circuit) - - # Execute on backend - handle = self._backend.process_circuit(compiled_circuit, n_shots=shots) - result = self._backend.get_result(handle) - - # Extract counts - counts_dict = {} - if hasattr(result, 'get_counts'): - counts_dict = result.get_counts() - elif hasattr(result, 'counts'): - counts_dict = result.counts - else: - logger.warning("Could not extract counts from TKET result") - - return { - 'counts': counts_dict, - 'shots': shots, - 'success': True, - 'backend': self._backend.__class__.__name__, - 'compiled': True, - 'device': self.device_name, - } - - except Exception as e: - logger.error(f"TKET circuit execution failed: {e}") - return { - 'counts': {}, - 'shots': shots, - 'success': False, - 'error': str(e), - 'device': self.device_name, - } + Unmeasured circuits get all qubits measured on a copy. + """ + shots = shots or self.shots + if circuit.n_gates_of_type(OpType.Measure) == 0: + circuit = circuit.copy() + circuit.measure_all() + compiled_circuit = self._backend.get_compiled_circuit(circuit) + handle = self._backend.process_circuit(compiled_circuit, n_shots=shots) + result = self._backend.get_result(handle) + counts = {''.join(str(int(b)) for b in key): int(v) for key, v in result.get_counts().items()} + return { + 'counts': counts, + 'shots': shots, + 'success': True, + 'backend': self._backend.__class__.__name__, + 'compiled': True, + 'device': self.device_name, + } # ======================================================================== # TKET-Specific Features @@ -360,78 +273,6 @@ def optimize_circuit(self, circuit: Circuit, optimization_level: int = 2) -> Cir logger.error(f"Circuit optimization failed: {e}") return circuit - def create_parameterized_circuit(self, n_qubits: int, n_params: int) -> tuple[Circuit, list[str]]: - """Create a parameterized quantum circuit for variational algorithms.""" - from pytket.circuit import fresh_symbol - - circuit = self.create_circuit(n_qubits) - - # Create symbolic parameters - symbols = [fresh_symbol(f"theta_{i}") for i in range(n_params)] - param_names = [str(symbol) for symbol in symbols] - - # Store parameter info - circuit._symbols = symbols - circuit._param_names = param_names - - return circuit, param_names - - def bind_parameters(self, circuit: Circuit, param_values: dict[str, float]) -> Circuit: - """Bind parameter values to parameterized circuit.""" - try: - bound_circuit = circuit.copy() - - # Create symbol substitution map - if hasattr(circuit, '_symbols'): - symbol_map = {} - for symbol, name in zip(circuit._symbols, circuit._param_names, strict=False): - if name in param_values: - symbol_map[symbol] = param_values[name] - - # Substitute symbols with values - bound_circuit.symbol_substitution(symbol_map) - - return bound_circuit - - except Exception as e: - logger.error(f"Parameter binding failed: {e}") - return circuit - - def expectation_value(self, circuit: Circuit, observable: str | np.ndarray, - shots: int | None = None) -> float: - """Calculate expectation value of observable using TKET.""" - shots = shots or self.shots - - try: - if isinstance(observable, str) and observable.upper() == 'Z': - # Measure in Z basis - measured_circuit = circuit.copy() - measured_circuit.add_c_register("c", 1) - measured_circuit.Measure(measured_circuit.qubits[0], measured_circuit.bits[0]) - - result = self.execute_circuit(measured_circuit, shots) - counts = result['counts'] - - # Calculate expectation - expectation = 0.0 - total_counts = sum(counts.values()) - - for bitstring, count in counts.items(): - prob = count / total_counts - if bitstring[0] == '0': - expectation += prob - else: - expectation -= prob - - return expectation - else: - logger.warning("Only Z observable currently implemented") - return 0.0 - - except Exception as e: - logger.error(f"Expectation value calculation failed: {e}") - return 0.0 - # ======================================================================== # Backend Information # ======================================================================== @@ -499,21 +340,10 @@ def _get_n_qubits(self, circuit: Circuit) -> int: return circuit.n_qubits def get_statevector(self, circuit: Circuit) -> np.ndarray: - """Get statevector from TKET circuit.""" - try: - if TKET_EXTENSIONS_AVAILABLE: - from pytket.extensions.qiskit import AerStateBackend - state_backend = AerStateBackend() - compiled_circuit = state_backend.get_compiled_circuit(circuit) - handle = state_backend.process_circuit(compiled_circuit) - result = state_backend.get_result(handle) - - if hasattr(result, 'get_state'): - return result.get_state() - - logger.warning("Statevector not available with current TKET setup") - return np.zeros(2**circuit.n_qubits, dtype=complex) - - except Exception as e: - logger.error(f"Failed to get statevector: {e}") - return np.zeros(2**circuit.n_qubits, dtype=complex) + """Exact statevector (big-endian) computed by pytket, ignoring measurements.""" + clean = Circuit(circuit.n_qubits) + for cmd in circuit.get_commands(): + if cmd.op.type == OpType.Measure: + continue + clean.add_gate(cmd.op, cmd.args) + return np.asarray(clean.get_statevector(), dtype=complex) diff --git a/src/superquantx/benchmarks.py b/src/superquantx/benchmarks.py new file mode 100644 index 0000000..4ba6e24 --- /dev/null +++ b/src/superquantx/benchmarks.py @@ -0,0 +1,324 @@ +"""Honest classical baselines for quantum classifiers. + +``compare_to_classical`` runs a quantum classifier, a tuned RBF SVM and a tuned +logistic regression on exactly the same stratified cross-validation folds, with +preprocessing fitted inside each fold, and reports mean and standard deviation of +the test accuracy together with wall time. + +The protocol follows the controls recommended by Bhalgami (2026), "Empirical +Evaluation of Quantum Kernel Methods for Classification: A Comparative Study with +Classical Kernels", arXiv:2610.42029: + +* the quantum kernel bandwidth is tuned on a grid of the same size as the RBF + ``gamma`` grid, so neither side is handicapped; +* the scaler is fitted on the training fold only and the quantum kernel is + recomputed inside every fold; +* the hardware cost of the fidelity kernel is reported in circuit evaluations + (``n_train * (n_train - 1) / 2 + n_test * n_train`` per fold and grid point), + because simulator wall time says nothing about QPU cost. + +That paper finds tuned quantum kernels statistically indistinguishable from a +tuned RBF SVM on four standard datasets. Expect the same here: on classical data +the honest default is a tie or a classical win. All quantum results in this +package are classically simulated. +""" + +from __future__ import annotations + +import time +from dataclasses import asdict, dataclass, field +from typing import Any + +import numpy as np +from sklearn.linear_model import LogisticRegression +from sklearn.model_selection import GridSearchCV, StratifiedKFold +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC + + +__all__ = [ + "ModelScore", + "ComparisonResult", + "compare_to_classical", + "corrected_paired_ttest", +] + +ARXIV_REFERENCE = "arXiv:2610.42029" + +DEFAULT_C_GRID = (0.1, 1.0, 10.0, 100.0, 1000.0) +DEFAULT_RBF_GAMMA_GRID = (0.01, 0.1, 1.0, 10.0, 100.0) +DEFAULT_BANDWIDTH_GRID = (0.05, 0.1, 0.25, 0.5, 1.0) +DEFAULT_LOGREG_C_GRID = (0.01, 0.1, 1.0, 10.0) + + +@dataclass +class ModelScore: + """Cross-validated score for one model.""" + + name: str + accuracy_mean: float + accuracy_std: float + fold_accuracies: list[float] + wall_time_s: float + grid_size: int + best_params: list[dict[str, Any]] = field(default_factory=list) + hardware_circuits: int | None = None + is_quantum: bool | None = False # None marks the untuned quantum reference row + + +@dataclass +class ComparisonResult: + """Result of :func:`compare_to_classical`.""" + + scores: list[ModelScore] + n_samples: int + n_features: int + cv: int + seed: int + p_value_vs_best_classical: float | None = None + delta_vs_best_classical: float | None = None + reference: str = ARXIV_REFERENCE + + @property + def quantum(self) -> ModelScore: + return next(s for s in self.scores if s.is_quantum is True) + + @property + def best_classical(self) -> ModelScore: + classical = [s for s in self.scores if s.is_quantum is False] + return max(classical, key=lambda s: s.accuracy_mean) + + @property + def verdict(self) -> str: + """Plain-language verdict at the 5% level (corrected resampled t-test).""" + if self.p_value_vs_best_classical is None or np.isnan(self.p_value_vs_best_classical): + return "not enough folds for a significance test" + if self.p_value_vs_best_classical >= 0.05: + return (f"no significant difference from {self.best_classical.name} " + f"(p={self.p_value_vs_best_classical:.2f})") + better = "better" if self.delta_vs_best_classical > 0 else "worse" + return (f"quantum is significantly {better} than {self.best_classical.name} " + f"(p={self.p_value_vs_best_classical:.3f})") + + def to_dict(self) -> dict[str, Any]: + d = asdict(self) + d["verdict"] = self.verdict + return d + + def table(self) -> str: + """Fixed-width text table, one row per model.""" + header = f"{'model':<34} {'accuracy':>16} {'wall time':>10} {'grid':>5} {'QPU circuits':>13}" + lines = [header, "-" * len(header)] + for s in self.scores: + acc = f"{s.accuracy_mean:.3f} +/- {s.accuracy_std:.3f}" + circ = f"{s.hardware_circuits:,}" if s.hardware_circuits is not None else "-" + lines.append(f"{s.name:<34} {acc:>16} {s.wall_time_s:>9.2f}s {s.grid_size:>5} {circ:>13}") + lines.append("-" * len(header)) + lines.append( + f"{self.n_samples} samples, {self.n_features} features, {self.cv}-fold stratified CV " + f"(identical folds for every model), seed={self.seed}" + ) + if self.delta_vs_best_classical is not None: + lines.append( + f"quantum minus best classical: {self.delta_vs_best_classical:+.3f}; {self.verdict}" + ) + lines.append(f"Protocol: {self.reference}. Quantum kernels are classically simulated.") + return "\n".join(lines) + + def __str__(self) -> str: + return self.table() + + +def corrected_paired_ttest(a: np.ndarray, b: np.ndarray, n_train: int, n_test: int) -> float: + """Two-sided p-value of the Nadeau and Bengio corrected resampled t-test. + + Plain paired t-tests over CV folds are over-confident because the training + sets overlap; the correction inflates the variance by ``n_test / n_train``. + """ + from scipy import stats + + d = np.asarray(a, dtype=float) - np.asarray(b, dtype=float) + k = len(d) + if k < 2: + return float("nan") + var = np.var(d, ddof=1) + if var == 0: + return 1.0 if np.mean(d) == 0 else 0.0 + t = np.mean(d) / np.sqrt((1.0 / k + n_test / n_train) * var) + return float(2 * stats.t.sf(abs(t), df=k - 1)) + + +def _is_kernel_classifier(clf: Any) -> bool: + backend = getattr(clf, "backend", None) + return ( + backend is not None + and hasattr(backend, "compute_kernel_matrix") + and hasattr(clf, "feature_map") + and getattr(clf, "quantum_kernel", None) is None + ) + + +def _quantum_kernel_fold(clf, X_tr, y_tr, X_te, bandwidths, C_grid, inner_cv, seed): + """Tune bandwidth and C on the training fold with a precomputed quantum kernel.""" + scaler = StandardScaler().fit(X_tr) + Xa, Xb = scaler.transform(X_tr), scaler.transform(X_te) + n_tr = len(Xa) + spec = clf.backend.create_feature_map( + n_features=X_tr.shape[1], + feature_map=clf.feature_map, + reps=getattr(clf, "feature_map_reps", 2), + ) + inner = StratifiedKFold(inner_cv, shuffle=True, random_state=seed) + best = (-np.inf, None, None, None) + for c in bandwidths: + Z = np.vstack([Xa, Xb]) * c + K = clf.backend.compute_kernel_matrix(Z, Z, feature_map=spec) + K_tr, K_te = K[:n_tr, :n_tr], K[n_tr:, :n_tr] + gs = GridSearchCV(SVC(kernel="precomputed"), {"C": list(C_grid)}, cv=inner) + gs.fit(K_tr, y_tr) + if gs.best_score_ > best[0]: + best = (gs.best_score_, c, gs.best_estimator_, K_te) + _, c, model, K_te = best + circuits = len(bandwidths) * (n_tr * (n_tr - 1) // 2 + len(Xb) * n_tr) + return model.predict(K_te), {"bandwidth": c, "C": model.C}, circuits + + +def compare_to_classical( + X: np.ndarray, + y: np.ndarray, + classifier: Any, + *, + cv: int = 5, + seed: int = 0, + inner_cv: int = 3, + bandwidth_grid: tuple[float, ...] | None = DEFAULT_BANDWIDTH_GRID, + C_grid: tuple[float, ...] = DEFAULT_C_GRID, + rbf_gamma_grid: tuple[float, ...] = DEFAULT_RBF_GAMMA_GRID, + logreg_C_grid: tuple[float, ...] = DEFAULT_LOGREG_C_GRID, + quantum_name: str | None = None, + include_untuned: bool = True, +) -> ComparisonResult: + """Compare a quantum classifier against tuned classical baselines. + + Every model sees the same ``StratifiedKFold(cv, shuffle=True, random_state=seed)`` + splits. Baselines: + + * ``SVC(kernel="rbf")`` with ``GridSearchCV`` over ``C`` and ``gamma``; + * ``LogisticRegression`` with ``GridSearchCV`` over ``C``. + + For a quantum kernel classifier (for example :class:`~superquantx.QuantumSVM`) + the bandwidth and ``C`` are tuned on a grid of the same size as the RBF grid, + using a precomputed fidelity kernel recomputed inside each fold. Pass + ``bandwidth_grid=None`` to keep the classifier's own settings and just call + ``fit``/``predict`` per fold (this is also what happens for any other + estimator with ``fit`` and ``predict``). Note that skipping the bandwidth + tuning handicaps the quantum model (arXiv:2610.42029, Sec. V.2). + + Args: + X: Feature matrix, shape (n_samples, n_features). + y: Labels. + classifier: Quantum classifier instance, refit on every fold. + cv: Number of outer folds. + seed: Seed for the fold split. + inner_cv: Folds for inner hyperparameter search. + bandwidth_grid: Quantum bandwidths tried (features are multiplied by it). + C_grid: SVM regularisation grid (quantum and RBF). + rbf_gamma_grid: RBF ``gamma`` grid. + logreg_C_grid: Logistic regression ``C`` grid. + quantum_name: Row label for the quantum model. + include_untuned: For quantum kernel classifiers, also report the same + kernel with bandwidth 1 and C 1, to show what tuning is worth. + + Returns: + ComparisonResult with per-model accuracy mean/std, wall time and a + ``table()`` for printing. + + """ + X = np.asarray(X, dtype=float) + y = np.asarray(y) + outer = StratifiedKFold(cv, shuffle=True, random_state=seed) + folds = list(outer.split(X, y)) + + tuned_kernel = bandwidth_grid is not None and _is_kernel_classifier(classifier) + backend_name = getattr(getattr(classifier, "backend", None), "__class__", type(None)).__name__ + if quantum_name is None: + quantum_name = f"{type(classifier).__name__} ({backend_name.replace('Backend', '')})" + if tuned_kernel: + quantum_name += ", tuned" + + def run(name, fit_predict, grid_size, is_quantum=False): + accs, params, circuits = [], [], 0 + start = time.perf_counter() + for tr, te in folds: + pred, p, circ = fit_predict(X[tr], y[tr], X[te]) + accs.append(float(np.mean(pred == y[te]))) + params.append(p) + circuits += circ or 0 + wall = time.perf_counter() - start + return ModelScore( + name=name, + accuracy_mean=float(np.mean(accs)), + accuracy_std=float(np.std(accs)), + fold_accuracies=accs, + wall_time_s=wall, + grid_size=grid_size, + best_params=params, + hardware_circuits=circuits if is_quantum and circuits else None, + is_quantum=is_quantum, + ) + + def quantum_fp(X_tr, y_tr, X_te): + if tuned_kernel: + return _quantum_kernel_fold( + classifier, X_tr, y_tr, X_te, bandwidth_grid, C_grid, inner_cv, seed + ) + classifier.fit(X_tr, y_tr) + n_tr = len(X_tr) + circ = n_tr * (n_tr - 1) // 2 + len(X_te) * n_tr if _is_kernel_classifier(classifier) else None + return np.asarray(classifier.predict(X_te)), {}, circ + + inner = StratifiedKFold(inner_cv, shuffle=True, random_state=seed) + + def rbf_fp(X_tr, y_tr, X_te): + gs = GridSearchCV( + make_pipeline(StandardScaler(), SVC(kernel="rbf")), + {"svc__C": list(C_grid), "svc__gamma": list(rbf_gamma_grid)}, + cv=inner, + ).fit(X_tr, y_tr) + return gs.predict(X_te), gs.best_params_, None + + def logreg_fp(X_tr, y_tr, X_te): + gs = GridSearchCV( + make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), + {"logisticregression__C": list(logreg_C_grid)}, + cv=inner, + ).fit(X_tr, y_tr) + return gs.predict(X_te), gs.best_params_, None + + def untuned_fp(X_tr, y_tr, X_te): + return _quantum_kernel_fold(classifier, X_tr, y_tr, X_te, (1.0,), (1.0,), inner_cv, seed) + + q_grid = len(bandwidth_grid) * len(C_grid) if tuned_kernel else 1 + scores = [run(quantum_name, quantum_fp, q_grid, is_quantum=True)] + if tuned_kernel and include_untuned: + untuned = run(quantum_name.replace(", tuned", ", untuned"), untuned_fp, 1) + untuned.hardware_circuits = None + scores.append(untuned) + scores += [ + run("SVC (RBF), tuned C and gamma", rbf_fp, len(C_grid) * len(rbf_gamma_grid)), + run("Logistic regression, tuned C", logreg_fp, len(logreg_C_grid)), + ] + # The untuned quantum row is a reference, not a classical baseline. + for sc in scores[1:]: + if "untuned" in sc.name and sc.name.startswith(type(classifier).__name__): + sc.is_quantum = None + + result = ComparisonResult(scores=scores, n_samples=len(X), n_features=X.shape[1], cv=cv, seed=seed) + q, best = result.quantum, result.best_classical + n_test = len(X) // cv + result.delta_vs_best_classical = q.accuracy_mean - best.accuracy_mean + result.p_value_vs_best_classical = corrected_paired_ttest( + q.fold_accuracies, best.fold_accuracies, len(X) - n_test, n_test + ) + return result diff --git a/src/superquantx/circuits.py b/src/superquantx/circuits.py index 136b59d..a829fde 100644 --- a/src/superquantx/circuits.py +++ b/src/superquantx/circuits.py @@ -39,6 +39,8 @@ def __repr__(self) -> str: qubits_str = f"q{', q'.join(map(str, self.qubits))}" return f"{self.name}{params_str} {qubits_str}" + __str__ = __repr__ + class ClassicalRegister(BaseModel): """Represents a classical register for measurements""" @@ -46,9 +48,18 @@ class ClassicalRegister(BaseModel): name: str = Field(..., description="Register name") size: int = Field(..., description="Number of classical bits") + def __init__(self, name: str | None = None, size: int | None = None, **data: Any) -> None: + if name is not None: + data["name"] = name + if size is not None: + data["size"] = size + super().__init__(**data) + def __repr__(self) -> str: return f"ClassicalRegister('{self.name}', {self.size})" + __str__ = __repr__ + class QuantumRegister(BaseModel): """Represents a quantum register""" @@ -56,9 +67,18 @@ class QuantumRegister(BaseModel): name: str = Field(..., description="Register name") size: int = Field(..., description="Number of qubits") + def __init__(self, name: str | None = None, size: int | None = None, **data: Any) -> None: + if name is not None: + data["name"] = name + if size is not None: + data["size"] = size + super().__init__(**data) + def __repr__(self) -> str: return f"QuantumRegister('{self.name}', {self.size})" + __str__ = __repr__ + class QuantumCircuit: """Quantum circuit representation with gate operations and measurements diff --git a/src/superquantx/cli/commands.py b/src/superquantx/cli/commands.py index 387eabb..6bba9fc 100644 --- a/src/superquantx/cli/commands.py +++ b/src/superquantx/cli/commands.py @@ -25,7 +25,7 @@ def info(): click.echo(f"Installation path: {sqx.__file__}") # Backend information - click.echo("\\nAvailable Backends:") + click.echo("\nInstalled backend SDKs (run list-backends to test them):") backend_info = sqx.get_backend_info() for backend_name, version in backend_info.items(): @@ -35,7 +35,7 @@ def info(): # Configuration config = sqx.config - click.echo("\\nCurrent Configuration:") + click.echo("\nCurrent Configuration:") click.echo(f" Default backend: {config.get('default_backend', 'auto')}") click.echo(f" Random seed: {config.get('random_seed', 42)}") click.echo(f" Shots: {config.get('shots', 1024)}") @@ -43,7 +43,7 @@ def info(): # Hardware info try: import psutil - click.echo("\\nSystem Resources:") + click.echo("\nSystem Resources:") click.echo(f" CPU cores: {psutil.cpu_count()}") click.echo(f" RAM: {psutil.virtual_memory().total / (1024**3):.1f} GB") except ImportError: @@ -90,7 +90,7 @@ def list_algorithms(category: str, verbose: bool): for cat in categories_to_show: if cat in algorithms: - click.echo(f"\\n{cat.title()}:") + click.echo(f"\n{cat.title()}:") for alg_name, description in algorithms[cat]: if verbose: @@ -110,51 +110,83 @@ def list_algorithms(category: str, verbose: bool): click.echo(f" โ€ข {alg_name}: {description}") +# (registry name, SDK key in get_backend_info, description) +_GATE_MODEL_BACKENDS = [ + ('simulator', None, 'Built-in NumPy statevector simulator'), + ('pennylane', 'pennylane', 'PennyLane default.qubit (local)'), + ('qiskit', 'qiskit', 'Qiskit Aer simulator (local)'), + ('cirq', 'cirq', 'Cirq simulator (local)'), + ('braket', 'braket', 'Amazon Braket LocalSimulator'), + ('tket', 'pytket', 'pytket with its local simulator'), +] +_PLANNED_BACKENDS = [ + ('azure_quantum', 'Azure Quantum'), + ('rigetti_forest', 'Rigetti Forest / pyQuil'), + ('cuquantum', 'NVIDIA cuQuantum'), + ('tensorflow_quantum', 'TensorFlow Quantum'), +] + + +def check_backend(name: str) -> tuple[bool, str]: + """Instantiate a backend and run a 2-qubit Bell circuit on it. + + Returns ``(ok, detail)``. A backend only counts as working if the Bell + circuit returns only 00 and 11. + """ + try: + kwargs = {'device': 'local:braket_sv'} if name == 'braket' else {} + backend = sqx.get_backend(name, **kwargs) + circuit = backend.create_circuit(2) + circuit = backend.add_gate(circuit, 'H', 0) + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + circuit = backend.add_measurement(circuit) + result = backend.execute_circuit(circuit, shots=200) + counts = backend.counts_big_endian(result['counts']) + bad = {k for k, v in counts.items() if v and k not in ('00', '11')} + if not counts or bad: + return False, f"Bell test gave unexpected outcomes {sorted(bad) or counts}" + return True, "Bell test passed" + except Exception as e: # noqa: BLE001 - report any failure to the user + return False, f"{type(e).__name__}: {e}".splitlines()[0][:100] + + @click.command('list-backends') @click.option( '--available-only', '-a', is_flag=True, - help='Show only installed backends' + help='Show only backends that pass the Bell test' ) def list_backends(available_only: bool): - """List quantum computing backends.""" - backends = { - 'Local Simulators': [ - ('simulator', 'SuperQuantX built-in simulator'), - ('pennylane_local', 'PennyLane local simulators'), - ('qiskit_aer', 'Qiskit Aer simulator') - ], - 'Cloud Simulators': [ - ('pennylane_cloud', 'PennyLane cloud devices'), - ('qiskit_ibm', 'IBM Quantum simulators'), - ('braket_sv1', 'AWS Braket SV1 simulator'), - ('cirq_cloud', 'Google Cirq cloud simulators') - ], - 'Quantum Hardware': [ - ('ibm_quantum', 'IBM Quantum hardware'), - ('braket_hardware', 'AWS Braket hardware access'), - ('azure_quantum', 'Azure Quantum hardware'), - ('rigetti_qcs', 'Rigetti Quantum Cloud Services') - ] - } - - backend_info = sqx.get_backend_info() + """List backends, running a real Bell-state check on each one.""" + versions = sqx.get_backend_info() click.echo("Quantum Computing Backends") click.echo("=" * 40) - - for category, backend_list in backends.items(): - click.echo(f"\\n{category}:") - - for backend_name, description in backend_list: - # Check if backend is available (simplified logic) - is_available = any(info for info in backend_info.values()) - - if available_only and not is_available: - continue - - status = "โœ“" if is_available else "โœ—" - click.echo(f" {status} {backend_name}: {description}") + click.echo("\nGate-model backends (checked with a Bell circuit):") + for name, sdk, description in _GATE_MODEL_BACKENDS: + ok, detail = check_backend(name) + if available_only and not ok: + continue + version = f" [{sdk} {versions.get(sdk)}]" if sdk and versions.get(sdk) else "" + mark = "OK " if ok else "FAIL" + click.echo(f" {mark} {name}: {description}{version}") + if not ok: + click.echo(f" {detail}") + + if not available_only: + click.echo("\nAnnealing:") + dwave = versions.get('dwave') + state = f"SDK installed ({dwave}); needs a D-Wave Leap token" if dwave \ + else "not installed (pip install 'superquantx[ocean]')" + click.echo(f" ---- ocean: D-Wave Ocean, QUBO/Ising only, {state}") + + click.echo("\nCloud hardware (reachable through the backends above, untested by CI):") + click.echo(" ---- IBM Quantum via qiskit, Amazon Braket devices via braket,") + click.echo(" Quantinuum via tket. Needs your own credentials.") + + click.echo("\nPlanned, not implemented:") + for _, description in _PLANNED_BACKENDS: + click.echo(f" ---- {description}") @click.command('run') @@ -272,7 +304,7 @@ def run_algorithm( } # Output results - click.echo("\\nResults:") + click.echo("\nResults:") click.echo(f"Accuracy: {accuracy:.4f}") click.echo(f"Training time: {training_time:.2f}s") @@ -294,92 +326,50 @@ def run_algorithm( @click.command() @click.option( - '--algorithms', '-a', - default='qsvm,qnn', - help='Comma-separated list of algorithms to benchmark' -) -@click.option( - '--datasets', '-d', - default='iris,wine', - help='Comma-separated list of datasets' + '--dataset', '-d', + type=click.Choice(['moons', 'circles', 'iris']), + default='moons', + help='Dataset (iris is reduced to its first two classes)' ) -@click.option( - '--backends', '-b', - default='simulator', - help='Comma-separated list of backends' -) -@click.option( - '--output', '-o', - type=click.Path(), - default='benchmark_results.json', - help='Output file for benchmark results' -) -@click.option( - '--runs', '-r', - default=3, - help='Number of runs for averaging' -) -def benchmark( - algorithms: str, - datasets: str, - backends: str, - output: str, - runs: int -): - """Benchmark algorithms across datasets and backends.""" - alg_list = algorithms.split(',') - dataset_list = datasets.split(',') - backend_list = backends.split(',') - - click.echo("SuperQuantX Benchmark") - click.echo("=" * 30) - click.echo(f"Algorithms: {alg_list}") - click.echo(f"Datasets: {dataset_list}") - click.echo(f"Backends: {backend_list}") - click.echo(f"Runs per combination: {runs}") - click.echo() - - results = [] - total_combinations = len(alg_list) * len(dataset_list) * len(backend_list) - current = 0 - - for algorithm in alg_list: - for dataset in dataset_list: - for backend in backend_list: - current += 1 - click.echo(f"[{current}/{total_combinations}] {algorithm} on {dataset} with {backend}") - - try: - # This would call the actual benchmark function - # For now, simulate results - result = { - 'algorithm': algorithm, - 'dataset': dataset, - 'backend': backend, - 'accuracy': np.random.uniform(0.7, 0.95), - 'execution_time': np.random.uniform(1.0, 10.0), - 'success': True - } - results.append(result) - - click.echo(f" Accuracy: {result['accuracy']:.4f}") - click.echo(f" Time: {result['execution_time']:.2f}s") - - except Exception as e: - click.echo(f" Failed: {e}") - results.append({ - 'algorithm': algorithm, - 'dataset': dataset, - 'backend': backend, - 'success': False, - 'error': str(e) - }) - - # Save results - with open(output, 'w') as f: - json.dump(results, f, indent=2) - - click.echo(f"\\nBenchmark complete. Results saved to {output}") +@click.option('--samples', '-n', default=100, help='Number of samples (moons/circles)') +@click.option('--backend', '-b', default='pennylane', help='Backend for the quantum kernel') +@click.option('--cv', default=5, help='Number of cross-validation folds') +@click.option('--seed', default=0, help='Random seed for data and folds') +@click.option('--output', '-o', type=click.Path(), help='Write the full result as JSON') +def benchmark(dataset: str, samples: int, backend: str, cv: int, seed: int, output: str | None): + """Compare a quantum kernel SVM with tuned classical baselines. + + Follows the protocol of arXiv:2610.42029: the quantum kernel bandwidth is + tuned on the same grid budget as the RBF gamma, every model sees the same + folds, and the p-value uses the Nadeau-Bengio corrected t-test. + """ + from sklearn import datasets as skd + + if dataset == 'moons': + X, y = skd.make_moons(samples, noise=0.2, random_state=seed) + elif dataset == 'circles': + X, y = skd.make_circles(samples, noise=0.1, factor=0.5, random_state=seed) + else: + X, y = skd.load_iris(return_X_y=True) + mask = y < 2 + X, y = X[mask], y[mask] + + click.echo(f"Benchmark: QuantumSVM ({backend}) vs classical on {dataset}, " + f"{len(X)} samples, {cv}-fold CV") + try: + result = sqx.compare_to_classical( + X, y, sqx.QuantumSVM(backend=backend), cv=cv, seed=seed) + except Exception as e: # noqa: BLE001 + click.echo(f"Benchmark failed: {e}", err=True) + sys.exit(1) + + click.echo(result.table()) + click.echo(f"\nVerdict: {result.verdict}") + + if output: + with open(output, 'w') as f: + json.dump(result.to_dict(), f, indent=2, default=float) + click.echo(f"Results saved to {output}") @click.command() diff --git a/src/superquantx/cli/main.py b/src/superquantx/cli/main.py index 0b8d5cc..512a140 100644 --- a/src/superquantx/cli/main.py +++ b/src/superquantx/cli/main.py @@ -9,7 +9,7 @@ import click -# Import version directly to avoid circular import +import superquantx as sqx from superquantx.version import __version__ from .commands import ( @@ -38,18 +38,17 @@ ) @click.pass_context def cli(ctx: click.Context, config: str | None, verbose: bool): - """SuperQuantX: Building the Foundation for Quantum Agentic AI + """SuperQuantX: experimental quantum machine learning toolkit. - Deploy quantum-enhanced autonomous agents and AI systems in minutes. - From quantum circuits to intelligent agents across all quantum platforms. + One API over PennyLane, Qiskit, Cirq, Braket, tket and a built-in + simulator, with classical baselines for every quantum result. + \b 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 - + superquantx -v version # versions of installed SDKs + superquantx list-backends # Bell-state check per backend + superquantx benchmark -d moons # quantum kernel vs tuned classical + superquantx run qsvm --data iris # train and score one algorithm """ # Ensure context object exists ctx.ensure_object(dict) @@ -99,10 +98,10 @@ def version(ctx: click.Context): def shell(): """Start interactive SuperQuantX shell.""" try: - import matplotlib.pyplot as plt + import matplotlib.pyplot as plt # noqa: F401 - exposed in the shell # Import common modules for convenience - import numpy as np + import numpy as np # noqa: F401 - exposed in the shell from IPython import embed banner = """ @@ -114,7 +113,7 @@ def shell(): - numpy as np - matplotlib.pyplot as plt - Try: sqx.algorithms.QuantumSVM() + Try: sqx.QuantumSVM(backend='simulator') """ embed(banner1=banner, exit_msg="Goodbye!") @@ -138,82 +137,33 @@ def examples(output: str): # Basic example basic_example = '''#!/usr/bin/env python3 -""" -Basic SuperQuantX Example: Quantum SVM Classification -""" +"""Quantum SVM on two Iris classes, checked against tuned classical baselines.""" import numpy as np -import superquantx as sqx - -# Load quantum-adapted Iris dataset -X_train, X_test, y_train, y_test, metadata = sqx.datasets.load_iris_quantum( - n_features=4, encoding='amplitude' -) - -print(f"Dataset: {metadata['dataset_name']}") -print(f"Training samples: {len(X_train)}") -print(f"Test samples: {len(X_test)}") -print(f"Features: {metadata['n_features']}") -print(f"Classes: {metadata['n_classes']}") - -# Create quantum SVM with automatic backend selection -qsvm = sqx.QuantumSVM( - backend='auto', - feature_map='ZZFeatureMap', - quantum_kernel=True -) - -# Train the model -print("\\nTraining Quantum SVM...") -qsvm.fit(X_train, y_train) +from sklearn.datasets import load_iris -# Make predictions -y_pred = qsvm.predict(X_test) +import superquantx as sqx -# Calculate accuracy -accuracy = np.mean(y_pred == y_test) -print(f"Test Accuracy: {accuracy:.4f}") +X, y = load_iris(return_X_y=True) +X, y = X[y < 2], y[y < 2] -# Visualize results -sqx.visualize_results({ - 'y_true': y_test, - 'y_pred': y_pred, - 'algorithm': 'QuantumSVM' -}, plot_type='classification') +result = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend="simulator"), cv=5) +print(result.table()) +print("Verdict:", result.verdict) ''' # VQE example vqe_example = '''#!/usr/bin/env python3 -""" -SuperQuantX VQE Example: H2 Molecule Ground State -""" - -import superquantx as sqx - -# Load H2 molecule -molecule, metadata = sqx.datasets.load_h2_molecule(bond_length=0.735) - -print(f"Molecule: {molecule.name}") -print(f"Bond length: {metadata['bond_length']} ร…") -print(f"Expected ground state energy: {metadata['ground_state_energy']} Ha") - -# Create VQE algorithm -vqe = sqx.VQE( - backend='auto', - ansatz='UCCSD', - optimizer='Adam' -) - -# Run VQE optimization -print("\\nRunning VQE optimization...") -result = vqe.compute_minimum_eigenvalue(molecule) +"""VQE for the H2 ground state (STO-3G, 0.735 Angstrom), checked against exact.""" -print(f"VQE ground state energy: {result['eigenvalue']:.6f} Ha") -print(f"Number of iterations: {result['n_iterations']}") -print(f"Optimization time: {result['optimization_time']:.2f} s") +from superquantx.algorithms import create_vqe_for_molecule -# Plot optimization history -sqx.plot_optimization_history(result) +vqe = create_vqe_for_molecule("H2", backend="simulator", seed=0) +energy = vqe.find_ground_state() +exact = vqe.exact_ground_energy() +print(f"VQE energy: {energy:.6f} Ha") +print(f"Exact energy: {exact:.6f} Ha") +print(f"Error: {abs(energy - exact):.2e} Ha") ''' # Write examples @@ -228,7 +178,7 @@ def examples(output: str): f.write(content) click.echo(f"Created: {example_path}") - click.echo(f"\\nExamples created in: {output_path}") + click.echo(f"\nExamples created in: {output_path}") click.echo("Run with: python basic_qsvm.py") @@ -242,7 +192,7 @@ def main(): try: cli() except KeyboardInterrupt: - click.echo("\\nInterrupted by user") + click.echo("\nInterrupted by user") sys.exit(130) except Exception as e: click.echo(f"Error: {e}", err=True) diff --git a/src/superquantx/config.py b/src/superquantx/config.py index 44ecdfc..418dbe4 100644 --- a/src/superquantx/config.py +++ b/src/superquantx/config.py @@ -296,19 +296,29 @@ def configure( setup_logging() def setup_logging() -> None: - """Setup logging configuration.""" - level = getattr(logging, config.get("logging.level", "INFO").upper()) - format_str = config.get("logging.format") + """Configure the ``superquantx`` package logger from the current config. + + Only the library's own logger is touched; the root logger and other + libraries' loggers (Qiskit, PennyLane, ...) are left alone. This is not + called on import: applications opt in via :func:`configure_logging` or + :func:`configure`. + """ + level = getattr(logging, str(config.get("logging.level", "WARNING")).upper()) + format_str = config.get("logging.format") or "%(asctime)s - %(name)s - %(levelname)s - %(message)s" log_file = config.get("logging.file") - # Configure root logger - logging.basicConfig( - level=level, - format=format_str, - filename=log_file, - filemode="a" if log_file else None, - force=True, - ) + pkg_logger = logging.getLogger("superquantx") + for handler in list(pkg_logger.handlers): + if getattr(handler, "_superquantx_handler", False): + pkg_logger.removeHandler(handler) + + handler: logging.Handler + handler = logging.FileHandler(log_file, mode="a") if log_file else logging.StreamHandler() + handler.setFormatter(logging.Formatter(format_str)) + handler._superquantx_handler = True # type: ignore[attr-defined] + pkg_logger.addHandler(handler) + pkg_logger.setLevel(level) + def get_platform_config(platform: str) -> dict[str, Any]: """Get configuration for a specific platform. @@ -735,5 +745,6 @@ def profile(name: str): """ return ProfileContext(name) -# Initialize logging on import -setup_logging() +# A library must not configure logging for the application: only attach a +# NullHandler so that "No handler found" warnings are avoided. +logging.getLogger("superquantx").addHandler(logging.NullHandler()) diff --git a/src/superquantx/logging_config.py b/src/superquantx/logging_config.py index fb73a21..ef51595 100644 --- a/src/superquantx/logging_config.py +++ b/src/superquantx/logging_config.py @@ -8,11 +8,15 @@ import sys import warnings from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from loguru import logger +if TYPE_CHECKING: + import loguru + + class SuperQuantXLogger: """Centralized logger for SuperQuantX with research-focused features. diff --git a/src/superquantx/measurements.py b/src/superquantx/measurements.py index 5fbeafb..ccef6ef 100644 --- a/src/superquantx/measurements.py +++ b/src/superquantx/measurements.py @@ -3,13 +3,17 @@ import json from collections import Counter, defaultdict -from typing import Any +from typing import TYPE_CHECKING, Any import matplotlib.pyplot as plt import numpy as np from pydantic import BaseModel, Field +if TYPE_CHECKING: + from .circuits import QuantumCircuit + + class MeasurementResult(BaseModel): """Represents the result of quantum measurements """ diff --git a/tests/integration/test_algorithms.py b/tests/integration/test_algorithms.py index 6d25221..76fc048 100644 --- a/tests/integration/test_algorithms.py +++ b/tests/integration/test_algorithms.py @@ -1,245 +1,123 @@ -""" -Integration tests for quantum algorithms -""" +"""End-to-end checks of the public algorithms against exact classical answers. +Every assertion compares a quantum result with something computed classically +(exact diagonalisation, brute force, or a known label set), so a silent +fallback to fake numbers would fail these tests. +""" import numpy as np import pytest -from superquantx.algorithms import ( - QAOA, - VQE, - QuantumNeuralNetwork, - create_vqe_for_molecule, -) -from superquantx.circuits import QuantumCircuit -from superquantx.gates import Hamiltonian - - -class TestVQEIntegration: - """Integration tests for VQE algorithm""" - - def test_vqe_h2_molecule(self, mock_client): - """Test VQE for H2 molecule""" - # Create simple H2 Hamiltonian - hamiltonian = Hamiltonian.from_dict({ - "ZZ": -1.0523732, - "ZI": -0.39793742, - "IZ": -0.39793742, - "XX": -0.01128010, - "YY": 0.01128010 - }) +import superquantx as sqx +from superquantx.algorithms import create_vqe_for_molecule +from superquantx.algorithms.qaoa import brute_force_maxcut, cut_value +from superquantx.algorithms.vqe import H2_STO3G_0735 +from superquantx.backends.base_backend import hamiltonian_to_matrix - def simple_ansatz(params): - circuit = QuantumCircuit(2) - circuit.ry(params[0], 0) - circuit.ry(params[1], 1) - circuit.cnot(0, 1) - return circuit - # Test without client (simulation mode) - vqe = VQE(hamiltonian, simple_ansatz, client=None) +def _backend_available(name: str) -> bool: + try: + sqx.get_backend(name) + return True + except Exception: + return False - initial_params = np.array([0.1, 0.1]) - results = vqe.run(initial_params) - assert "optimal_energy" in results - assert "optimal_parameters" in results - assert "optimization_history" in results - assert "converged" in results - assert isinstance(results["optimal_energy"], float) - assert isinstance(results["optimal_parameters"], np.ndarray) +BACKENDS = [b for b in ("simulator", "pennylane", "qiskit", "cirq") if _backend_available(b)] - def test_vqe_with_mock_client(self, mock_client): - """Test VQE with mock client""" - hamiltonian = Hamiltonian.from_dict({"ZZ": -1.0}) - - def simple_ansatz(params): - circuit = QuantumCircuit(2) - circuit.ry(params[0], 0) - return circuit - - vqe = VQE(hamiltonian, simple_ansatz, client=mock_client) - - # Mock client should return consistent results - results = vqe.run(np.array([0.1])) - - assert isinstance(results, dict) - assert mock_client.submit_job_sync.called - assert mock_client.wait_for_job_sync.called - - def test_vqe_molecule_factory(self): - """Test VQE molecule factory function""" - vqe = create_vqe_for_molecule("H2", client=None) +# 5-node graph whose maximum cut is 6. +GRAPH = np.array( + [[0, 1, 1, 0, 1], + [1, 0, 1, 1, 0], + [1, 1, 0, 1, 0], + [0, 1, 1, 0, 1], + [1, 0, 0, 1, 0]], + dtype=float, +) - assert isinstance(vqe, VQE) - assert vqe.hamiltonian.num_qubits == 2 - # Test unsupported molecule - with pytest.raises(ValueError): - create_vqe_for_molecule("unknown_molecule") +class TestVQEIntegration: + @pytest.mark.parametrize("backend", BACKENDS) + def test_vqe_single_qubit_z(self, backend): + vqe = sqx.VQE(hamiltonian={"Z": 1.0}, backend=backend, seed=0) + assert vqe.find_ground_state() == pytest.approx(-1.0, abs=1e-3) + + def test_vqe_h2_molecule_matches_exact(self): + vqe = create_vqe_for_molecule("H2", backend="simulator", seed=0) + energy = vqe.find_ground_state() + exact = vqe.exact_ground_energy() + assert exact == pytest.approx(-1.857275, abs=1e-5) + assert energy == pytest.approx(exact, abs=1.6e-3) # chemical accuracy + + def test_vqe_molecule_factory_rejects_unknown(self): + with pytest.raises(NotImplementedError): + create_vqe_for_molecule("LiH") + with pytest.raises(NotImplementedError): + create_vqe_for_molecule("H2", bond_distance=1.5) + + def test_h2_hamiltonian_spectrum(self): + H = hamiltonian_to_matrix(dict(H2_STO3G_0735), 2) + assert np.allclose(H, H.conj().T) + assert np.linalg.eigvalsh(H)[0] == pytest.approx(-1.857275, abs=1e-5) class TestQAOAIntegration: - """Integration tests for QAOA algorithm""" - - def test_qaoa_max_cut(self): - """Test QAOA for Max-Cut problem""" - # Simple triangle graph: edges (0,1), (1,2), (0,2) - from superquantx.algorithms import create_qaoa_for_max_cut - - graph_edges = [(0, 1), (1, 2), (0, 2)] - qaoa = create_qaoa_for_max_cut(graph_edges, num_nodes=3, p=1, client=None) - - assert isinstance(qaoa, QAOA) - assert qaoa.cost_hamiltonian.num_qubits == 3 - assert qaoa.p == 1 - - def test_qaoa_circuit_creation(self): - """Test QAOA circuit creation""" - cost_hamiltonian = Hamiltonian.from_dict({"ZZ": 0.5, "ZI": -0.5}) - qaoa = QAOA(cost_hamiltonian, p=2, client=None) - - # Parameters for 2 layers: [gamma1, beta1, gamma2, beta2] - parameters = np.array([0.1, 0.2, 0.3, 0.4]) - circuit = qaoa.create_qaoa_circuit(parameters) - - assert isinstance(circuit, QuantumCircuit) - assert circuit.num_qubits == 2 # From Hamiltonian - assert len(circuit.gates) > 0 # Should have gates - - # Should start with Hadamards for equal superposition - h_gates = [g for g in circuit.gates if g.name == "H"] - assert len(h_gates) == 2 # One H per qubit - - def test_qaoa_optimization(self): - """Test QAOA optimization""" - cost_hamiltonian = Hamiltonian.from_dict({"Z": 1.0}) - qaoa = QAOA(cost_hamiltonian, p=1, client=None) - - results = qaoa.run(initial_parameters=np.array([0.1, 0.2])) - - assert "optimal_energy" in results - assert "optimal_parameters" in results - assert "optimal_circuit" in results - assert "converged" in results - - optimal_circuit = results["optimal_circuit"] - assert isinstance(optimal_circuit, QuantumCircuit) - - -class TestQuantumNeuralNetworkIntegration: - """Integration tests for Quantum Neural Network""" - - def test_qnn_binary_classification(self, mock_client, quantum_feature_data): - """Test QNN for binary classification""" - X, y = quantum_feature_data - - qnn = QuantumNeuralNetwork( - num_qubits=3, - num_layers=2, - client=None # Use simulation mode - ) - - # Fit the model - qnn.fit(X, y) - - assert qnn.is_fitted_ - assert qnn.parameters is not None - assert len(qnn.parameters) == qnn.num_parameters - - # Make predictions - predictions = qnn.predict(X) - assert len(predictions) == len(y) - assert all(pred in [-1, 1] for pred in predictions) - - def test_qnn_circuit_creation(self): - """Test QNN circuit creation""" - qnn = QuantumNeuralNetwork(num_qubits=2, num_layers=1, client=None) - - parameters = np.random.uniform(0, 2*np.pi, qnn.num_parameters) - x = np.array([0.5, 1.5]) # Input data - - circuit = qnn.create_ansatz(parameters, x) - - assert isinstance(circuit, QuantumCircuit) - assert circuit.num_qubits == 2 - assert len(circuit.gates) > 0 - - def test_qnn_with_mock_client(self, mock_client, quantum_feature_data): - """Test QNN with mock client""" - X, y = quantum_feature_data - - qnn = QuantumNeuralNetwork( - num_qubits=2, - num_layers=1, - client=mock_client + def test_brute_force_reference(self): + bits, best = brute_force_maxcut(GRAPH) + assert best == 6 + assert cut_value(GRAPH, bits) == 6 + + @pytest.mark.parametrize("backend", BACKENDS) + def test_qaoa_max_cut_finds_optimum(self, backend): + result = sqx.QAOA(backend=backend, p=2, seed=7, maxiter=200).solve(GRAPH) + assert result["classical_optimum"] == 6 + assert result["cut_value"] == 6 + assert cut_value(GRAPH, np.array([int(b) for b in result["bitstring"]])) == 6 + # Expected cut of the QAOA state is below the optimum and well above random (3.5). + assert 3.5 < result["expected_cut"] <= 6 + 1e-9 + assert 0.0 < result["approximation_ratio"] <= 1.0 + + def test_qaoa_rejects_non_square(self): + with pytest.raises(ValueError, match="square adjacency"): + sqx.QAOA(backend="simulator", p=1).solve(np.ones((2, 3))) + + +class TestClassifiersIntegration: + @pytest.fixture(scope="class") + def moons(self): + from sklearn.datasets import make_moons + return make_moons(40, noise=0.1, random_state=0) + + def test_quantum_svm_fits_and_predicts(self, moons): + X, y = moons + model = sqx.QuantumSVM(backend="simulator", feature_map="ZZFeatureMap", gamma=0.5) + model.fit(X, y) + preds = model.predict(X) + assert set(np.unique(preds)) <= set(np.unique(y)) + assert np.mean(preds == y) > 0.6 # untuned bandwidth; see compare_to_classical + K = model.backend.compute_kernel_matrix(X[:5], X[:5], feature_map="ZZFeatureMap") + assert np.allclose(np.diag(K), 1.0, atol=1e-6) + + def test_quantum_nn_learns(self, moons): + X, y = moons + model = sqx.QuantumNN(backend="simulator", n_layers=2, max_epochs=15, + batch_size=40, learning_rate=0.1, seed=1) + model.fit(X, y) + assert model.loss_history[-1] < model.loss_history[0] + assert model.score(X, y) > 0.6 + + +class TestBenchmarkIntegration: + def test_compare_to_classical_reports_baselines(self): + from sklearn.datasets import make_moons + X, y = make_moons(30, noise=0.1, random_state=0) + result = sqx.compare_to_classical( + X, y, sqx.QuantumSVM(backend="simulator"), cv=3, + bandwidth_grid=(0.5,), C_grid=(1.0,), include_untuned=False, ) - - # Should work with mock client - qnn.fit(X, y) - predictions = qnn.predict(X) - - assert len(predictions) == len(y) - assert mock_client.submit_job_sync.called - - -class TestAlgorithmComposition: - """Test composition of multiple algorithms""" - - def test_vqe_then_qaoa(self): - """Test using VQE result to initialize QAOA""" - # Use same Hamiltonian for both - hamiltonian = Hamiltonian.from_dict({"ZZ": 1.0, "XX": -0.5}) - - # Run VQE first - def vqe_ansatz(params): - circuit = QuantumCircuit(2) - circuit.ry(params[0], 0) - circuit.ry(params[1], 1) - return circuit - - vqe = VQE(hamiltonian, vqe_ansatz, client=None) - vqe_results = vqe.run(np.array([0.1, 0.2])) - - # Use VQE energy as reference for QAOA - qaoa = QAOA(hamiltonian, p=1, client=None) - qaoa_results = qaoa.run(np.array([0.1, 0.2])) - - # Both should provide energy estimates - assert "optimal_energy" in vqe_results - assert "optimal_energy" in qaoa_results - - # QAOA might find better or similar solution - vqe_energy = vqe_results["optimal_energy"] - qaoa_energy = qaoa_results["optimal_energy"] - - # Both should be reasonable energy values - assert isinstance(vqe_energy, float) - assert isinstance(qaoa_energy, float) - - def test_algorithm_parameter_estimation(self): - """Test parameter counting for different algorithms""" - hamiltonian = Hamiltonian.from_dict({"ZZ": 1.0}) - - # VQE parameter estimation - def ansatz(params): - circuit = QuantumCircuit(2) - for i in range(len(params)): - circuit.ry(params[i], i % 2) - return circuit - - vqe = VQE(hamiltonian, ansatz, client=None) - estimated_params = vqe._estimate_parameter_count() - - # Should estimate based on number of qubits - assert estimated_params == 4 # 2 qubits * 2 - - # QAOA parameter count is deterministic - qaoa = QAOA(hamiltonian, p=3, client=None) - # QAOA has 2*p parameters - assert qaoa.p == 3 - - # QNN parameter count - qnn = QuantumNeuralNetwork(num_qubits=3, num_layers=2, client=None) - assert qnn.num_parameters == 3 * 2 * 3 # num_qubits * num_layers * 3 + assert result.quantum.is_quantum is True + assert result.best_classical.is_quantum is False + assert 0.0 <= result.quantum.accuracy_mean <= 1.0 + assert len(result.quantum.fold_accuracies) == 3 + assert result.p_value_vs_best_classical is not None + assert "2610.42029" in result.reference diff --git a/tests/unit/test_agents.py b/tests/unit/test_agents.py new file mode 100644 index 0000000..d5a266c --- /dev/null +++ b/tests/unit/test_agents.py @@ -0,0 +1,89 @@ +"""Agents must return real computations with classical checks, never fabricated numbers.""" + +import numpy as np +import pytest +from sklearn.datasets import make_moons + +import superquantx as sqx +from superquantx.algorithms.quantum_agents import portfolio_qubo_values + + +@pytest.fixture(scope="module") +def returns(): + rng = np.random.default_rng(3) + mu = np.array([0.010, 0.008, 0.012, 0.006]) + A = rng.normal(size=(4, 4)) * 0.01 + return rng.multivariate_normal(mu, A @ A.T + np.eye(4) * 1e-4, size=200) + + +def test_portfolio_qubo_penalises_wrong_cardinality(returns): + v = portfolio_qubo_values(returns.mean(0), np.cov(returns.T), k=2) + feasible = [i for i in range(16) if bin(i).count("1") == 2] + infeasible = [i for i in range(16) if bin(i).count("1") != 2] + assert v[feasible].min() < v[infeasible].min() + + +def test_portfolio_agent_matches_brute_force(returns): + res = sqx.QuantumPortfolioAgent(backend="simulator", n_select=2, seed=0).solve(returns) + assert res.error is None + r = res.result + assert r["feasible"] + assert r["matches_classical_optimum"] + assert r["objective"] == pytest.approx(r["classical_objective"]) + assert np.isclose(r["weights"].sum(), 1.0) + assert np.isclose(r["markowitz_reference"]["weights"].sum(), 1.0) + assert "quantum_advantage" not in r + + +def test_portfolio_agent_is_deterministic(returns): + a = sqx.QuantumPortfolioAgent(backend="simulator", n_select=2, seed=1).solve(returns).result + b = sqx.QuantumPortfolioAgent(backend="simulator", n_select=2, seed=1).solve(returns).result + assert a["selected_assets"] == b["selected_assets"] + assert a["probability_of_optimum"] == pytest.approx(b["probability_of_optimum"]) + + +def test_optimization_agent_maxcut(): + W = np.array([[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]], float) + res = sqx.QuantumOptimizationAgent(backend="simulator", seed=1).solve(W) + assert res.error is None + assert res.result["classical_optimum"] == 4.0 + assert res.result["cut_value"] <= res.result["classical_optimum"] + assert 0 < res.result["approximation_ratio"] <= 1.0 + + +def test_optimization_agent_ground_state(): + res = sqx.QuantumOptimizationAgent( + backend="simulator", problem_type="continuous", seed=0 + ).solve({"ZZ": 1.0, "XI": 0.5}) + assert res.result["ground_energy"] == pytest.approx(res.result["exact_energy"], abs=1e-4) + + +def test_classification_agent_reports_cv_against_classical(): + X, y = make_moons(n_samples=40, noise=0.2, random_state=0) + res = sqx.QuantumClassificationAgent(backend="simulator", cv=3, seed=0).solve( + (X, y), bandwidth_grid=(0.1, 1.0), C_grid=(1.0, 100.0), rbf_gamma_grid=(0.1, 1.0) + ) + r = res.result + assert 0.0 <= r["cv_accuracy"] <= 1.0 + assert "RBF" in r["best_classical"] or "Logistic" in r["best_classical"] + assert "verdict" in r + + +def test_research_agent_is_honest(): + agent = sqx.QuantumResearchAgent(backend="simulator", seed=0) + with pytest.raises(NotImplementedError): + agent.investigate("Find a room-temperature superconductor") + r = agent.simulate_ground_state().result + assert r["exact_energy"] == pytest.approx(-1.857275, abs=1e-5) + assert r["error"] < 1e-4 + + +def test_trading_agent_has_no_fabricated_numbers(returns): + agent = sqx.QuantumTradingAgent(backend="simulator", seed=0) + with pytest.raises(NotImplementedError): + agent.predict(returns) + with pytest.raises(NotImplementedError): + sqx.QuantumTradingAgent(backend="simulator", strategy="momentum").deploy(returns) + r = agent.deploy(returns).result + assert "quantum_advantage" not in r + assert "classical_objective" in r diff --git a/tests/unit/test_backends.py b/tests/unit/test_backends.py index be05347..b5f25c0 100644 --- a/tests/unit/test_backends.py +++ b/tests/unit/test_backends.py @@ -5,8 +5,6 @@ including the new AWS Braket, TKET/Quantinuum, and D-Wave Ocean backends. """ -from unittest.mock import Mock, patch - import numpy as np import pytest @@ -89,211 +87,160 @@ def test_get_backend_invalid(self): get_backend('totally_invalid_backend') -class TestBraketBackend: - """Test AWS Braket backend functionality.""" - - @pytest.fixture - def mock_braket(self): - """Mock Braket SDK components.""" - with patch('superquantx.backends.braket_backend.BRAKET_AVAILABLE', True), \ - patch('superquantx.backends.braket_backend.BraketCircuit') as mock_circuit, \ - patch('superquantx.backends.braket_backend.LocalSimulator') as mock_sim: - - mock_circuit.return_value = Mock() - mock_sim.return_value = Mock() - yield mock_circuit, mock_sim - - def test_braket_backend_creation(self, mock_braket): - """Test Braket backend creation.""" - try: - from superquantx.backends.braket_backend import BraketBackend - backend = BraketBackend(device='local:braket/braket_sv') - assert backend.device_name == 'local:braket/braket_sv' - except ImportError: - pytest.skip("Braket not available") - - def test_braket_circuit_creation(self, mock_braket): - """Test Braket circuit creation.""" - try: - from superquantx.backends.braket_backend import BraketBackend - backend = BraketBackend() - circuit = backend.create_circuit(4) - assert circuit is not None - except ImportError: - pytest.skip("Braket not available") - - def test_braket_gate_mapping(self, mock_braket): - """Test Braket gate operations.""" - try: - from superquantx.backends.braket_backend import BraketBackend - backend = BraketBackend() - circuit = backend.create_circuit(2) - - # Test basic gates - backend.add_gate(circuit, 'h', 0) - backend.add_gate(circuit, 'cnot', [0, 1]) - backend.add_gate(circuit, 'rx', 0, [np.pi/4]) - except ImportError: - pytest.skip("Braket not available") - - -class TestTKETBackend: - """Test TKET/Quantinuum backend functionality.""" +GATE_MODEL_BACKENDS = [ + ('simulator', {}), + ('qiskit', {}), + ('pennylane', {}), + ('cirq', {}), + ('braket', {'device': 'local:braket_sv'}), + ('tket', {}), +] + + +def _backend_or_skip(name, **kwargs): + try: + return get_backend(name, **kwargs) + except ImportError as exc: + pytest.skip(f"{name} not installed: {exc}") + + +@pytest.mark.parametrize("name,kwargs", GATE_MODEL_BACKENDS) +class TestGateModelBackends: + """Every gate-model backend must agree on real circuit results.""" + + def test_bell_state_counts(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + circuit = backend.create_circuit(2) + circuit = backend.add_gate(circuit, 'H', 0) + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + circuit = backend.add_measurement(circuit) + counts = backend.execute_circuit(circuit, shots=400)['counts'] + assert sum(counts.values()) == 400 + assert set(counts) <= {'00', '11'} + assert min(counts.get('00', 0), counts.get('11', 0)) > 100 + + def test_qubit_order_is_normalised(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + circuit = backend.create_circuit(3) + circuit = backend.add_gate(circuit, 'X', 0) + sv = backend.statevector_big_endian(circuit) + assert np.argmax(np.abs(sv)) == 0b100 + circuit = backend.add_measurement(circuit) + counts = backend.counts_big_endian(backend.execute_circuit(circuit, shots=20)['counts']) + assert counts == {'100': 20} + + def test_exact_expectation(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + circuit = backend.create_circuit(1) + circuit = backend.add_gate(circuit, 'RY', 0, [np.pi]) + assert backend.compute_expectation(circuit, {'Z': 1.0}) == pytest.approx(-1.0, abs=1e-6) + + def test_fidelity_kernel_matches_simulator(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + X = np.array([[0.1, 0.2], [0.5, 0.9], [1.3, -0.4]]) + K = backend.compute_kernel_matrix(X, X) + K_ref = get_backend('simulator').compute_kernel_matrix(X, X) + np.testing.assert_allclose(np.diag(K), 1.0, atol=1e-6) + np.testing.assert_allclose(K, K_ref, atol=1e-6) + + def test_kernel_uses_feature_map(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + X = np.array([[0.1, 0.2, 0.3], [0.7, -0.4, 1.1]]) + off_diag = {} + for fm in ('ZZFeatureMap', 'ZFeatureMap', 'PauliFeatureMap', 'AngleEncoding'): + K = backend.compute_kernel_matrix(X, X, feature_map=fm) + np.testing.assert_allclose(np.diag(K), 1.0, atol=1e-6) + off_diag[fm] = K[0, 1] + assert len({round(float(v), 6) for v in off_diag.values()}) == 4 + # Same map through QuantumSVM's spec path + spec = backend.create_feature_map(3, 'AngleEncoding', reps=2) + assert backend.compute_kernel_matrix(X, X, feature_map=spec)[0, 1] == pytest.approx( + off_diag['AngleEncoding'], abs=1e-6) + + def test_unknown_gate_raises(self, name, kwargs): + backend = _backend_or_skip(name, **kwargs) + circuit = backend.create_circuit(1) + with pytest.raises(ValueError): + backend.add_gate(circuit, 'NOT_A_GATE', 0) - @pytest.fixture - def mock_tket(self): - """Mock TKET components.""" - with patch('superquantx.backends.tket_backend.TKET_AVAILABLE', True), \ - patch('superquantx.backends.tket_backend.Circuit') as mock_circuit, \ - patch('superquantx.backends.tket_backend.OpType') as mock_optype: - - mock_circuit.return_value = Mock() - mock_circuit.return_value.qubits = [Mock() for _ in range(10)] - mock_circuit.return_value.bits = [Mock() for _ in range(10)] - mock_circuit.return_value.n_qubits = 4 - mock_circuit.return_value.n_bits = 0 - mock_circuit.return_value.n_gates = 5 - - yield mock_circuit, mock_optype - - def test_tket_backend_creation(self, mock_tket): - """Test TKET backend creation.""" - try: - from superquantx.backends.tket_backend import TKETBackend - backend = TKETBackend(device='aer_simulator') - assert backend.device_name == 'aer_simulator' - except ImportError: - pytest.skip("TKET not available") - def test_tket_circuit_optimization(self, mock_tket): - """Test TKET circuit optimization.""" - try: - from superquantx.backends.tket_backend import TKETBackend - backend = TKETBackend() +class TestBraketBackend: + """AWS Braket specifics (local simulator only).""" - mock_circuit = Mock() - mock_circuit.copy.return_value = mock_circuit - mock_circuit.n_gates = 10 + def test_device_name_accepts_braket_prefix(self): + pytest.importorskip("braket.circuits") + from superquantx.backends.braket_backend import BraketBackend + backend = BraketBackend(device='local:braket/braket_sv') + assert backend.device_name == 'local:braket/braket_sv' + assert backend.is_available() - # Should not crash even without real TKET - optimized = backend.optimize_circuit(mock_circuit, optimization_level=1) - assert optimized is not None - except ImportError: - pytest.skip("TKET not available") + def test_register_size_is_fixed(self): + pytest.importorskip("braket.circuits") + from superquantx.backends.braket_backend import BraketBackend + backend = BraketBackend() + circuit = backend.create_circuit(4) + backend.add_gate(circuit, 'rx', 0, [np.pi / 4]) + assert circuit.qubit_count == 4 - def test_tket_parameterized_circuits(self, mock_tket): - """Test TKET parameterized circuit creation.""" - try: - from superquantx.backends.tket_backend import TKETBackend - backend = TKETBackend() - circuit, param_names = backend.create_parameterized_circuit(4, 8) - assert len(param_names) == 8 - assert all(name.startswith('theta_') for name in param_names) - except ImportError: - pytest.skip("TKET not available") +class TestTKETBackend: + """TKET specifics.""" + + def test_rotation_angles_are_radians(self): + pytest.importorskip("pytket.extensions.qiskit") + from superquantx.backends.tket_backend import TKETBackend + backend = TKETBackend(device='aer_simulator') + circuit = backend.add_gate(backend.create_circuit(1), 'RX', 0, [np.pi]) + counts = backend.execute_circuit(circuit, shots=50)['counts'] + assert counts == {'1': 50} + + def test_circuit_optimization(self): + pytest.importorskip("pytket.extensions.qiskit") + from superquantx.backends.tket_backend import TKETBackend + backend = TKETBackend() + circuit = backend.create_circuit(2) + for _ in range(2): + backend.add_gate(circuit, 'H', 0) + optimized = backend.optimize_circuit(circuit, optimization_level=1) + assert optimized.n_gates <= circuit.n_gates class TestOceanBackend: - """Test D-Wave Ocean backend functionality.""" + """D-Wave Ocean backend (simulated annealing, no hardware).""" @pytest.fixture - def mock_ocean(self): - """Mock Ocean SDK components.""" - with patch('superquantx.backends.ocean_backend.OCEAN_AVAILABLE', True), \ - patch('superquantx.backends.ocean_backend.dimod') as mock_dimod, \ - patch('superquantx.backends.ocean_backend.SimulatedAnnealingSampler') as mock_sampler: - - # Mock BQM and sampleset - mock_bqm = Mock() - mock_dimod.BinaryQuadraticModel.from_qubo.return_value = mock_bqm - mock_dimod.BinaryQuadraticModel.from_ising.return_value = mock_bqm - - mock_sampleset = Mock() - mock_sampleset.data.return_value = [ - ({'x0': 1, 'x1': 0}, -1.0, 1), - ({'x0': 0, 'x1': 1}, -0.5, 1) - ] - mock_sampleset.__len__ = Mock(return_value=2) - mock_sampleset.info = {'timing': {}} - - mock_sampler_instance = Mock() - mock_sampler_instance.sample.return_value = mock_sampleset - mock_sampler.return_value = mock_sampler_instance - - yield mock_dimod, mock_sampler, mock_sampleset - - def test_ocean_backend_creation(self, mock_ocean): - """Test Ocean backend creation.""" - try: - from superquantx.backends.ocean_backend import OceanBackend - backend = OceanBackend(device='simulator') - assert backend.device_name == 'simulator' - assert backend._is_quantum_annealing - except ImportError: - pytest.skip("Ocean not available") - - def test_ocean_qubo_solving(self, mock_ocean): - """Test QUBO problem solving.""" - try: - from superquantx.backends.ocean_backend import OceanBackend - backend = OceanBackend() - - Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} - result = backend.solve_qubo(Q, num_reads=100) - - assert result['success'] - assert 'samples' in result - assert 'energies' in result - assert result['problem_type'] == 'QUBO' - except ImportError: - pytest.skip("Ocean not available") - - def test_ocean_ising_solving(self, mock_ocean): - """Test Ising model solving.""" - try: - from superquantx.backends.ocean_backend import OceanBackend - backend = OceanBackend() - - h = {0: -1, 1: 1} - J = {(0, 1): -1} - result = backend.solve_ising(h, J, num_reads=50) - - assert result['success'] - assert result['problem_type'] == 'Ising' - except ImportError: - pytest.skip("Ocean not available") - - def test_ocean_max_cut(self, mock_ocean): - """Test Max Cut problem solving.""" - try: - from superquantx.backends.ocean_backend import OceanBackend - backend = OceanBackend() - - # Simple graph as edge list - edges = [(0, 1), (1, 2), (2, 0)] - result = backend.solve_max_cut(edges, num_reads=100) - - assert 'samples' in result - except ImportError: - pytest.skip("Ocean not available") - - def test_ocean_circuit_compatibility(self, mock_ocean): - """Test Ocean backend circuit compatibility warnings.""" - try: - from superquantx.backends.ocean_backend import OceanBackend - backend = OceanBackend() - - # Should return placeholder - circuit = backend.create_circuit(4) - assert circuit['type'] == 'optimization_placeholder' - - # Should warn about gate operations - backend.add_gate(circuit, 'h', 0) # Should warn - result = backend.execute_circuit(circuit) # Should warn - assert not result['success'] - except ImportError: - pytest.skip("Ocean not available") + def ocean(self): + pytest.importorskip("dimod") + from superquantx.backends.ocean_backend import OceanBackend + return OceanBackend(device='simulator') + + def test_ocean_backend_creation(self, ocean): + assert ocean.device_name == 'simulator' + assert ocean._is_quantum_annealing + assert ocean.gate_model is False + + def test_ocean_qubo_solving(self, ocean): + Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} + result = ocean.solve_qubo(Q, num_reads=50) + assert result['success'] + assert result['problem_type'] == 'QUBO' + assert min(result['energies']) == pytest.approx(-1.0) + + def test_ocean_ising_solving(self, ocean): + result = ocean.solve_ising({0: -1, 1: 1}, {(0, 1): -1}, num_reads=50) + assert result['success'] + assert result['problem_type'] == 'Ising' + + def test_ocean_max_cut_finds_maximum(self, ocean): + # Square 0-1-2-3-0: maximum cut is 4 (alternate colouring) + result = ocean.solve_max_cut([(0, 1), (1, 2), (2, 3), (3, 0)], num_reads=50) + assert result['best_cut_value'] == pytest.approx(4.0) + + def test_ocean_rejects_gate_model_calls(self, ocean): + with pytest.raises(NotImplementedError, match="annealer"): + ocean.create_circuit(4) + with pytest.raises(NotImplementedError): + ocean.execute_circuit({}) class TestUnifiedAPIIntegration: diff --git a/tests/unit/test_benchmarks.py b/tests/unit/test_benchmarks.py new file mode 100644 index 0000000..504372b --- /dev/null +++ b/tests/unit/test_benchmarks.py @@ -0,0 +1,93 @@ +"""Tests for superquantx.benchmarks.compare_to_classical.""" + +import numpy as np +import pytest +from sklearn.datasets import make_moons +from sklearn.neighbors import KNeighborsClassifier + +import superquantx as sqx +from superquantx.benchmarks import ( + ComparisonResult, + compare_to_classical, + corrected_paired_ttest, +) + + +@pytest.fixture(scope="module") +def moons(): + return make_moons(n_samples=40, noise=0.2, random_state=0) + + +@pytest.fixture(scope="module") +def result(moons): + X, y = moons + return compare_to_classical( + X, y, sqx.QuantumSVM(backend="simulator"), cv=4, seed=1, + bandwidth_grid=(0.1, 1.0), C_grid=(1.0, 100.0), rbf_gamma_grid=(0.1, 1.0), + ) + + +def test_exported_from_package(): + assert sqx.compare_to_classical is compare_to_classical + + +def test_result_structure(result): + assert isinstance(result, ComparisonResult) + names = [s.name for s in result.scores] + assert names[0].startswith("QuantumSVM") + assert any("untuned" in n for n in names) + assert any("RBF" in n for n in names) + assert any("Logistic" in n for n in names) + for s in result.scores: + assert len(s.fold_accuracies) == 4 + assert 0.0 <= s.accuracy_mean <= 1.0 + assert s.accuracy_std >= 0.0 + assert s.wall_time_s > 0.0 + + +def test_equal_tuning_budget(result): + q = result.quantum + rbf = next(s for s in result.scores if "RBF" in s.name) + assert q.grid_size == rbf.grid_size == 4 + assert all(set(p) == {"bandwidth", "C"} for p in q.best_params) + assert q.hardware_circuits and q.hardware_circuits > 0 + + +def test_best_classical_excludes_quantum_rows(result): + assert result.best_classical.is_quantum is False + assert result.delta_vs_best_classical == pytest.approx( + result.quantum.accuracy_mean - result.best_classical.accuracy_mean + ) + assert 0.0 <= result.p_value_vs_best_classical <= 1.0 + + +def test_table_and_dict(result): + table = result.table() + assert "arXiv:2610.42029" in table + assert "identical folds" in table + assert str(result) == table + d = result.to_dict() + assert d["cv"] == 4 and "verdict" in d + + +def test_same_folds_are_deterministic(moons): + X, y = moons + kw = {"cv": 3, "seed": 5} + a = compare_to_classical(X, y, KNeighborsClassifier(), **kw) + b = compare_to_classical(X, y, KNeighborsClassifier(), **kw) + assert [s.fold_accuracies for s in a.scores] == [s.fold_accuracies for s in b.scores] + + +def test_generic_estimator_path(moons): + X, y = moons + r = compare_to_classical(X, y, KNeighborsClassifier(), cv=3, quantum_name="kNN") + assert r.quantum.name == "kNN" + assert r.quantum.hardware_circuits is None + assert len(r.scores) == 3 + + +def test_corrected_ttest(): + assert corrected_paired_ttest([0.9, 0.9], [0.9, 0.9], 80, 20) == 1.0 + p = corrected_paired_ttest([0.9, 0.8, 0.85, 0.95], [0.7, 0.6, 0.65, 0.7], 75, 25) + assert 0.0 < p < 0.05 + assert np.isnan(corrected_paired_ttest([0.9], [0.8], 80, 20)) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..9c70b92 --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,31 @@ +"""Smoke tests for the superquantx command line interface.""" + +from click.testing import CliRunner + +from superquantx.cli.main import cli + + +def _run(*args): + result = CliRunner().invoke(cli, list(args)) + assert result.exit_code == 0, result.output + return result.output + + +def test_version_verbose_lists_sdks(): + out = _run("-v", "version") + assert "SuperQuantX version" in out + assert "\\n" not in out + + +def test_help_uses_real_command_name(): + out = _run("--help") + assert "superquantx list-backends" in out + assert "sqx " not in out + + +def test_list_backends_checks_simulator_and_never_ticks_planned(): + out = _run("list-backends") + assert "OK simulator" in out + planned = out.split("Planned, not implemented:")[1] + assert "Azure Quantum" in planned and "Rigetti" in planned + assert "OK azure" not in out and "OK rigetti" not in out diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index a02b606..dc31cd8 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -149,7 +149,7 @@ async def test_request_with_retry(self): assert result == {"success": True} assert mock_client.request.call_count == 2 - mock_sleep.assert_called_once_with(2) # Exponential backoff + mock_sleep.assert_called_once_with(1) # Exponential backoff: 2**0 after the first failure @pytest.mark.asyncio async def test_submit_job(self): diff --git a/uv.lock b/uv.lock index c617f95..8a6a6c1 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.13'", @@ -1620,7 +1620,7 @@ wheels = [ [[package]] name = "ibm-quantum-schemas" -version = "0.11.20260824" +version = "0.13.20261016" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -1631,9 +1631,9 @@ dependencies = [ { name = "qiskit-qasm3-import" }, { name = "samplomatic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/42/cb/a20c461223a172951eeca5336fcbffd4feaecf7dddf499e14f96d3e410ec/ibm_quantum_schemas-0.11.20260824.tar.gz", hash = "sha256:8618358ba3c7d591141661bb71e075644f69d8a3b8af7fa4eb75ed50fcc59846", size = 104905, upload-time = "2026-08-24T16:21:33.985Z" } +sdist = { url = "https://files.pythonhosted.org/packages/af/e4/83d8ec84aed86b433828614eee747904b0f549822dd6363c41771631cacd/ibm_quantum_schemas-0.13.20261016.tar.gz", hash = "sha256:1d4481b0723d7b56b87e4ca6a88e47eeaaefa54a5491a1d600e40c767bbbd2e7", size = 106373, upload-time = "2026-10-16T13:33:24.933Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/47/c2/8b716171c19e3346bea8da55168b6f96002304de39a513143b8bec435b09/ibm_quantum_schemas-0.11.20260824-py3-none-any.whl", hash = "sha256:10b27916b0ffa3dff677475bb27888b32971ff86faa9c8a00d816265ab8839ae", size = 120751, upload-time = "2026-08-24T16:21:32.619Z" }, + { url = "https://files.pythonhosted.org/packages/ac/fb/02f6739f78510819aa6a561ee699456424312adf7b542e40bf4ac12c5949/ibm_quantum_schemas-0.13.20261016-py3-none-any.whl", hash = "sha256:5d957996e367baac8d74a3885a0bf6c3b0aefa5d943beed173a83db45619cf11", size = 122918, upload-time = "2026-10-16T13:33:23.256Z" }, ] [[package]] @@ -3729,6 +3729,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750, upload-time = "2025-09-04T14:34:20.226Z" }, ] +[[package]] +name = "pytest-asyncio" +version = "1.4.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, +] + [[package]] name = "pytest-benchmark" version = "5.1.0" @@ -3982,7 +3995,7 @@ wheels = [ [[package]] name = "qiskit" -version = "2.5.2" +version = "2.6.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "dill" }, @@ -3993,20 +4006,20 @@ dependencies = [ { name = "stevedore" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c3/b3/9e080540cf1dedc6ce36d9c346f0d1e17772fb646c09049b609271acf5a0/qiskit-2.5.2.tar.gz", hash = "sha256:cf05388c717392cff5d01be4ea9b45652c2709a5c697c174428d8863089b6247", size = 4261177, upload-time = "2026-08-13T19:08:14.183Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/fd/35b9222a244fd76a9094db134a1363837ae52af218ff9bdb7bbd570703d9/qiskit-2.6.1.tar.gz", hash = "sha256:3e915793167541b4045665230421785485d4dfd845ce5050a41bc9aa4868a906", size = 4664392, upload-time = "2026-10-22T21:34:37.36Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9c/66/92681da23c4f4502fabe16cb23c7c98d141ae1e25a2f14fdd8e351ae8ef8/qiskit-2.5.2-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:4aa7ddb0d9c1cd14298bf2fdd242646a5e0eaeebdebd2f31d5d2a018c75fa744", size = 9349327, upload-time = "2026-08-13T19:08:56.878Z" }, - { url = "https://files.pythonhosted.org/packages/60/c4/26f9f63a6954b69778b7401822e7855ed62194c959562e4ad3645e5ebfca/qiskit-2.5.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c559ee1e2a92b5ded6a130f1fd8dc4bea19a5b35e99d39180889746f12550666", size = 8740831, upload-time = "2026-08-13T19:08:04.199Z" }, - { url = "https://files.pythonhosted.org/packages/43/42/0eb83d0eefd6a1d3752db43839c327c39d67b2ef060b2b1da8fcd3424dc5/qiskit-2.5.2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2835e38af67932e592562c7b1b6b7fadd015bd1101a1320e2c5051de12508428", size = 9035471, upload-time = "2026-08-13T19:08:06.86Z" }, - { url = "https://files.pythonhosted.org/packages/e0/37/b09591e2386b0c4773d2c405ace6e89552366fc798df7f3ee72b46b26603/qiskit-2.5.2-cp310-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d7940da5ea03d638bace6f9cc47bb892502c85a9c05eebe1cbe3c0e693586109", size = 9954423, upload-time = "2026-08-13T19:08:59.707Z" }, - { url = "https://files.pythonhosted.org/packages/ed/92/404d085301365d79a06a1ae34b4292e35a510a22a32ec0b5a8e8ee1d87dd/qiskit-2.5.2-cp310-abi3-manylinux_2_28_s390x.whl", hash = "sha256:c2eab89804161dd927d25d521c6c43af1bcd17042e6b02124166d6d07a9c9cb1", size = 11160496, upload-time = "2026-08-13T19:09:02.586Z" }, - { url = "https://files.pythonhosted.org/packages/c4/32/1e411db90b68a6096275186e7fc57ea16d99355fc3b498182845dd5419ff/qiskit-2.5.2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:28fcb983e565b8f027a13ef43cda7aaeb1f1a6caf9df07408708abcf7bc0b59d", size = 9753072, upload-time = "2026-08-13T19:08:09.439Z" }, - { url = "https://files.pythonhosted.org/packages/c2/b4/61872b4ba4319c685615123739b25a3c42abc0f057c4a4889f7b3cad8c7b/qiskit-2.5.2-cp310-abi3-win_amd64.whl", hash = "sha256:d436cd45db22ea0132be815930d7c90343774756da9620dee68714968966f65e", size = 9451684, upload-time = "2026-08-13T19:08:11.872Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ae/d05f0a4fb9c06d805c03007e89c831c5b51ac856f451cae3474f4499e8a8/qiskit-2.6.1-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:11cb7dc819a4731da46f57379674797df43c598072ac9b0fa58e2fd340439fc1", size = 9644489, upload-time = "2026-10-22T21:47:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/93/0c/67174f35da5c7a46237f03db004049215d375ea3ee19591bc0a991649734/qiskit-2.6.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:1ba267eed0dde7c63f9af2278700e786a07b488286fd60eb87f40fffba0be513", size = 9055090, upload-time = "2026-10-22T21:34:28.19Z" }, + { url = "https://files.pythonhosted.org/packages/71/14/503dce4dcddde350bb01f3f367467b15d626939d7cde8344522fe33a91e9/qiskit-2.6.1-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1ede5ee12680b13ff923374ca46d4544054b8eb7f6c9c6ae31ddb56439b4c197", size = 9343817, upload-time = "2026-10-22T21:34:30.938Z" }, + { url = "https://files.pythonhosted.org/packages/ac/fe/a98356e6e5d0d15a4c3fce4d209b401bbb86520612a20996a1b3949553d5/qiskit-2.6.1-cp310-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9b782a5df1149f08144ccfa814df2d081b43307718cb45c4f05953d8bb33195a", size = 10262392, upload-time = "2026-10-22T21:47:22.284Z" }, + { url = "https://files.pythonhosted.org/packages/4e/4f/86e3bba7b4f8254d24e412cc04347e33adb980f28003a0867833b165bc1f/qiskit-2.6.1-cp310-abi3-manylinux_2_28_s390x.whl", hash = "sha256:e9f312e6c6346bd7d3624223b638661eff91a87dffa57c757bb46be7635bbdb5", size = 11867024, upload-time = "2026-10-22T21:47:24.892Z" }, + { url = "https://files.pythonhosted.org/packages/4c/36/5a51bf5d5d0d7e112c1f74b8247696ffc36d450aa3287fb7e06981f25001/qiskit-2.6.1-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c35f12552e689a8ca5216c133414cff84be6d41fe63f70494fbd31a8ccf06d34", size = 9558044, upload-time = "2026-10-22T21:34:32.9Z" }, + { url = "https://files.pythonhosted.org/packages/37/63/fb62fadba092bd565352c23c01d7c4ec721b1d311e618ccb5cd000a1419d/qiskit-2.6.1-cp310-abi3-win_amd64.whl", hash = "sha256:00209531dd1d145cd12d0fdea53852c828b2c7c91b8d92bf240dc7a508f89137", size = 9250679, upload-time = "2026-10-22T21:34:35.146Z" }, ] [[package]] name = "qiskit-aer" -version = "0.17.1" +version = "0.18.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -4016,36 +4029,48 @@ dependencies = [ { name = "qiskit" }, { name = "scipy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f7/37/40d06dab01752712a8ad903c175f282088f5d92ede2fc558e9b43622ec27/qiskit_aer-0.17.1.tar.gz", hash = "sha256:4de47d5a23e283e6cea44186002ab296212c4d837705c528818fbb6cfd28c185", size = 6551853, upload-time = "2025-06-04T12:06:02.68Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/44/59/a0b94e83d90e7d507a3e92988fc00f98ba6f481c46d606e05d3f943cb7ae/qiskit_aer-0.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3816f225891cc30a66addefed3bf86bb537a579600e6131925fa71b38ba62324", size = 2478177, upload-time = "2025-06-04T12:04:46.672Z" }, - { url = "https://files.pythonhosted.org/packages/81/70/4a176bbba854de61c478155528a606ebeece2209cde9fb5ef9009040943a/qiskit_aer-0.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:27568479515d5cb24290803149fe369dac1e3bd3e28057cba27dca38f3424db0", size = 2164648, upload-time = "2025-06-04T12:04:48.219Z" }, - { url = "https://files.pythonhosted.org/packages/12/3b/9e0a52679e591fe0feb08ab9698e0e0fe9b3c5d373a180acf6b1826aa218/qiskit_aer-0.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dda1b166f822f6846e6c5a2be3e5cd6bf6d767175cda378ef05f4acbe70a5cf5", size = 6430106, upload-time = "2025-06-04T13:27:21.648Z" }, - { url = "https://files.pythonhosted.org/packages/84/84/ac27fa6e42f4e4b839ddefe43c00ffb09a742b32f54e46a7f0e84a04f524/qiskit_aer-0.17.1-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eb1ff2fac1529a2513faf31e08311e3b908a17241d4b312a34fcdc5a965cb9b4", size = 7941548, upload-time = "2025-06-04T12:04:50.619Z" }, - { url = "https://files.pythonhosted.org/packages/40/cc/3decc08f7c67b6475298c3960a98f00f2bc72ccd959a5296059154e5432a/qiskit_aer-0.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73ac5e973946fc1c77154ec2213fafa821e748bd5dae1866bc465ba9f0617c71", size = 7891652, upload-time = "2025-06-04T12:57:49.53Z" }, - { url = "https://files.pythonhosted.org/packages/b3/44/6de695a1aaabab3baf2be7ab420bea0b1a165499a5d2f2c52e304f64628e/qiskit_aer-0.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae4db8490e9d0be1d762f97d48f239d521011ae1ce2a17eef4c37f03327daa2c", size = 12357212, upload-time = "2025-06-04T12:04:52.828Z" }, - { url = "https://files.pythonhosted.org/packages/2f/35/d4aaa5e7b6f7f8cd5331fa0f43740ee843e4e1ccff1559066c97898cdfb1/qiskit_aer-0.17.1-cp311-cp311-win32.whl", hash = "sha256:b64435e85efdf78880b0307eedf305b26a26687f8662c1a0ce2260d5919a90f0", size = 6899630, upload-time = "2025-06-04T12:04:54.968Z" }, - { url = "https://files.pythonhosted.org/packages/cb/91/19e26a9499f8536e851546e0b08ebdc1e6334f8f3709de163770ed4aabe4/qiskit_aer-0.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:adbb49c16909b52881e9d83e7cd270ebe38110210ad7c709cb91b38438bc696b", size = 9522360, upload-time = "2025-06-04T12:04:56.743Z" }, - { url = "https://files.pythonhosted.org/packages/30/04/a367bf585c02a9bb11c1928f6a148119404bf6b115733408ad232c1eeb36/qiskit_aer-0.17.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:faaa019be9cb6dede838e8533c4bd58e73e963071edf9ab2db7614d4fb01549e", size = 2478667, upload-time = "2025-06-04T12:04:59.173Z" }, - { url = "https://files.pythonhosted.org/packages/60/a3/3bb5c173f0ed9271f377e066e03cd0766f9cbe5ea7b4e81ce885bd77837b/qiskit_aer-0.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:16615593945191f361a788aad108ae2f3b698a1433b97ed8ed97b1abc754f600", size = 2166018, upload-time = "2025-06-04T12:05:00.508Z" }, - { url = "https://files.pythonhosted.org/packages/8f/1f/4dec986872172dc6330e22a3d3a76762cb7ecead0759b8168dbcd43df0bf/qiskit_aer-0.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:46589420f41e091fddda1230adb7ee293cdd59c32a70bcf0efd13d5e885760b1", size = 6432980, upload-time = "2025-06-04T13:27:23.469Z" }, - { url = "https://files.pythonhosted.org/packages/15/88/261bc5616a3c5a9f165c66e690c488ef9527bcd289cedf030015b3d9c79b/qiskit_aer-0.17.1-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a8bd3e4cbbf713bb62542b3bf1f36d3aba51db73cbcf8dd3fd31a28d4895f00d", size = 7944858, upload-time = "2025-06-04T12:05:01.975Z" }, - { url = "https://files.pythonhosted.org/packages/b9/26/4f8bc088eb5aae47dfeae02c12f1e52244af6aed2f958979ae3e206b27ec/qiskit_aer-0.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a8a64cf24d296f55c6c0d2245e07346eaae0d8f7dabcc032468910abde6f45a3", size = 7893820, upload-time = "2025-06-04T12:57:53.042Z" }, - { url = "https://files.pythonhosted.org/packages/3b/11/acd5361c2fac5d3147c646c8d9e57628ba73110c4beb7a27fb60cfecc42c/qiskit_aer-0.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4201015430d199b4512060c495f54e63dce72397b71f037a7954d2fd2761829f", size = 12353958, upload-time = "2025-06-04T12:05:03.708Z" }, - { url = "https://files.pythonhosted.org/packages/9b/f1/d4d5d8940162f96624d6c436bd8c8676dd8cd0320b8479f9af08da84a3fe/qiskit_aer-0.17.1-cp312-cp312-win32.whl", hash = "sha256:454c7b8563b26e827bd475e3095db443a331acd34d61c8e0a142c722f805e1ac", size = 6900658, upload-time = "2025-06-04T12:05:05.837Z" }, - { url = "https://files.pythonhosted.org/packages/56/98/fbd68369d23a3d2d0265ded2b64ad267b27bab7bdab6564b6df52335dc07/qiskit_aer-0.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:ea9996841f5a256a4d7e22f8c8d375f5099d1c3069b4bebfb8250ef5773412d6", size = 9524116, upload-time = "2025-06-04T12:05:07.741Z" }, - { url = "https://files.pythonhosted.org/packages/66/4b/48a9632a9bd1da013bc2284b9981cb507bf9d8e8000db48368d16bbbe691/qiskit_aer-0.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e42b44dc688650c6fc5c26488cd31569e9c0ac6a1e471f62c9ef2b806f2c6e28", size = 2478586, upload-time = "2025-06-04T12:05:10.254Z" }, - { url = "https://files.pythonhosted.org/packages/ea/f6/7b2695e51737e902d7c7369fe4f37e93871b91637161057e0f1e34138943/qiskit_aer-0.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f50eaa64c2559a50e272b0f0fb2c793fde63de222e95f51279134348a1cf50a0", size = 2166198, upload-time = "2025-06-04T12:05:11.771Z" }, - { url = "https://files.pythonhosted.org/packages/3a/eb/313087f7435d84d0d4de683226be1a890346b157e3def7dd9542412d5879/qiskit_aer-0.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4bac894b887a06a812b4a2d5f4af10e47f6fbc0d4f85c35cc79074b624eac13a", size = 6432886, upload-time = "2025-06-04T13:27:25.729Z" }, - { url = "https://files.pythonhosted.org/packages/4c/0d/7510036dd3ec271a83128b9d042481f43e106050adf2f9c7ffa6a7ae9cb2/qiskit_aer-0.17.1-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cb2f2e7a45d2904c692cf67bf6d118a7e7f6f05e3141381ac99fe182c9fa6fbc", size = 7944357, upload-time = "2025-06-04T12:05:13.222Z" }, - { url = "https://files.pythonhosted.org/packages/28/32/c538d890e1ccf2392ba8d39e430ef23c11a5c00808d69ccff03ee17df9ae/qiskit_aer-0.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf023d8394ce3241552c88086a06359a4f260af3a4a40c99be00afe3e538b252", size = 12353593, upload-time = "2025-06-04T12:05:15.359Z" }, - { url = "https://files.pythonhosted.org/packages/55/fb/d0a80540227909e3508f19d84f67e4b6edd2830822e657863e2353b5b915/qiskit_aer-0.17.1-cp313-cp313-win32.whl", hash = "sha256:491c598bae41300a37df80050b81d5097ca27060e7c4e876b853e30f056d2a07", size = 6900856, upload-time = "2025-06-04T12:05:17.451Z" }, - { url = "https://files.pythonhosted.org/packages/f6/f2/0e2260961c721ba0889e3f7fcdd69e5a7a24694b135d7ad5b6fe55e84e16/qiskit_aer-0.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:de793b75f19d762981198d6c770c991a5d4e0d32bc1768416cfa1520e28bdcf8", size = 9524145, upload-time = "2025-06-04T12:05:20.308Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/ca/b0/063a953680b9031ecb778bf27a743e9bfb2485286df37434af95d4c8701a/qiskit_aer-0.18.2.tar.gz", hash = "sha256:8df1171a0f3685d85a2e12425de7d907ee36d98e8cd749e9e853a7624037c060", size = 6553091, upload-time = "2026-10-26T20:03:25.322Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/b4/1d9979ab7515fa4cf1812e9f7190ad34db687449ed1fb6d17a213a5186ac/qiskit_aer-0.18.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:fac7088fe1067fd5d100bc61ea6a18b528a99926c49f70f6eb2fecd49d01839d", size = 2375395, upload-time = "2026-10-26T20:02:00.348Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0b/704ff8f1a2a25d9d239075a431938512bebfe5af9fa46fe5d55c27dcb325/qiskit_aer-0.18.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8a0663ab93d7564165d6393c1e08291a9c68067481abd790492ced51e6897b6f", size = 2117218, upload-time = "2026-10-26T20:02:02.954Z" }, + { url = "https://files.pythonhosted.org/packages/aa/de/dd3a96a49991eccadb155b1df6ba44b0481960bf61bfb6418b038b9d2742/qiskit_aer-0.18.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:efaf9770252e33b9c993f400ec3407c645266e8248c6fa9fe679e787c87e587b", size = 6998700, upload-time = "2026-10-26T20:02:04.867Z" }, + { url = "https://files.pythonhosted.org/packages/ee/40/541a0bc58a8d0ddbc8f072d86f9e81f434e51445b3ceaa00fabc941e3384/qiskit_aer-0.18.2-cp311-cp311-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d469ef2c7c5711b74b2d04b54c715350b76152f5623cc6036db3c91dc6ff420b", size = 10604288, upload-time = "2026-10-26T22:08:45.414Z" }, + { url = "https://files.pythonhosted.org/packages/bf/aa/3f7964e5e12944ebbfd3c533fb76d7a75747afdfd84c55f8aa2db838b8b1/qiskit_aer-0.18.2-cp311-cp311-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:014d05f6bb798d5717a5c938bc592b1ce0a7cd19ec10398ee2e761142406261a", size = 8468749, upload-time = "2026-10-26T22:32:28.736Z" }, + { url = "https://files.pythonhosted.org/packages/be/70/34b59417c1fa2ff4dbdd2de69b75d5f30f6df4a187033453349c1d616209/qiskit_aer-0.18.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2a27caeea887388eed4b14944577cbe74520c5ba332f0f7cf1e6012b272cc2d6", size = 14216863, upload-time = "2026-10-26T20:02:06.873Z" }, + { url = "https://files.pythonhosted.org/packages/3e/ae/fff0550c1e1fa01858262fcce271384271ea07511c792cd8aad572cd82ef/qiskit_aer-0.18.2-cp311-cp311-win_amd64.whl", hash = "sha256:2029706f823bf99bccb36a0e648053fb72a6f324f2f20574431b970e0542c16c", size = 9861348, upload-time = "2026-10-26T20:02:09.132Z" }, + { url = "https://files.pythonhosted.org/packages/a6/fb/4420adbc86251771254dacfe764dc96b3759fb17a6c8a2305b1a459120ab/qiskit_aer-0.18.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ffe3885a4d72083b79776d16695473f3e412115519991d5084b255d849c908a9", size = 2375506, upload-time = "2026-10-26T20:02:11.371Z" }, + { url = "https://files.pythonhosted.org/packages/b3/b4/82d3b9784ff0464f7982561b01bc8b67edb9a2adf7a36169e0386647bdd2/qiskit_aer-0.18.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:617f8c35a06c86e12ebd85df261c34ec8f5265ebd622757486fbe390063f89b1", size = 2118008, upload-time = "2026-10-26T20:02:13.188Z" }, + { url = "https://files.pythonhosted.org/packages/63/fd/67027adc4915f027edf9836c45318599275530bea15df426944bd0e79aa1/qiskit_aer-0.18.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bfc0ce3ed51b00d9d7c2675e4a3021127ad57aab0836f72c2a5e4f9549db5084", size = 7001773, upload-time = "2026-10-26T20:02:14.877Z" }, + { url = "https://files.pythonhosted.org/packages/25/89/670426a65fb202dfb8c9f8c04afe6d7117b29c8d1ff7d60e90407ddd0318/qiskit_aer-0.18.2-cp312-cp312-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:741b44d6b80a5806955221a524ea2ee1b6e23b6ce979a765a878a0dcf880cf51", size = 10607411, upload-time = "2026-10-26T22:08:48.293Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f1/0d03fb2af19cbfaaa4b0004c32c22726259c568bad75bc601c2970ff1728/qiskit_aer-0.18.2-cp312-cp312-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:cc5da3dc8f4f7a93f0caa5611317264c86fa42dbb74787286b81988a34917fb1", size = 8475723, upload-time = "2026-10-26T22:32:31.506Z" }, + { url = "https://files.pythonhosted.org/packages/ac/d1/984ecebc53d7d3ba7c3bd9d392be046520e16966ed88890eff4e32af76a4/qiskit_aer-0.18.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0c010f3829b925e6cb77a1856d099b742b2dbfea517f9b0422eef9247f884b49", size = 14220648, upload-time = "2026-10-26T20:02:17.07Z" }, + { url = "https://files.pythonhosted.org/packages/cf/67/fba68153279a5d932df3b2ef021c1500d1758d4fe84f3980e1291fa11ca6/qiskit_aer-0.18.2-cp312-cp312-win_amd64.whl", hash = "sha256:f5628ab71b791a634a61fac4ec6d51347111ad6e45ffb174db25e2b9afe4080d", size = 9859552, upload-time = "2026-10-26T20:02:19.164Z" }, + { url = "https://files.pythonhosted.org/packages/6f/87/c46e75b5d0fb216487a41cd08c6e8d1134d1a142bae09dd6f1d1db7cd256/qiskit_aer-0.18.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ccaf87ab7f6bd956c4e96da0e84b3509ca31ad755727cd1538953b3cf0ebddb", size = 2375587, upload-time = "2026-10-26T20:02:21.782Z" }, + { url = "https://files.pythonhosted.org/packages/16/83/2846a21e52075935229010952cd543e5d02cccec092281e6bc67af0efc25/qiskit_aer-0.18.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:40aa9bcbae38afaa8f01c4793eee771183f0f9f9349ec4ad796f1f032f254802", size = 2118056, upload-time = "2026-10-26T20:02:23.976Z" }, + { url = "https://files.pythonhosted.org/packages/c8/dc/b64bc2320e678b56ec9b5d29b4ad7293d8bd88d2f66f210e5a65f65f1063/qiskit_aer-0.18.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:562d1fdfb89587491711c467b009d8f106a21d13caa40daae40d50d632266c4e", size = 7001941, upload-time = "2026-10-26T20:02:25.482Z" }, + { url = "https://files.pythonhosted.org/packages/28/7a/b3cac4d9136e2d3bc2ffd07834a1ff250fae67fe6577c38a5a85565f4cb9/qiskit_aer-0.18.2-cp313-cp313-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e009515fbde3e163cadd76ba062ae9688f98593097d8c2560600e3e2a72d33d0", size = 10607679, upload-time = "2026-10-26T22:08:50.779Z" }, + { url = "https://files.pythonhosted.org/packages/81/8f/334c9d535f27f87ad9ed1e341a5acd77378450dea2755818b95cb4f37782/qiskit_aer-0.18.2-cp313-cp313-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:120a0c495cb62cc8c9cf38a7d039c580e732e1bbb1cce6ad7aa5618f81b46523", size = 8475786, upload-time = "2026-10-26T22:32:33.907Z" }, + { url = "https://files.pythonhosted.org/packages/0e/25/a9cc269ee701fdeb63842e70fed3fc34a7c77ade8429e5a279abe5a9fcd6/qiskit_aer-0.18.2-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f6285f8214cdd53526fd0d33ff8f7855f7d87d98f57c3c6417cf87d29e542f9", size = 14220695, upload-time = "2026-10-26T20:02:27.24Z" }, + { url = "https://files.pythonhosted.org/packages/82/aa/a73295980ab5a86fa9153b19a31679b7ca232380ea84f6679b444ef14ff7/qiskit_aer-0.18.2-cp313-cp313-win_amd64.whl", hash = "sha256:0a39528b9583c0e902ef322d37cb0cdf0a3ccb8956b615258f47f3fba8e27ea4", size = 9859545, upload-time = "2026-10-26T20:02:29.475Z" }, + { url = "https://files.pythonhosted.org/packages/3d/64/802c5231ec03edcaffcc78c2b867c9d2381b4bf8347d4767118d82d94345/qiskit_aer-0.18.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d471d1540f003382c0a9a6a81db3a0cec228c40fb425684d4c613e14d1238f0b", size = 2376620, upload-time = "2026-10-26T20:02:31.589Z" }, + { url = "https://files.pythonhosted.org/packages/58/b8/8921149139f449e42be77939a34de1090aca7071aa1f3d3dd75f02c586e9/qiskit_aer-0.18.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:df3ef546a9c289d1ce33463c14dfad45af0a5a32d375a309c19cabc30e0447cc", size = 2118360, upload-time = "2026-10-26T20:02:33.095Z" }, + { url = "https://files.pythonhosted.org/packages/2b/8e/599379c3f7025de5b7060b21eca29820ed99b1f71e9ee928ed6bc66178a4/qiskit_aer-0.18.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7b17daa83b0ab5e5d75660e0cd6007485bf28f8a88fd78d70a40dcbe208fa71a", size = 7003132, upload-time = "2026-10-26T20:02:34.757Z" }, + { url = "https://files.pythonhosted.org/packages/b3/03/9896702ea89cbef51057f2d8a8ed095a5722a0667a4444d5e75b82162029/qiskit_aer-0.18.2-cp314-cp314-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ff5919f174399dd296a18ae0ae43d545f894c714135c8a2f2ded887476b97162", size = 10609043, upload-time = "2026-10-26T22:08:53.709Z" }, + { url = "https://files.pythonhosted.org/packages/29/3e/bb503761383b84975183d0b64f89782be5d6322368c8a7978470c9f3dcc0/qiskit_aer-0.18.2-cp314-cp314-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:26713c8a65d9b4db5ab22e0e52898a7bed5ef2b04b1db012e432c2c011efc09a", size = 8477582, upload-time = "2026-10-26T22:32:36.416Z" }, + { url = "https://files.pythonhosted.org/packages/8a/37/057caca69d0524fb6587c7cee877f8b93b2cfba20d3a3fc8d7c09a36b48f/qiskit_aer-0.18.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:956d1b6bc307b7e7aaff1a61654303bd755ca737f6c6293f746fee73219638d2", size = 14220634, upload-time = "2026-10-26T20:02:36.576Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d1/fab0dbae6faf1fd99de09b98b5c789ef3f719cfdf8664b123282abd79022/qiskit_aer-0.18.2-cp314-cp314-win_amd64.whl", hash = "sha256:c8c2aef71c04f49377b3159d332d306a6d6e85b6a2dd7a4831e8cca01cfcd8c0", size = 10006912, upload-time = "2026-10-26T20:02:38.827Z" }, + { url = "https://files.pythonhosted.org/packages/3c/93/df10a85210ffa7c5df9163facfb91abafb55afdb8582d7468947d3fc86e9/qiskit_aer-0.18.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:be5c5ad4d381653bdc4ab0f4e84c5347c4ee12683d7662dea612e4b04b32a710", size = 2376623, upload-time = "2026-10-26T20:02:41.278Z" }, + { url = "https://files.pythonhosted.org/packages/1d/38/485741a48adda02b511095f7d2b09b5d5d11f188743596659efb6bcaa92a/qiskit_aer-0.18.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:f21a15e7409c729bdcd79fe16e9d7e2e8f2460702bb8929de2a0b75657c14bac", size = 2118357, upload-time = "2026-10-26T20:02:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/a9/e2/9c5aab519161698e9a75374b0d3d900796a6301fa45b54f8f0cba9531693/qiskit_aer-0.18.2-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57201e4731c63a83af9164870dd1173b42da61bfa80cf7b4122821b4c81faea9", size = 7003133, upload-time = "2026-10-26T20:02:44.52Z" }, + { url = "https://files.pythonhosted.org/packages/61/21/953f829c518cf646c96c3fbc5d2ee08221032b4a87eb4f7bf020c1d85384/qiskit_aer-0.18.2-cp315-cp315-manylinux_2_27_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:54a8d60c416b10032c6f21f88051466f859c60adf0663fec7deef6f474807dbb", size = 10609042, upload-time = "2026-10-26T22:08:56.429Z" }, + { url = "https://files.pythonhosted.org/packages/30/42/27630b76d91d743a8c6531b3a455662ca8e703ffed7ac0d223248aa4285c/qiskit_aer-0.18.2-cp315-cp315-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0b75628349dfc1eb745d392b63b9001248d045bc42a97112235c2194cd42c620", size = 8477585, upload-time = "2026-10-26T22:32:39.315Z" }, + { url = "https://files.pythonhosted.org/packages/df/b3/5372633d9d176a781426529ad4d86780fa1ee4e85fdb5878455afc4c96dc/qiskit_aer-0.18.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eacd82b70dbad3963f44e50db2d9075d7c89b3ecb879626211413af4a261c496", size = 14220637, upload-time = "2026-10-26T20:02:46.339Z" }, + { url = "https://files.pythonhosted.org/packages/78/40/34ef29b60b0c2bb270a5b3dc195f4f1c7f420aa6785ada922007ecc3fedb/qiskit_aer-0.18.2-cp315-cp315-win_amd64.whl", hash = "sha256:5932c0c15fbb6ac2451d8773e1426e21f03d7c9b0086c3d49fb4f7b9d8903eb8", size = 10006913, upload-time = "2026-10-26T20:02:48.539Z" }, ] [[package]] name = "qiskit-ibm-runtime" -version = "0.49.0" +version = "0.51.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ibm-platform-services" }, @@ -4056,15 +4081,32 @@ dependencies = [ { name = "pydantic" }, { name = "python-dateutil" }, { name = "qiskit" }, + { name = "qiskit-mitigation" }, { name = "requests" }, { name = "requests-ntlm" }, { name = "samplomatic" }, { name = "scipy" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5b/ef/b6845813b5d45da702a6ef06a67cb7a236b11a8b9a440339c8ac7b28c499/qiskit_ibm_runtime-0.49.0.tar.gz", hash = "sha256:f300eec48784afc5ce4be2691f1bd63ba7905ae4c0702c822e699376aa39432c", size = 2107733, upload-time = "2026-08-10T16:43:43.929Z" } +sdist = { url = "https://files.pythonhosted.org/packages/dd/33/a6ff6aad92fef92a733f376204083f0cb6b1e0dadddf8ed85d7e63168f62/qiskit_ibm_runtime-0.51.0.tar.gz", hash = "sha256:8873224137d4eb0e2187813252bc5e84ce73dfce7f17c954d25d51c74a6b4827", size = 3690046, upload-time = "2026-10-22T19:07:39.43Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/c5/7c14b2f83b526aa9fb2df8802b631853fb7ad5a644f19cb1e5e6c1f5bcd7/qiskit_ibm_runtime-0.51.0-py3-none-any.whl", hash = "sha256:eb3fd3dbf09e7a066106fc557bb4beb8a3cbf3cbc40623c8e9647db00ed7c28c", size = 1989560, upload-time = "2026-10-22T19:07:37.448Z" }, +] + +[[package]] +name = "qiskit-mitigation" +version = "0.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "qiskit" }, + { name = "samplomatic" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5b/67/efd5d910918201d1e846ff4cf906acb961b7e38b4dd308ccd06f14dabd94/qiskit_mitigation-0.1.1.tar.gz", hash = "sha256:d527ed3e5a511720394812d628163e19f67e916434e01beb96caf76b34d12ad8", size = 1839761, upload-time = "2026-09-24T17:52:33.782Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/32/c8a84aa1ca3308f7c04b660586341df7a6959d7730073abda0ff1c8d4a21/qiskit_ibm_runtime-0.49.0-py3-none-any.whl", hash = "sha256:b29b4a0a5e013b6e6fd6556158fd34a05e2930dea870c60edef738b834977f2b", size = 2001333, upload-time = "2026-08-10T16:43:42.283Z" }, + { url = "https://files.pythonhosted.org/packages/5c/92/70f86bedb10f6dbb00e1f018b1b10538a7614bfd5830bc585a57cddca7f4/qiskit_mitigation-0.1.1-py3-none-any.whl", hash = "sha256:a99c9a9b67a734675ff1f3a1cefdefe06507761b8771e87b1d10fcc9a812f7b0", size = 113312, upload-time = "2026-09-24T17:52:31.338Z" }, ] [[package]] @@ -4653,6 +4695,7 @@ dev = [ { name = "mypy" }, { name = "pre-commit" }, { name = "pytest" }, + { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, { name = "pytest-cov" }, { name = "pytest-mock" }, @@ -4685,6 +4728,7 @@ full-dev = [ { name = "pennylane-lightning" }, { name = "pre-commit" }, { name = "pytest" }, + { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, { name = "pytest-cov" }, { name = "pytest-mock" }, @@ -4764,6 +4808,8 @@ requires-dist = [ { name = "pydantic", specifier = ">=2.5.0" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" }, { name = "pytest", marker = "extra == 'full-dev'", specifier = ">=8.0.0" }, + { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23.0" }, + { name = "pytest-asyncio", marker = "extra == 'full-dev'", specifier = ">=0.23.0" }, { name = "pytest-benchmark", marker = "extra == 'dev'", specifier = ">=4.0.0" }, { name = "pytest-benchmark", marker = "extra == 'full-dev'", specifier = ">=4.0.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.1.0" }, @@ -4779,15 +4825,15 @@ requires-dist = [ { name = "pytket-qiskit", marker = "extra == 'full-dev'", specifier = ">=0.78.0" }, { name = "pytket-qiskit", marker = "extra == 'tket'", specifier = ">=0.78.0" }, { name = "pyyaml", specifier = ">=6.0.0" }, - { name = "qiskit", marker = "extra == 'all-backends'", specifier = ">=2.0,<3" }, - { name = "qiskit", marker = "extra == 'full-dev'", specifier = ">=2.0,<3" }, - { name = "qiskit", marker = "extra == 'qiskit'", specifier = ">=2.0,<3" }, - { name = "qiskit-aer", marker = "extra == 'all-backends'", specifier = ">=0.17.0" }, - { name = "qiskit-aer", marker = "extra == 'full-dev'", specifier = ">=0.17.0" }, - { name = "qiskit-aer", marker = "extra == 'qiskit'", specifier = ">=0.17.0" }, - { name = "qiskit-ibm-runtime", marker = "extra == 'all-backends'", specifier = ">=0.49.0" }, - { name = "qiskit-ibm-runtime", marker = "extra == 'full-dev'", specifier = ">=0.49.0" }, - { name = "qiskit-ibm-runtime", marker = "extra == 'qiskit'", specifier = ">=0.49.0" }, + { name = "qiskit", marker = "extra == 'all-backends'", specifier = ">=2.6,<3" }, + { name = "qiskit", marker = "extra == 'full-dev'", specifier = ">=2.6,<3" }, + { name = "qiskit", marker = "extra == 'qiskit'", specifier = ">=2.6,<3" }, + { name = "qiskit-aer", marker = "extra == 'all-backends'", specifier = ">=0.18" }, + { name = "qiskit-aer", marker = "extra == 'full-dev'", specifier = ">=0.18" }, + { name = "qiskit-aer", marker = "extra == 'qiskit'", specifier = ">=0.18" }, + { name = "qiskit-ibm-runtime", marker = "extra == 'all-backends'", specifier = ">=0.50" }, + { name = "qiskit-ibm-runtime", marker = "extra == 'full-dev'", specifier = ">=0.50" }, + { name = "qiskit-ibm-runtime", marker = "extra == 'qiskit'", specifier = ">=0.50" }, { name = "rich", specifier = ">=13.7.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.2.0" }, { name = "ruff", marker = "extra == 'full-dev'", specifier = ">=0.2.0" },