From ec71a3917fee5a2dac57c9991eb5a6271ba9b8bb Mon Sep 17 00:00:00 2001 From: Superagentic AI <190614718+Superagentic-AI@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:03:12 +0000 Subject: [PATCH] Docs: align examples with SuperQuantX 0.3.0 APIs Rewrite stale docs and README-adjacent examples to the real 0.3.0 surface (add_gate/execute_circuit, QuantumNN, FeatureMapSpec, Ocean QUBO helpers). Add scripts/check_docs_examples.py to extract and run Python fences; mark credential-only hardware snippets with docs-check skip. mkdocs build --strict passes; 267 blocks run with 0 failures (21 skipped). --- docs/BACKENDS.md | 361 +----- docs/api/agents.md | 1073 +++-------------- docs/api/algorithms.md | 188 +-- docs/api/backends.md | 519 +-------- docs/api/circuits.md | 471 +++----- docs/api/core.md | 436 +------ docs/api/utilities.md | 703 +---------- docs/backends/braket.md | 564 +++------ docs/backends/cirq.md | 515 ++------- docs/backends/ocean.md | 1177 ++----------------- docs/backends/pennylane.md | 1541 +++---------------------- docs/backends/qiskit.md | 1157 ++++++------------- docs/backends/simulator.md | 978 ++-------------- docs/backends/tket.md | 468 ++++---- docs/design/qmes-feature-map-auto.md | 8 +- docs/development/architecture.md | 227 ++-- docs/development/contributing.md | 26 +- docs/development/standards.md | 210 ++-- docs/development/testing.md | 460 +++----- docs/getting-started/configuration.md | 12 +- docs/getting-started/first-program.md | 4 - docs/mcp.md | 20 +- docs/tutorials/basic-quantum.md | 4 - docs/tutorials/quantum-ml.md | 19 +- docs/user-guide/algorithms.md | 1146 +++++------------- docs/user-guide/overview.md | 334 +++--- scripts/check_docs_examples.py | 140 +++ 27 files changed, 2778 insertions(+), 9983 deletions(-) create mode 100644 scripts/check_docs_examples.py diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index ea6e6fd..f15d877 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -1,334 +1,87 @@ -# SuperQuantX Backend Documentation +# Backend Overview -!!! 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). +SuperQuantX 0.3.0 exposes one portable gate-model API across several frameworks, +plus a separate Ocean backend for annealing. Prefer the per-backend guides for +detail: +| Backend | Guide | Local default | Notes | +|---|---|---|---| +| Simulator | [simulator](backends/simulator.md) | always | Pure Python, fluent `circuit.h` API | +| PennyLane | [pennylane](backends/pennylane.md) | `default.qubit` | Best for variational / QML work | +| Qiskit | [qiskit](backends/qiskit.md) | Aer simulator | IBM Quantum needs credentials | +| Cirq | [cirq](backends/cirq.md) | local Cirq simulator | Google hardware needs credentials | +| Braket | [braket](backends/braket.md) | local Braket SV | AWS / IonQ / Rigetti need credentials | +| TKET | [tket](backends/tket.md) | Aer via pytket-qiskit | Quantinuum hardware needs credentials | +| Ocean | [ocean](backends/ocean.md) | simulated annealing | QUBO / Ising, not gate circuits | -## Overview - -SuperQuantX provides a unified API that works across all major quantum computing platforms. This documentation covers all supported backends and their specific features. - -## Supported Backends - -### Gate-Model Quantum Computers - -#### 1. PennyLane Backend -**Device Name**: `'pennylane'`, `'pl'`, `'penny'` -**Provider**: Xanadu Quantum Technologies -**Type**: Quantum Machine Learning focused framework +## Portable Gate-Model Pattern ```python +import numpy as np import superquantx as sqx -# Basic usage -qnn = sqx.QuantumNN(backend='pennylane', device='default.qubit') - -# With specific device -backend = sqx.get_backend('pennylane', device='lightning.qubit', shots=1000) -``` - -**Features**: -- Automatic differentiation for quantum circuits -- Extensive ML library integration -- Support for multiple hardware providers through PennyLane plugins -- Optimized for variational quantum algorithms - -**Supported Devices**: -- `default.qubit`: CPU simulator -- `lightning.qubit`: Fast C++ simulator -- `strawberryfields.fock`: Continuous-variable quantum computing -- Hardware devices via plugins (IBM, Rigetti, etc.) - -#### 2. Qiskit Backend -**Device Name**: `'qiskit'`, `'qk'`, `'ibm'` -**Provider**: IBM Quantum -**Type**: Gate-model quantum circuits - -```python -# Local simulator -qsvm = sqx.QuantumSVM(backend='qiskit', device='aer_simulator') - -# IBM hardware (requires IBM account) -backend = sqx.get_backend('qiskit', - device='ibmq_manila', # Specific IBM device - hub='ibm-q', - group='open', - project='main') -``` - -**Features**: -- Direct access to IBM Quantum Network -- Advanced noise modeling -- Quantum circuit transpilation and optimization -- Extensive gate set and circuit control - -**Supported Devices**: -- `aer_simulator`: Local quantum simulator -- `statevector_simulator`: Statevector simulation -- `ibmq_*`: IBM quantum hardware (e.g., `ibmq_manila`, `ibmq_bogota`) - -#### 3. Cirq Backend -**Device Name**: `'cirq'`, `'google'` -**Provider**: Google Quantum AI -**Type**: NISQ-focused quantum circuits - -```python -# Local simulator -qaoa = sqx.QAOA(backend='cirq', device='cirq_simulator') - -# Google hardware (requires access) -backend = sqx.get_backend('cirq', device='weber', project_id='your-project') +for name in ["simulator", "pennylane", "qiskit", "cirq", "braket", "tket"]: + backend = sqx.get_backend(name) + 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=200)["counts"] + print(name, counts) ``` -**Features**: -- Google Quantum AI hardware access -- NISQ algorithm optimization -- Advanced circuit scheduling -- Native support for Google's quantum processors - -**Supported Devices**: -- `cirq_simulator`: Local Cirq simulator -- `weber`, `rainbow`, `sycamore`: Google quantum processors (requires access) - -#### 4. AWS Braket Backend ⭐ *NEW* -**Device Name**: `'braket'`, `'aws'`, `'amazon'` -**Provider**: Amazon Web Services -**Type**: Multi-vendor quantum access - -```python -# Local simulator -backend = sqx.get_backend('braket', device='local:braket/braket_sv') - -# IonQ hardware via AWS -backend = sqx.get_backend('braket', - device='arn:aws:braket::device/qpu/ionq/ionQdevice', - s3_folder=('my-bucket', 'quantum-results')) - -# Rigetti hardware via AWS -backend = sqx.get_backend('braket', - device='arn:aws:braket::device/qpu/rigetti/Aspen-M-3') -``` - -**Features**: -- Access to multiple quantum hardware providers -- Managed simulators with high performance -- Automatic result storage in S3 -- Pay-per-use pricing model - -**Supported Devices**: -- `local:braket/braket_sv`: Local state vector simulator -- IonQ trapped-ion processors -- Rigetti superconducting processors -- D-Wave quantum annealers (via Braket) - -#### 5. TKET/Quantinuum Backend ⭐ *NEW* -**Device Name**: `'tket'`, `'quantinuum'`, `'pytket'`, `'h1'`, `'h2'` -**Provider**: Quantinuum/Cambridge Quantum Computing -**Type**: Advanced compilation + trapped-ion hardware - -```python -# Local simulator -backend = sqx.get_backend('tket', device='aer_simulator') - -# Quantinuum H1-1E hardware -backend = sqx.get_backend('quantinuum', - device='H1-1E', - api_key='your-quantinuum-key') - -# With circuit optimization -circuit = backend.create_circuit(4) -optimized = backend.optimize_circuit(circuit, optimization_level=3) -``` - -**Features**: -- Advanced quantum circuit compilation and optimization -- Direct access to Quantinuum H-Series trapped-ion systems -- Industry-leading gate fidelities -- Sophisticated error mitigation - -**Supported Devices**: -- `H1-1E`: 20-qubit trapped-ion processor -- `H1-2E`: 56-qubit trapped-ion processor -- `H2-1`: 32-qubit second-generation system -- Various simulators through TKET - -### Quantum Annealing Systems - -#### 6. D-Wave Ocean Backend ⭐ *NEW* -**Device Name**: `'ocean'`, `'dwave'`, `'annealing'` -**Provider**: D-Wave Systems -**Type**: Quantum annealing for optimization +## Selecting a Backend ```python -# Simulated annealing -backend = sqx.get_backend('ocean', device='simulator') - -# D-Wave Advantage hardware -backend = sqx.get_backend('dwave', - device='advantage', - token='your-dwave-token') - -# Solve optimization problem -Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} # QUBO formulation -result = backend.solve_qubo(Q, num_reads=1000) -``` - -**Features**: -- Quantum annealing for optimization problems -- QUBO and Ising model solving -- Hybrid classical-quantum algorithms -- Large problem sizes (5000+ variables) - -**Supported Problems**: -- Quadratic Unconstrained Binary Optimization (QUBO) -- Ising model problems -- Maximum Cut, TSP, portfolio optimization -- Constrained optimization via penalty methods - -## Backend Comparison - -| Backend | Hardware Access | Max Qubits | Specialization | Cost Model | -|---------|----------------|------------|----------------|------------| -| **PennyLane** | Multi-vendor | Varies | Quantum ML | Provider-dependent | -| **Qiskit** | IBM Quantum | 127+ | General purpose | IBM pricing | -| **Cirq** | Google Quantum | 70+ | NISQ algorithms | Google Cloud | -| **Braket** | Multi-vendor | Varies | Cloud access | AWS pay-per-use | -| **Quantinuum** | H-Series | 56 | High fidelity | Premium pricing | -| **D-Wave** | Advantage | 5000+ | Optimization | Annealing-specific | - -## Advanced Usage - -### Backend Auto-Selection -```python -# Automatically select best available backend -backend = sqx.get_backend('auto') - -# Custom preference order -for backend_name in ['quantinuum', 'braket', 'pennylane']: - try: - backend = sqx.get_backend(backend_name) - break - except ImportError: - continue -``` - -### Multi-Backend Benchmarking -```python -backends = ['pennylane', 'qiskit', 'cirq', 'braket'] -results = {} - -for backend_name in backends: - try: - qnn = sqx.QuantumNN(backend=backend_name, n_layers=2) - qnn.fit(X_train, y_train) - accuracy = qnn.score(X_test, y_test) - results[backend_name] = accuracy - except Exception as e: - results[backend_name] = f"Error: {e}" - -print("Cross-platform results:", results) -``` - -### Hardware-Specific Optimization -```python -# TKET advanced optimization -tket_backend = sqx.get_backend('tket') -circuit = tket_backend.create_circuit(4) -# ... add gates ... -optimized_circuit = tket_backend.optimize_circuit(circuit, optimization_level=3) +import superquantx as sqx -# D-Wave problem-specific solving -ocean_backend = sqx.get_backend('ocean') -# Max Cut problem -import networkx as nx -G = nx.complete_graph(4) -result = ocean_backend.solve_max_cut(G, num_reads=1000) +print(sqx.list_available_backends()) +backend = sqx.get_backend("auto") # first available gate-model backend +print(type(backend).__name__) ``` +## Hardware Access -## Backend Version Compatibility - -Declared optional-extra floors (PyPI majors verified 2026-09-04). Installs target **Python ≥3.11**. - -| Extra | Packages (declared floor) | Latest verified | Notes | -|-------|---------------------------|-----------------|-------| -| `pennylane` | `pennylane>=0.45.0`, `pennylane-lightning>=0.45.0` | 0.45.1 / 0.45.0 | Requires Python ≥3.11 | -| `qiskit` | `qiskit>=2.0,<3`, `qiskit-aer>=0.17.0`, `qiskit-ibm-runtime>=0.49.0` | 2.5.2 / 0.17.2 / 0.49.0 | Explicit Qiskit **2.x** policy (not open-ended ≥1.0) | -| `cirq` | `cirq>=1.7.0` | 1.7.0 | Requires Python ≥3.11 | -| `braket` | `amazon-braket-sdk>=1.127.0` | 1.127.0 | Requires Python ≥3.11 | -| `tket` | `pytket>=2.18.0`, `pytket-qiskit>=0.78.0` | 2.18.1 / 0.78.0 | pytket 2.x | -| `ocean` | `dwave-ocean-sdk>=9.0.0`, `dimod>=0.12.22` | 9.4.0 / 0.12.22 | Ocean 9.x | - -Core scientific stack floors stay **3.11-compatible** (NumPy/SciPy latest majors that need Python ≥3.12 are intentionally not forced). - -## Installation Requirements - -### Core Backends (Included) -- PennyLane: `pip install pennylane` -- Qiskit: `pip install qiskit` -- Cirq: `pip install cirq` - -### New Backends (Additional Install) -```bash -# AWS Braket -pip install amazon-braket-sdk boto3 - -# TKET/Quantinuum -pip install pytket pytket-quantinuum - -# D-Wave Ocean -pip install dwave-ocean-sdk dwave-system -``` +Hardware constructors accept credentials but are not exercised in CI. -### Authentication Setup +!!! note "Requires credentials" + IBM Quantum, AWS Braket QPUs, Quantinuum and D-Wave Leap all need accounts. + Snippets below are API-checked only. -#### IBM Quantum + ```python -from qiskit import IBMQ -IBMQ.save_account('your-ibm-token') -``` +import superquantx as sqx -#### AWS Braket -```bash -aws configure # Set up AWS credentials -``` +# IBM Quantum (Qiskit Runtime) +ibm = sqx.QiskitBackend(device="ibm_brisbane", shots=1024) -#### Quantinuum -```python -# API key passed directly to backend -backend = sqx.get_backend('quantinuum', api_key='your-key') -``` +# Amazon Braket QPU +braket = sqx.BraketBackend( + device="arn:aws:braket:us-east-1::device/qpu/ionq/Forte-1", + s3_folder=("my-braket-bucket", "runs"), + shots=100, +) -#### D-Wave -```python -# Set environment variable -export DWAVE_API_TOKEN='your-dwave-token' +# D-Wave Leap +ocean = sqx.OceanBackend(device="advantage", token="YOUR_DWAVE_LEAP_TOKEN") ``` -## Error Handling +There is no separate `quantinuum` backend name in 0.3.0; use `tket` locally. +Quantinuum cloud access needs `pytket-quantinuum`, which is not part of the +`superquantx[tket]` extra. -All backends include graceful error handling: +## Annealing (Ocean) ```python -# Check backend availability -available = sqx.list_available_backends() -print("Available backends:", available) +import superquantx as sqx -# Validate specific backend -compatibility = sqx.check_backend_compatibility('quantinuum') -if compatibility['compatible']: - backend = sqx.get_backend('quantinuum') -else: - print("Issue:", compatibility['reason']) +backend = sqx.get_backend("ocean", device="simulator") +Q = {(0, 0): 1, (1, 1): -2, (0, 1): 1} +result = backend.solve_qubo(Q, num_reads=200) +print(result["samples"][0], result["energies"][0]) ``` -## Research Applications - -### For SuperXLab Research -- **Cross-platform validation**: Test quantum algorithms on all major platforms -- **Hardware comparison**: Benchmark quantum advantages across different architectures -- **Quantinuum H-Series**: Direct access for trapped-ion research -- **D-Wave optimization**: Quantum annealing for complex optimization problems -- **Multi-vendor access**: AWS Braket provides access to multiple hardware types +## Further Reading -This unified backend system enables comprehensive quantum computing research across the entire landscape of available quantum hardware and simulators. \ No newline at end of file +- [User guide: backends](user-guide/backends.md) +- [API: backends](api/backends.md) diff --git a/docs/api/agents.md b/docs/api/agents.md index 3747b9d..67d017b 100644 --- a/docs/api/agents.md +++ b/docs/api/agents.md @@ -1,1015 +1,304 @@ # 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). +Quantum agents bundle one or more SuperQuantX algorithms behind a task-level interface. Every agent reports a classical baseline next to the quantum answer, computed in the same call, so you can see how the quantum result compares. - -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. +All examples on this page run on SuperQuantX 0.3.0 with the built-in simulator. ## Overview -Quantum agents are specialized combinations of quantum algorithms designed for specific problem domains. They provide high-level interfaces for complex quantum machine learning workflows and autonomous decision-making. - -### Agent Types +| Agent | What it does | Classical check | +|---|---|---| +| [QuantumPortfolioAgent](#quantumportfolioagent) | Picks `k` of `n` assets with CVaR-VQE on a mean-variance QUBO | Brute-force optimum and a Markowitz solution | +| [QuantumOptimizationAgent](#quantumoptimizationagent) | Weighted MaxCut with QAOA, or a ground state with VQE | Brute force or exact diagonalisation | +| [QuantumClassificationAgent](#quantumclassificationagent) | Trains quantum classifiers, optionally as an ensemble | Tuned RBF SVM and logistic regression on the same folds | +| [QuantumTradingAgent](#quantumtradingagent) | Experimental: portfolio selection only | Same as the portfolio agent | +| [QuantumResearchAgent](#quantumresearchagent) | Experimental: VQE ground-state simulation only | Exact diagonalisation | -- **[QuantumTradingAgent](#quantumtradingagent)**: Autonomous financial trading with quantum advantages -- **[QuantumResearchAgent](#quantumresearchagent)**: Scientific discovery and hypothesis generation -- **[QuantumOptimizationAgent](#quantumoptimizationagent)**: General combinatorial and continuous optimization -- **[QuantumClassificationAgent](#quantumclassificationagent)**: Automated ML with ensemble methods -- **[QuantumPortfolioAgent](#quantumportfolioagent)**: Portfolio optimization and risk management +Agents do not report a "quantum advantage" figure. Features that are not implemented raise `NotImplementedError` instead of returning placeholder output. -## Base Classes +## Base class ### QuantumAgent -Base class for all quantum agents providing common functionality. - ```python from superquantx.algorithms.quantum_agents import QuantumAgent + class MyQuantumAgent(QuantumAgent): def _initialize_agent(self): - # Initialize agent-specific algorithms + # Create the algorithms this agent uses and store them in self.algorithms pass - + def solve(self, problem_instance, **kwargs): - # Implement problem-solving logic + # Return a QuantumResult, for example via self._result(result_dict, start_time) pass -``` - -#### Constructor - -##### __init__(backend, agent_config=None, shots=1024, **kwargs) - -**Parameters:** -- `backend` (str|Backend): Quantum backend for circuit execution -- `agent_config` (dict, optional): Configuration dictionary for the agent -- `shots` (int): Number of measurement shots (default: 1024) -- `**kwargs`: Additional parameters - -#### Methods - -##### _initialize_agent() - -Abstract method to initialize agent-specific algorithms and configurations. - -**Must be implemented by subclasses.** - -##### solve(problem_instance, **kwargs) - -Abstract method to solve a problem using the quantum agent. -**Parameters:** -- `problem_instance` (Any): Problem data or specification -- `**kwargs`: Additional solving parameters + # QuantumAgent is a BaseQuantumAlgorithm, so fit and predict are required too + def fit(self, X, y=None, **kwargs): + self.is_fitted = True + return self -**Returns:** -- `QuantumResult`: Solution result with metadata + def predict(self, X, **kwargs): + return X -##### get_agent_info() -Get information about the agent and its algorithms. - -**Returns:** -- `dict`: Agent information including algorithms, config, and performance metrics - -#### Attributes - -- `algorithms` (dict): Dictionary of initialized quantum algorithms -- `results_history` (list): History of problem-solving results -- `performance_metrics` (dict): Performance metrics for different algorithms -- `agent_config` (dict): Agent configuration parameters - -## Specialized Agents - -### QuantumTradingAgent - -Autonomous quantum trading agent for financial markets. - -```python -from superquantx import QuantumTradingAgent - -# Create trading agent -agent = QuantumTradingAgent( - backend='pennylane', - strategy='quantum_portfolio', - risk_tolerance=0.6, - markets=['stocks', 'crypto'] -) - -# Deploy agent -result = agent.deploy(market_data) -print(f"Performance: {result.result['performance']}") -print(f"Quantum advantage: {result.result['quantum_advantage']}") +agent = MyQuantumAgent(backend='simulator') +print(agent.get_agent_info()['agent_type']) ``` -#### Constructor - -##### __init__(backend='auto', strategy='quantum_portfolio', risk_tolerance=0.5, quantum_advantage_threshold=0.05, markets=None, **kwargs) - -**Parameters:** -- `backend` (str): Quantum backend ('auto' for automatic selection) -- `strategy` (str): Trading strategy type - - `'quantum_portfolio'`: Quantum portfolio optimization - - `'momentum'`: Quantum-enhanced momentum trading - - `'mean_reversion'`: Mean reversion with quantum analysis -- `risk_tolerance` (float): Risk tolerance level (0.0 to 1.0) -- `quantum_advantage_threshold` (float): Minimum quantum advantage required -- `markets` (list): Markets to trade in (['stocks', 'crypto', 'forex']) -- `**kwargs`: Additional parameters +**Constructor:** `QuantumAgent(backend, agent_config=None, shots=1024, **kwargs)` -#### Methods +- `backend` (str or backend): backend name such as `'simulator'` or a backend instance +- `agent_config` (dict, optional): configuration stored on the agent +- `shots` (int): measurement shots +- `**kwargs`: base algorithm options such as `seed` -##### deploy(market_data=None, **kwargs) +**Methods:** -Deploy the trading agent and return performance metrics. +- `_initialize_agent()`: abstract; create the agent's algorithms +- `solve(problem_instance, **kwargs)`: abstract; returns a `QuantumResult` +- `get_agent_info()`: agent type, configuration, algorithms and metrics -**Parameters:** -- `market_data` (Any, optional): Historical market data for analysis -- `**kwargs`: Deployment parameters +**Attributes:** `algorithms`, `results_history`, `performance_metrics`, `agent_config`. -**Returns:** -- `QuantumResult`: Trading performance and quantum advantage metrics +`QuantumResult` has the fields `result` (dict), `metadata` (dict), `execution_time` (seconds), `backend_info`, `error` and `intermediate_results`. -##### fit(X, y=None, **kwargs) +## QuantumPortfolioAgent -Fit the trading agent (optional for pre-configured agents). +Selects `n_select` of `n` assets with equal weights. The selection problem is encoded as a diagonal Hamiltonian; a RealAmplitudes circuit is trained to minimise the CVaR of the energy, and the best sampled selection is returned. The brute-force optimum of the same QUBO and a long-only Markowitz portfolio are computed in the same call. Practical up to about 10 assets. -**Parameters:** -- `X` (numpy.ndarray): Historical market data -- `y` (numpy.ndarray, optional): Target returns -- `**kwargs`: Fitting parameters +**Constructor:** `QuantumPortfolioAgent(backend, n_select=None, risk_aversion=1.0, reps=2, alpha=0.25, n_restarts=5, maxiter=300, **kwargs)` -**Returns:** -- `QuantumTradingAgent`: Self +- `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`, `maxiter`: optimizer restarts and iterations per restart +- `seed` (keyword): makes the run reproducible -##### predict(X, **kwargs) +**Methods:** -Predict trading decisions based on market data. - -**Parameters:** -- `X` (numpy.ndarray): Market data for prediction - -**Returns:** -- `numpy.ndarray`: Trading signals (0=hold, 1=buy, -1=sell) - -#### Strategy Types - -- **quantum_portfolio**: Uses QAOA for portfolio optimization -- **momentum**: Quantum-enhanced momentum detection -- **mean_reversion**: Quantum analysis of market reversals - -#### Example +- `fit(returns)`: estimate mean returns and covariance from a (periods x assets) matrix +- `solve(returns=None)`: run the selection; refits if returns are given +- `predict(returns=None)`: equal weights of the selected assets ```python import numpy as np -from superquantx import QuantumTradingAgent - -# Create sample market data -market_data = { - 'prices': np.random.randn(100, 10), # 100 days, 10 assets - 'returns': np.random.randn(100, 10), - 'volatility': np.random.rand(10) -} - -# Create and deploy trading agent -agent = QuantumTradingAgent( - strategy='quantum_portfolio', - risk_tolerance=0.4, - markets=['stocks'] -) - -result = agent.deploy(market_data) - -print(f"Expected Return: {result.result['performance']['expected_return']:.3f}") -print(f"Risk: {result.result['performance']['risk']:.3f}") -print(f"Sharpe Ratio: {result.result['performance']['sharpe_ratio']:.3f}") -print(f"Quantum Advantage: {result.result['quantum_advantage']:.3f}") -``` - -### QuantumResearchAgent - -Autonomous quantum research agent for scientific discovery. - -```python -from superquantx import QuantumResearchAgent - -# Create research agent -agent = QuantumResearchAgent( - domain='materials_science', - hypothesis_generation=True, - experiment_design=True -) - -# Investigate research question -result = agent.investigate( - "How can quantum simulation accelerate discovery of superconducting materials?" -) -print(result.result['research_plan']) -``` - -#### Constructor - -##### __init__(backend='auto', domain='materials_science', hypothesis_generation=True, experiment_design=True, literature_synthesis=False, **kwargs) - -**Parameters:** -- `backend` (str): Quantum backend for simulations -- `domain` (str): Research domain - - `'materials_science'`: Materials and condensed matter research - - `'drug_discovery'`: Pharmaceutical and biochemical research - - `'physics'`: Fundamental physics research -- `hypothesis_generation` (bool): Enable automated hypothesis generation -- `experiment_design` (bool): Enable quantum experiment design -- `literature_synthesis` (bool): Enable literature review and synthesis -- `**kwargs`: Additional parameters - -#### Methods - -##### investigate(research_question, constraints=None, **kwargs) - -Investigate a research question and return research plan. - -**Parameters:** -- `research_question` (str): The research question to investigate -- `constraints` (dict, optional): Research constraints (timeline, budget, etc.) -- `**kwargs`: Investigation parameters - -**Returns:** -- `QuantumResult`: Research plan, hypotheses, and experiment designs - -##### fit(X, y=None, **kwargs) - -Fit the research agent to domain-specific data. - -##### predict(X, **kwargs) - -Predict research outcomes based on data. - -#### Research Domains - -- **materials_science**: Quantum simulation of materials, electronic structure calculations -- **drug_discovery**: Molecular simulation, protein folding, drug-target interactions -- **physics**: Fundamental physics simulations, quantum many-body systems - -#### Example - -```python -from superquantx import QuantumResearchAgent - -# Create research agent for drug discovery -agent = QuantumResearchAgent( - domain='drug_discovery', - hypothesis_generation=True, - experiment_design=True -) - -# Investigate research question -research_question = "Can quantum simulation identify novel COVID-19 drug targets?" -constraints = {'timeline': '18_months', 'budget': 500000} - -result = agent.investigate(research_question, constraints) - -# Access results -research_plan = result.result['research_plan'] -hypothesis = result.result['hypothesis'] -experiments = result.result['experiments'] - -print("Research Plan Phases:", research_plan['phases']) -print("Primary Hypothesis:", hypothesis['primary_hypothesis']) -print("Number of Experiments:", len(experiments)) - -for exp in experiments: - print(f"- {exp['experiment_name']}: {exp['expected_duration']}") -``` - -### QuantumOptimizationAgent - -General-purpose quantum optimization agent. - -```python -from superquantx import QuantumOptimizationAgent - -# Create optimization agent -agent = QuantumOptimizationAgent( - backend='qiskit', - problem_type='combinatorial', - algorithms=['qaoa', 'vqe'] -) +from superquantx import QuantumPortfolioAgent -# Solve optimization problem -result = agent.solve(problem_instance) +rng = np.random.default_rng(42) +returns = rng.multivariate_normal( + mean=[0.08, 0.12, 0.10, 0.15], + cov=[[0.16, 0.05, 0.03, 0.02], + [0.05, 0.25, 0.04, 0.03], + [0.03, 0.04, 0.20, 0.05], + [0.02, 0.03, 0.05, 0.30]], + size=252, +) / 100 + +agent = QuantumPortfolioAgent(backend='simulator', n_select=2, risk_aversion=2.0, seed=0) +result = agent.solve(returns) +r = result.result + +print("Quantum selection: ", r['selected_assets'], r['weights']) +print("Brute-force selection: ", r['classical_selected_assets']) +print("Matches optimum: ", r['matches_classical_optimum']) +print(f"P(optimum) after VQE: {r['probability_of_optimum']:.3f}") +print(f"Expected return {r['expected_return']:.4f}, risk {r['risk']:.4f}") +print("Markowitz weights: ", np.round(r['markowitz_reference']['weights'], 3)) ``` -#### Constructor +Keys in `result.result`: `selected_assets`, `weights`, `objective`, `feasible`, `classical_selected_assets`, `classical_objective`, `matches_classical_optimum`, `objective_gap`, `probability_of_optimum`, `optimum_sampled`, `markowitz_reference`, `expected_return`, `risk`, `sharpe_ratio`, plus `cvar_rescaled` and `shots`. -##### __init__(backend, problem_type='combinatorial', algorithms=None, **kwargs) +!!! note "Not available in 0.3.0" + Black-Litterman or factor risk models, Sharpe or risk-parity objectives, per-asset weight limits and sector constraints are not implemented. The agent selects an equal-weight subset; use `markowitz_reference` for continuous weights. -**Parameters:** -- `backend` (str): Quantum backend -- `problem_type` (str): Type of optimization - - `'combinatorial'`: Discrete optimization (TSP, Max-Cut, etc.) - - `'continuous'`: Continuous optimization (VQE, portfolio, etc.) - - `'mixed'`: Mixed integer optimization -- `algorithms` (list): Algorithms to use (['qaoa', 'vqe']) -- `**kwargs`: Additional parameters +## QuantumOptimizationAgent -#### Methods +**Constructor:** `QuantumOptimizationAgent(backend, problem_type='combinatorial', p=2, algorithms=None, maxiter=200, n_restarts=3, reps=2, **kwargs)` -##### solve(problem_instance, **kwargs) +- `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 +- `p`: QAOA layers; `reps`: VQE ansatz repetitions -Solve optimization problem using appropriate quantum algorithm. - -**Parameters:** -- `problem_instance` (Any): Problem specification or data -- `**kwargs`: Solving parameters - -**Returns:** -- `QuantumResult`: Optimization result with solution and metadata - -##### fit(X, y=None, **kwargs) - -Fit optimization algorithms to problem characteristics. - -##### predict(X, **kwargs) - -Predict optimal solutions for new problem instances. - -#### Supported Algorithms - -- **QAOA**: Quantum Approximate Optimization Algorithm for combinatorial problems -- **VQE**: Variational Quantum Eigensolver for continuous optimization - -#### Example +### MaxCut with QAOA ```python import numpy as np from superquantx import QuantumOptimizationAgent -# Create Max-Cut problem (combinatorial) -edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] -weights = [1, 1, 1, 1, 2] - -problem = { - 'type': 'max_cut', - 'edges': edges, - 'weights': weights, - 'num_nodes': 4 -} - -# Create and use optimization agent -agent = QuantumOptimizationAgent( - problem_type='combinatorial', - algorithms=['qaoa'] -) - -result = agent.solve(problem) -print(f"Optimal solution: {result.result}") -print(f"Algorithm used: {result.metadata['algorithm_used']}") +# 4-node graph: edges (0,1), (1,2), (2,3), (3,0) with weight 1 and (0,2) with weight 2 +adjacency = np.array([ + [0, 1, 2, 1], + [1, 0, 1, 0], + [2, 1, 0, 1], + [1, 0, 1, 0], +], dtype=float) + +agent = QuantumOptimizationAgent(backend='simulator', problem_type='combinatorial', p=2, seed=0) +result = agent.solve(adjacency) + +print("Partition:", result.result['bitstring']) +print("Cut value:", result.result['cut_value'], "optimum:", result.result['classical_optimum']) +print("Approximation ratio:", round(result.result['approximation_ratio'], 3)) +print("Algorithm:", result.metadata['algorithm_used']) ``` -### QuantumClassificationAgent - -Ensemble quantum machine learning agent for classification. +### Ground state with VQE ```python -from superquantx import QuantumClassificationAgent +from superquantx import Hamiltonian, QuantumOptimizationAgent -# Create classification agent -agent = QuantumClassificationAgent( - backend='pennylane', - algorithms=['quantum_svm', 'quantum_nn', 'hybrid'], - ensemble_method='weighted' -) +# Two-qubit transverse-field Ising model +H = Hamiltonian.ising_model(2, J=1.0, h=0.5) -# Fit and predict -agent.fit(X_train, y_train) -predictions = agent.predict(X_test) +agent = QuantumOptimizationAgent(backend='simulator', problem_type='continuous', seed=0) +result = agent.solve(H) +print(f"VQE energy {result.result['ground_energy']:.6f}, exact {result.result['exact_energy']:.6f}") ``` -#### Constructor - -##### __init__(backend, algorithms=None, ensemble_method='voting', auto_tune=False, **kwargs) - -**Parameters:** -- `backend` (str): Quantum backend -- `algorithms` (list): Algorithms to include - - `'quantum_svm'`: Quantum Support Vector Machine - - `'quantum_nn'`: Quantum Neural Network - - `'hybrid'`: Hybrid quantum-classical classifier -- `ensemble_method` (str): How to combine predictions - - `'voting'`: Majority voting - - `'weighted'`: Performance-weighted voting - - `'stacking'`: Meta-learning ensemble -- `auto_tune` (bool): Automatic hyperparameter tuning -- `**kwargs`: Additional parameters - -#### Methods - -##### fit(X, y, **kwargs) - -Train all classification algorithms and compute ensemble weights. - -**Parameters:** -- `X` (numpy.ndarray): Training features -- `y` (numpy.ndarray): Training labels -- `**kwargs`: Training parameters - -**Returns:** -- `QuantumClassificationAgent`: Self - -##### predict(X, **kwargs) - -Make ensemble predictions on new data. - -**Parameters:** -- `X` (numpy.ndarray): Test features -- `**kwargs`: Prediction parameters - -**Returns:** -- `numpy.ndarray`: Predicted labels - -##### solve(problem_instance, **kwargs) +`predict(problem)` returns the MaxCut partition as an array of 0/1, or the VQE energy. -Solve complete classification problem with performance evaluation. +## QuantumClassificationAgent -**Parameters:** -- `problem_instance` (tuple): (X, y) data tuple -- `**kwargs`: Solving parameters +**Constructor:** `QuantumClassificationAgent(backend, algorithms=None, ensemble_method='voting', cv=5, **kwargs)` -**Returns:** -- `QuantumResult`: Classification results with ensemble performance +- `algorithms`: any of `'quantum_svm'` (default), `'quantum_nn'`, `'hybrid'` (`'hybrid'` uses `HybridClassifier`, which fails in `fit` in 0.3.0; see the [algorithms guide](../user-guide/algorithms.md#hybrid-classifier)) +- `ensemble_method`: `'voting'`, `'weighted'` (weights votes by training accuracy) or `'best'` +- `cv`: folds used by `solve` -#### Ensemble Methods +**Methods:** -- **voting**: Simple majority voting among algorithms -- **weighted**: Weight votes by individual algorithm performance -- **stacking**: Train meta-learner to combine algorithm predictions +- `fit(X, y)`: train every algorithm and record its training accuracy in `performance_metrics` +- `predict(X)`: predictions from one algorithm, or the ensemble vote +- `solve((X, y))`: cross-validated benchmark of the first algorithm against classical baselines with `compare_to_classical`, then fit on all the data -#### Example +### Ensemble ```python from sklearn.datasets import make_classification from superquantx import QuantumClassificationAgent -# Generate dataset -X, y = make_classification(n_samples=200, n_features=8, n_classes=2, random_state=42) -X_train, X_test = X[:160], X[160:] -y_train, y_test = y[:160], y[160:] +X, y = make_classification(n_samples=60, n_features=4, n_informative=3, n_redundant=0, random_state=42) +X_train, X_test = X[:45], X[45:] +y_train, y_test = y[:45], y[45:] -# Create ensemble agent agent = QuantumClassificationAgent( + backend='simulator', algorithms=['quantum_svm', 'quantum_nn'], ensemble_method='weighted', - backend='simulator' + seed=0, ) +agent.algorithms['quantum_nn'].max_epochs = 20 # keep the example quick -# Train ensemble agent.fit(X_train, y_train) - -# Make predictions predictions = agent.predict(X_test) -accuracy = agent.score(X_test, y_test) - -print(f"Ensemble accuracy: {accuracy:.3f}") -print("Individual performances:", agent.performance_metrics) +print(f"Ensemble test accuracy: {(predictions == y_test).mean():.3f}") +print("Training accuracy per algorithm:", agent.performance_metrics) ``` -### QuantumPortfolioAgent - -Specialized quantum agent for portfolio optimization and risk management. +### Benchmark against classical models ```python -from superquantx import QuantumPortfolioAgent - -# Create portfolio agent -agent = QuantumPortfolioAgent( - backend='pennylane', - risk_model='mean_variance', - optimization_objective='sharpe', - constraints=[ - {'type': 'budget'}, - {'type': 'long_only'}, - {'type': 'max_weight', 'value': 0.2} - ] -) - -# Fit to historical returns -agent.fit(returns_data) -optimal_weights = agent.predict(current_data) -``` - -#### Constructor - -##### __init__(backend, risk_model='mean_variance', optimization_objective='sharpe', constraints=None, rebalancing_frequency='monthly', **kwargs) - -**Parameters:** -- `backend` (str): Quantum backend -- `risk_model` (str): Risk model type - - `'mean_variance'`: Classic mean-variance optimization - - `'black_litterman'`: Black-Litterman model - - `'factor'`: Factor-based risk model -- `optimization_objective` (str): Objective function - - `'return'`: Maximize expected return - - `'sharpe'`: Maximize Sharpe ratio - - `'risk_parity'`: Risk parity allocation -- `constraints` (list): Portfolio constraints (see below) -- `rebalancing_frequency` (str): Rebalancing frequency -- `**kwargs`: Additional parameters +from sklearn.datasets import make_classification +from superquantx import QuantumClassificationAgent -#### Constraint Types +X, y = make_classification(n_samples=60, n_features=4, n_informative=3, n_redundant=0, random_state=0) -Portfolio constraints can be specified as dictionaries: +agent = QuantumClassificationAgent(backend='simulator', cv=3, seed=0) +result = agent.solve((X, y)) +r = result.result -```python -constraints = [ - {'type': 'budget'}, # Sum of weights = 1 - {'type': 'long_only'}, # All weights >= 0 - {'type': 'max_weight', 'value': 0.3}, # Max weight per asset - {'type': 'sector_limit', 'assets': [0,1,2], 'value': 0.5} # Sector exposure limit -] +print(f"QuantumSVM CV accuracy: {r['cv_accuracy']:.3f} +/- {r['cv_accuracy_std']:.3f}") +print(f"Best classical ({r['best_classical']}): {r['best_classical_cv_accuracy']:.3f}") +print(f"p-value: {r['p_value']:.3f}") +print("Verdict:", r['verdict']) ``` -#### Methods - -##### fit(X, y=None, **kwargs) +!!! note "Not available in 0.3.0" + There is no `'stacking'` ensemble and no `auto_tune` option. -Fit portfolio optimization to historical returns data. +## QuantumTradingAgent -**Parameters:** -- `X` (numpy.ndarray): Historical returns (samples × assets) -- `y` (numpy.ndarray, optional): Not used -- `**kwargs`: Additional parameters including `risk_aversion` +!!! warning "Experimental" + Only `strategy='quantum_portfolio'` is implemented. `deploy(returns)` runs the portfolio agent and returns its result. Other strategies (for example momentum or mean reversion) and `predict()` raise `NotImplementedError`. There are no trading signals or backtests. -**Returns:** -- `QuantumPortfolioAgent`: Self - -##### predict(X, **kwargs) - -Predict optimal portfolio weights for current market conditions. - -**Parameters:** -- `X` (numpy.ndarray): Current market data -- `**kwargs`: Prediction parameters - -**Returns:** -- `numpy.ndarray`: Optimal portfolio weights - -##### solve(problem_instance, **kwargs) - -Solve complete portfolio optimization problem. - -**Parameters:** -- `problem_instance` (numpy.ndarray): Returns data -- `**kwargs`: Solving parameters including `method` ('vqe' or 'qaoa') - -**Returns:** -- `QuantumResult`: Portfolio optimization results - -#### Example +**Constructor:** `QuantumTradingAgent(backend='simulator', strategy='quantum_portfolio', risk_tolerance=0.5, markets=None, **kwargs)`. Higher `risk_tolerance` puts less weight on variance. ```python import numpy as np -from superquantx import QuantumPortfolioAgent - -# Generate sample returns data -np.random.seed(42) -returns = np.random.multivariate_normal( - mean=[0.08, 0.12, 0.10, 0.15], # Expected returns - cov=[[0.16, 0.05, 0.03, 0.02], # Covariance matrix - [0.05, 0.25, 0.04, 0.03], - [0.03, 0.04, 0.20, 0.05], - [0.02, 0.03, 0.05, 0.30]], - size=252 # One year of daily returns -) - -# Create portfolio agent with constraints -agent = QuantumPortfolioAgent( - risk_model='mean_variance', - optimization_objective='sharpe', - constraints=[ - {'type': 'budget'}, - {'type': 'long_only'}, - {'type': 'max_weight', 'value': 0.4} - ] -) - -# Optimize portfolio -agent.fit(returns, risk_aversion=2.0) -result = agent.solve(returns, method='vqe') - -weights = result.result['weights'] -expected_return = result.result['expected_return'] -risk = result.result['risk'] -sharpe = result.result['sharpe_ratio'] - -print(f"Optimal weights: {weights}") -print(f"Expected return: {expected_return:.3f}") -print(f"Risk (volatility): {risk:.3f}") -print(f"Sharpe ratio: {sharpe:.3f}") -``` - -## Agent Workflows - -### Multi-Agent Systems - -Combine multiple agents for complex problems: - -```python -from superquantx import QuantumTradingAgent, QuantumResearchAgent - -# Research agent discovers new strategies -research_agent = QuantumResearchAgent(domain='finance') -research_result = research_agent.investigate( - "What quantum advantages exist in high-frequency trading?" -) - -# Trading agent implements the strategies -trading_agent = QuantumTradingAgent( - strategy='quantum_momentum', - risk_tolerance=0.3 -) -trading_result = trading_agent.deploy(market_data) - -# Compare results -quantum_advantage = ( - trading_result.result['quantum_advantage'] + - research_result.result.get('expected_quantum_advantage', 0) -) / 2 -``` - -### Agent Orchestration - -Coordinate agents for complex workflows: - -```python -class QuantumAgentOrchestrator: - def __init__(self): - self.agents = {} - - def add_agent(self, name, agent): - self.agents[name] = agent - - def run_workflow(self, problem_data, workflow_steps): - results = {} - - for step in workflow_steps: - agent_name = step['agent'] - method = step['method'] - params = step.get('params', {}) - - agent = self.agents[agent_name] - result = getattr(agent, method)(problem_data, **params) - results[agent_name] = result - - # Pass results to next step - if 'output_to' in step: - problem_data = result.result - - return results - -# Use orchestrator -orchestrator = QuantumAgentOrchestrator() -orchestrator.add_agent('research', QuantumResearchAgent()) -orchestrator.add_agent('optimization', QuantumOptimizationAgent()) - -workflow = [ - {'agent': 'research', 'method': 'investigate', 'params': {'research_question': 'Optimize supply chain'}}, - {'agent': 'optimization', 'method': 'solve', 'output_to': 'final_result'} -] - -results = orchestrator.run_workflow(supply_chain_data, workflow) -``` - -### Performance Monitoring - -Monitor agent performance across deployments: - -```python -class AgentPerformanceMonitor: - def __init__(self): - self.performance_history = {} - - def track_agent_performance(self, agent_name, result): - if agent_name not in self.performance_history: - self.performance_history[agent_name] = [] - - performance_data = { - 'timestamp': time.time(), - 'execution_time': result.execution_time, - 'success': result.error is None, - 'quantum_advantage': result.result.get('quantum_advantage', 0), - 'metadata': result.metadata - } - - self.performance_history[agent_name].append(performance_data) - - def get_performance_summary(self, agent_name): - history = self.performance_history.get(agent_name, []) - if not history: - return None - - success_rate = sum(1 for h in history if h['success']) / len(history) - avg_execution_time = np.mean([h['execution_time'] for h in history]) - avg_quantum_advantage = np.mean([h['quantum_advantage'] for h in history]) - - return { - 'success_rate': success_rate, - 'avg_execution_time': avg_execution_time, - 'avg_quantum_advantage': avg_quantum_advantage, - 'total_deployments': len(history) - } - -# Monitor agent performance -monitor = AgentPerformanceMonitor() - -# Deploy agents and track performance -trading_agent = QuantumTradingAgent() -result = trading_agent.deploy(market_data) -monitor.track_agent_performance('trading_agent', result) - -# Get performance summary -summary = monitor.get_performance_summary('trading_agent') -print(f"Success rate: {summary['success_rate']:.2%}") -print(f"Avg execution time: {summary['avg_execution_time']:.2f}s") -``` - -## Error Handling - -All quantum agents implement robust error handling: - -```python -try: - agent = QuantumTradingAgent(strategy='invalid_strategy') - result = agent.deploy(market_data) - - if result.error: - print(f"Agent error: {result.error}") - print(f"Metadata: {result.metadata}") - else: - print(f"Success: {result.result}") - -except Exception as e: - print(f"Unexpected error: {e}") -``` - -### Common Error Types - -- **AlgorithmError**: Issues with quantum algorithm execution -- **ConfigurationError**: Invalid agent configuration -- **ConvergenceError**: Optimization failed to converge -- **BackendError**: Quantum backend issues -- **DataError**: Invalid input data format - -### Error Recovery +from superquantx import QuantumTradingAgent -Agents can implement automatic error recovery: +rng = np.random.default_rng(1) +returns = rng.normal(0.001, 0.02, size=(250, 4)) # 250 periods, 4 assets -```python -class ResilientQuantumAgent(QuantumAgent): - def solve(self, problem_instance, max_retries=3, **kwargs): - for attempt in range(max_retries): - try: - return super().solve(problem_instance, **kwargs) - except Exception as e: - if attempt == max_retries - 1: - raise e - else: - logger.warning(f"Attempt {attempt + 1} failed: {e}. Retrying...") - # Modify strategy for retry - kwargs['fallback_mode'] = True +agent = QuantumTradingAgent(strategy='quantum_portfolio', risk_tolerance=0.4, seed=0) +result = agent.deploy(returns) +print("Selected assets:", result.result['selected_assets']) +print("Matches brute-force optimum:", result.result['matches_classical_optimum']) +print(f"Sharpe ratio of selection: {result.result['sharpe_ratio']:.3f}") ``` -## Best Practices +## QuantumResearchAgent -### Agent Selection +!!! warning "Experimental" + Only ground-state simulation is implemented. `investigate()` (automated research planning, hypothesis generation, experiment design) raises `NotImplementedError`. -Choose agents based on problem characteristics: +**Constructor:** `QuantumResearchAgent(backend='simulator', domain='materials_science', **kwargs)` -```python -def select_optimal_agent(problem_type, data_size, quantum_resources): - if problem_type == 'portfolio_optimization': - return QuantumPortfolioAgent( - backend='pennylane' if quantum_resources == 'high' else 'simulator' - ) - elif problem_type == 'classification' and data_size > 1000: - return QuantumClassificationAgent( - algorithms=['quantum_svm', 'hybrid'], - ensemble_method='weighted' - ) - elif problem_type == 'research': - return QuantumResearchAgent( - domain=infer_domain(problem_type), - hypothesis_generation=True - ) - else: - return QuantumOptimizationAgent( - problem_type='combinatorial' if is_discrete(problem_type) else 'continuous' - ) -``` - -### Configuration Management - -Use configuration files for agent setup: +`simulate_ground_state(hamiltonian=None)` runs VQE and reports the exact energy. With no argument it uses H2 in STO-3G at 0.735 Angstrom. ```python -import yaml - -# agent_config.yaml -config = yaml.safe_load(""" -trading_agent: - strategy: quantum_portfolio - risk_tolerance: 0.4 - markets: [stocks, crypto] - constraints: - - type: long_only - - type: max_weight - value: 0.3 - -research_agent: - domain: materials_science - hypothesis_generation: true - experiment_design: true -""") - -# Load agents from config -agents = {} -for agent_name, agent_config in config.items(): - if 'trading' in agent_name: - agents[agent_name] = QuantumTradingAgent(**agent_config) - elif 'research' in agent_name: - agents[agent_name] = QuantumResearchAgent(**agent_config) -``` - -### Performance Optimization - -Optimize agent performance: - -```python -# 1. Use appropriate backends -agent = QuantumTradingAgent( - backend='pennylane' if complex_problem else 'simulator' -) - -# 2. Tune shot counts -agent.shots = 2048 if high_precision_needed else 1024 - -# 3. Enable parallel execution -results = [] -with ThreadPoolExecutor() as executor: - futures = [ - executor.submit(agent.solve, problem_instance) - for problem_instance in problem_batch - ] - results = [f.result() for f in futures] - -# 4. Cache expensive computations -from functools import lru_cache +from superquantx import QuantumResearchAgent -@lru_cache(maxsize=128) -def cached_agent_solve(agent_hash, problem_hash): - return agent.solve(problem_instance) +agent = QuantumResearchAgent(seed=0) +result = agent.simulate_ground_state() +print(result.result['hamiltonian']) +print(f"VQE {result.result['ground_energy']:.6f} Ha, exact {result.result['exact_energy']:.6f} Ha") ``` -## Examples +## Combining agents -### Financial Portfolio Management - -Complete portfolio management workflow: +Agents are ordinary Python objects, so you can chain them yourself: ```python -import pandas as pd import numpy as np -from superquantx import QuantumPortfolioAgent, QuantumTradingAgent - -# Load historical data -returns_data = pd.read_csv('stock_returns.csv').values - -# Create portfolio optimization agent -portfolio_agent = QuantumPortfolioAgent( - optimization_objective='sharpe', - constraints=[ - {'type': 'budget'}, - {'type': 'long_only'}, - {'type': 'max_weight', 'value': 0.25} - ] -) - -# Optimize portfolio -portfolio_agent.fit(returns_data) -optimal_weights = portfolio_agent.predict(returns_data[-30:]) - -# Create trading agent for execution -trading_agent = QuantumTradingAgent( - strategy='quantum_portfolio', - risk_tolerance=0.3 -) +from superquantx import QuantumOptimizationAgent, QuantumPortfolioAgent -# Deploy trading strategy -trading_result = trading_agent.deploy({ - 'optimal_weights': optimal_weights, - 'current_prices': current_market_data -}) +rng = np.random.default_rng(7) +returns = rng.normal(0.001, 0.02, size=(250, 4)) -print(f"Portfolio Performance:") -print(f"Expected Return: {trading_result.result['performance']['expected_return']:.2%}") -print(f"Risk: {trading_result.result['performance']['risk']:.2%}") -print(f"Quantum Advantage: {trading_result.result['quantum_advantage']:.2%}") -``` - -### Scientific Research Acceleration - -Accelerate materials science research: - -```python -from superquantx import QuantumResearchAgent +portfolio = QuantumPortfolioAgent(backend='simulator', n_select=2, seed=0).solve(returns) +held = portfolio.result['selected_assets'] -# Create research agent for materials science -research_agent = QuantumResearchAgent( - domain='materials_science', - hypothesis_generation=True, - experiment_design=True -) +# Split the held assets' correlation graph with MaxCut +corr = np.abs(np.corrcoef(returns[:, held].T)) +np.fill_diagonal(corr, 0) +split = QuantumOptimizationAgent(backend='simulator', seed=0).solve(corr) -# Investigate superconductor research -research_question = ( - "How can quantum simulation discover room-temperature superconductors " - "with transition temperatures above 300K?" -) - -constraints = { - 'timeline': '24_months', - 'budget': 1000000, - 'quantum_hardware': 'available' -} - -result = research_agent.investigate(research_question, constraints) - -# Access research plan -plan = result.result['research_plan'] -hypothesis = result.result['hypothesis'] -experiments = result.result['experiments'] - -print("Research Plan:") -for i, phase in enumerate(plan['phases'], 1): - print(f"{i}. {phase}") - -print(f"\nPrimary Hypothesis:") -print(hypothesis['primary_hypothesis']) - -print(f"\nProposed Experiments:") -for exp in experiments: - print(f"- {exp['experiment_name']}") - print(f" Duration: {exp['expected_duration']}") - print(f" Resources: {exp['quantum_resources_needed']}") +print("Held:", held, "split:", split.result['bitstring']) +for name, res in [('portfolio', portfolio), ('maxcut', split)]: + print(f"{name}: {res.execution_time:.2f}s, error={res.error}") ``` -### Multi-Modal Classification - -Complex classification with ensemble methods: +## Error handling ```python -from sklearn.datasets import fetch_openml -from superquantx import QuantumClassificationAgent - -# Load complex dataset -X, y = fetch_openml('wine-quality-red', return_X_y=True, as_frame=False) -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - -# Create ensemble classification agent -classification_agent = QuantumClassificationAgent( - algorithms=['quantum_svm', 'quantum_nn', 'hybrid'], - ensemble_method='weighted', - auto_tune=True -) - -# Solve classification problem -result = classification_agent.solve((X_train, y_train)) - -# Evaluate on test set -test_predictions = classification_agent.predict(X_test) -test_accuracy = accuracy_score(y_test, test_predictions) - -print("Classification Results:") -print(f"Training Accuracy: {result.result['accuracy']:.3f}") -print(f"Test Accuracy: {test_accuracy:.3f}") +import numpy as np +from superquantx import QuantumResearchAgent, QuantumTradingAgent -print("\nIndividual Algorithm Performance:") -for algo, performance in result.result['individual_performances'].items(): - print(f" {algo}: {performance:.3f}") +try: + QuantumTradingAgent(strategy='momentum').deploy(np.zeros((10, 3))) +except NotImplementedError as e: + print("Not implemented:", e) -print(f"\nEnsemble Method: {result.result['ensemble_method']}") -print(f"Algorithms Used: {result.metadata['algorithms_used']}") +try: + QuantumResearchAgent().investigate("Find a room-temperature superconductor") +except NotImplementedError as e: + print("Not implemented:", e) ``` ---- - -*The quantum agent API represents the cutting edge of quantum AI - autonomous systems that leverage quantum advantages for real-world problem solving. These agents combine multiple quantum algorithms with classical AI to create powerful, specialized problem-solving capabilities.* - -!!! tip "Agent Selection" - Choose agents based on your problem domain and quantum resource availability. Start with simulation backends and upgrade to quantum hardware when advantages are demonstrated. - -!!! warning "Performance Considerations" - Quantum agents may require significant computational resources. Monitor performance and use appropriate backends for your use case. +Invalid arguments raise `ValueError`, for example an unknown algorithm name in `QuantumClassificationAgent` or a `problem_type` other than `'combinatorial'` or `'continuous'`. -!!! info "Extensibility" - The agent framework is designed for extensibility. Create custom agents by inheriting from `QuantumAgent` and implementing domain-specific logic. \ No newline at end of file +!!! tip "Choosing an agent" + Start on the `'simulator'` backend. Every agent accepts any SuperQuantX gate-model backend name, for example `'qiskit'` or `'pennylane'`, once the matching extra is installed. diff --git a/docs/api/algorithms.md b/docs/api/algorithms.md index 741cbcc..03f7add 100644 --- a/docs/api/algorithms.md +++ b/docs/api/algorithms.md @@ -1,9 +1,5 @@ # 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 @@ -147,176 +143,104 @@ SuperQuantX provides a comprehensive collection of quantum algorithms for machin ## Examples and Usage Patterns -### Machine Learning Example +All snippets below run on SuperQuantX 0.3.0 with the built-in simulator. + +### Quantum SVM ```python import numpy as np from sklearn.datasets import make_classification import superquantx as sqx -# Generate sample data X, y = make_classification( - n_samples=100, - n_features=4, - n_classes=2, - random_state=42 -) - -# Split data -X_train, X_test = X[:80], X[80:] -y_train, y_test = y[:80], y[80:] - -# Create and train Quantum SVM -qsvm = sqx.QuantumSVM( - backend='simulator', - feature_map='ZFeatureMap', - num_features=4 + n_samples=60, n_features=4, n_informative=3, n_redundant=0, random_state=0 ) +X_train, X_test, y_train, y_test = X[:45], X[45:], y[:45], y[45:] +qsvm = sqx.QuantumSVM(backend="simulator", feature_map="ZFeatureMap") qsvm.fit(X_train, y_train) -predictions = qsvm.predict(X_test) -accuracy = qsvm.score(X_test, y_test) - -print(f"Quantum SVM Accuracy: {accuracy:.3f}") +print(float(np.mean(qsvm.predict(X_test) == y_test))) ``` -### VQE Molecule Example +### VQE for a Molecule ```python import superquantx as sqx -# Create VQE for H2 molecule vqe = sqx.create_vqe_for_molecule( - molecule='H2', - bond_length=0.735, # Angstroms - backend='simulator' + molecule_name="H2", + bond_distance=0.735, + backend="simulator", + maxiter=40, ) - -# Find ground state -ground_energy = vqe.find_ground_state() -print(f"H2 Ground State Energy: {ground_energy:.6f} Ha") - -# Get optimized parameters -optimal_params = vqe.get_optimal_parameters() -print(f"Optimal parameters: {optimal_params}") +energy = vqe.find_ground_state() +print(f"H2 ground-state energy: {energy:.6f} Ha") ``` -### QAOA Optimization Example +### QAOA MaxCut ```python +import numpy as np import superquantx as sqx -# Define Max-Cut problem -edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] - -qaoa = sqx.QAOA( - problem_type='max_cut', - graph_edges=edges, - layers=3, - backend='simulator' -) +adjacency = np.array([ + [0, 1, 1, 0], + [1, 0, 1, 1], + [1, 1, 0, 1], + [0, 1, 1, 0], +], dtype=float) -# Solve optimization problem -solution = qaoa.solve() -optimal_value = qaoa.get_optimal_value() - -print(f"Max-Cut Solution: {solution}") -print(f"Cut Value: {optimal_value}") +qaoa = sqx.QAOA(backend="simulator", p=1, maxiter=30, n_restarts=1) +result = qaoa.solve(adjacency) +print(result["bitstring"], result["cut_value"], result["classical_optimum"]) ``` -### Quantum Agent Example +### Quantum Portfolio Agent ```python import superquantx as sqx -# Create quantum portfolio optimization agent -portfolio_agent = sqx.QuantumPortfolioAgent( - backend='simulator', - risk_tolerance=0.1, - optimization_method='qaoa' +returns, cov, _, meta = sqx.generate_portfolio_data( + n_assets=4, n_scenarios=40, random_state=0 ) - -# Sample portfolio data -assets = ['AAPL', 'GOOGL', 'MSFT', 'TSLA'] -returns = [0.12, 0.15, 0.08, 0.20] -risks = [0.05, 0.10, 0.03, 0.15] - -# Optimize portfolio -optimal_weights = portfolio_agent.optimize_portfolio( - assets=assets, - expected_returns=returns, - risk_estimates=risks, - budget=10000 +agent = sqx.QuantumPortfolioAgent( + backend="simulator", n_select=2, maxiter=40, n_restarts=1 ) - -print("Optimal Portfolio:") -for asset, weight in zip(assets, optimal_weights): - print(f"{asset}: {weight:.2%}") +agent.fit(returns) +result = agent.solve() +print(result.result["selected_assets"], result.result["matches_classical_optimum"]) ``` -## Best Practices - -### Algorithm Selection - -1. **For Classification**: Use `QuantumSVM` for small datasets, `QuantumNN` for complex patterns -2. **For Optimization**: Use `VQE` for chemistry problems, `QAOA` for combinatorial optimization -3. **For Autonomous Tasks**: Use specialized `QuantumAgent` implementations - -### Backend Optimization - -```python -# Choose appropriate backend for algorithm -algorithms_backends = { - 'QuantumSVM': 'pennylane', # Best autodiff support - 'VQE': 'qiskit', # Good hardware access - 'QAOA': 'cirq', # Flexible circuit construction - 'QuantumAgents': 'simulator', # Fast prototyping -} - -# Use backend-specific optimizations -qsvm = sqx.QuantumSVM( - backend='pennylane', - feature_map='ZZFeatureMap', # More expressive for PennyLane - optimization_level=2 -) -``` - -### Performance Monitoring +### Comparing Algorithms ```python import time +import numpy as np +from sklearn.datasets import make_classification import superquantx as sqx -# Benchmark different algorithms -def benchmark_algorithm(algorithm_class, X, y, **kwargs): - start_time = time.time() - - algorithm = algorithm_class(**kwargs) - algorithm.fit(X, y) - predictions = algorithm.predict(X) - - execution_time = time.time() - start_time - accuracy = algorithm.score(X, y) - - return { - 'accuracy': accuracy, - 'time': execution_time, - 'algorithm': algorithm_class.__name__ - } - -# Compare algorithms -algorithms = [sqx.QuantumSVM, sqx.QuantumNN, sqx.HybridClassifier] -results = [] - -for algo in algorithms: - result = benchmark_algorithm(algo, X_train, y_train, backend='simulator') - results.append(result) - print(f"{result['algorithm']}: {result['accuracy']:.3f} accuracy in {result['time']:.2f}s") +X, y = make_classification( + n_samples=40, n_features=2, n_informative=2, n_redundant=0, random_state=0 +) + +def time_fit(ctor, **kwargs): + model = ctor(**kwargs) + t0 = time.time() + model.fit(X, y) + return time.time() - t0, float(np.mean(model.predict(X) == y)) + +for name, ctor, kwargs in [ + ("QuantumSVM", sqx.QuantumSVM, {"backend": "simulator", "feature_map": "ZFeatureMap"}), + ("QuantumNN", sqx.QuantumNN, {"backend": "simulator", "n_layers": 1, "max_epochs": 8, "seed": 0}), +]: + secs, acc = time_fit(ctor, **kwargs) + print(f"{name}: acc={acc:.3f} in {secs:.2f}s") ``` --- For complete algorithm implementations and advanced usage patterns, see: -- [Backend Integration Guide](../backends/) -- [Tutorial Examples](../tutorials/) -- [User Guide](../user-guide/) \ No newline at end of file + +- [Backend Integration Guide](../backends/simulator.md) +- [Tutorial Examples](../tutorials/basic-quantum.md) +- [User Guide](../user-guide/overview.md) diff --git a/docs/api/backends.md b/docs/api/backends.md index 134ac32..078d646 100644 --- a/docs/api/backends.md +++ b/docs/api/backends.md @@ -1,519 +1,90 @@ # 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). +Backend classes wrap a quantum framework behind one portable interface. +Autodoc for the base class and factory is below; runnable examples follow. - -SuperQuantX provides a unified interface to multiple quantum computing backends, enabling seamless switching between simulators and real quantum hardware from different providers. - -## Base Classes - -### Base Backend +## Base Backend ::: superquantx.backends.BaseBackend handler: python options: docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -## Simulator Backends - -### Python Simulator Backend - -::: superquantx.backends.SimulatorBackend - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -## Hardware Backends - -### IBM Qiskit Backend - -::: superquantx.backends.QiskitBackend - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -### PennyLane Backend - -::: superquantx.backends.PennyLaneBackend - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -### Google Cirq Backend - -::: superquantx.backends.CirqBackend - handler: python - options: - docstring_style: google - show_source: true + show_source: false show_root_heading: true - show_root_toc_entry: true -### Amazon Braket Backend +## Factory -::: superquantx.backends.BraketBackend +::: superquantx.get_backend handler: python options: docstring_style: google - show_source: true + show_source: false show_root_heading: true - show_root_toc_entry: true - -### TKET/Quantinuum Backend - -::: superquantx.backends.TKETBackend - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -### D-Wave Ocean Backend - -::: superquantx.backends.OceanBackend - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -## Utility Functions - -### Backend Management - -::: superquantx.backends.get_backend - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.backends.list_available_backends - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.backends.check_backend_compatibility - handler: python - options: - docstring_style: google - show_source: true - -## Backend Selection Guide - -### By Use Case -**Development & Prototyping** -```python -# Fast local simulation -backend = sqx.get_backend('simulator', max_qubits=10) - -# Cross-platform testing -backend = sqx.get_backend('pennylane', device='default.qubit') -``` - -**Production & Research** -```python -# IBM Quantum hardware -backend = sqx.get_backend('qiskit', device='ibmq_manila', token='your-token') - -# Google Quantum AI -backend = sqx.get_backend('cirq', processor_id='rainbow', project_id='your-project') - -# AWS Braket cloud -backend = sqx.get_backend('braket', device_arn='arn:aws:braket:us-east-1::device/qpu/ionq/ionQdevice') -``` +## Creating Backends -**Specialized Applications** ```python -# Quantum chemistry (TKET optimization) -backend = sqx.get_backend('tket', device='H1-1E', api_key='quantinuum-key') - -# Optimization problems (D-Wave annealing) -backend = sqx.get_backend('ocean', device='advantage', token='dwave-token') -``` - -### By Performance Requirements - -**High Accuracy (Large Shot Counts)** -```python -backends_high_accuracy = { - 'simulator': sqx.get_backend('simulator', shots=100000), - 'ibm_hardware': sqx.get_backend('qiskit', device='ibmq_montreal', shots=8192), - 'aws_sv1': sqx.get_backend('braket', device='sv1', shots=100000) -} -``` - -**Fast Iteration (Low Latency)** -```python -backends_fast = { - 'local_sim': sqx.get_backend('simulator', shots=1000), - 'pennylane': sqx.get_backend('pennylane', device='lightning.qubit'), - 'braket_local': sqx.get_backend('braket', device='braket_sv') -} -``` +import superquantx as sqx -**Cost Optimization** -```python -# Free tier resources -free_backends = { - 'simulator': sqx.get_backend('simulator'), - 'ibm_free': sqx.get_backend('qiskit', device='ibmq_qasm_simulator'), - 'aws_sim': sqx.get_backend('braket', device='braket_sv') # First 1 hour free -} +sim = sqx.get_backend("simulator", max_qubits=10, shots=1000) +pl = sqx.get_backend("pennylane", device="default.qubit") +qk = sqx.get_backend("qiskit") +print(type(sim).__name__, type(pl).__name__, type(qk).__name__) ``` -## Integration Examples - -### Multi-Backend Algorithm Testing +## Portable Circuit Execution ```python import superquantx as sqx -def test_algorithm_across_backends(algorithm_func, backends, *args, **kwargs): - """Test quantum algorithm across multiple backends.""" - - results = {} - - for backend_name, backend in backends.items(): - try: - print(f"Testing on {backend_name}...") - - # Run algorithm - result = algorithm_func(backend, *args, **kwargs) - results[backend_name] = result - - print(f" ✓ Success: {result}") - - except Exception as e: - print(f" ✗ Failed: {e}") - results[backend_name] = None - - return results - -# Define test backends -test_backends = { - 'simulator': sqx.get_backend('simulator'), - 'pennylane': sqx.get_backend('pennylane', device='default.qubit'), -} - -# Example quantum algorithm -def simple_bell_state(backend): +def bell_counts(name, shots=300): + backend = sqx.get_backend(name) circuit = backend.create_circuit(2) - circuit = backend.add_gate(circuit, 'h', 0) - circuit = backend.add_gate(circuit, 'cx', [0, 1]) - return backend.execute_circuit(circuit) + backend.add_gate(circuit, "H", 0) + backend.add_gate(circuit, "CNOT", [0, 1]) + backend.add_measurement(circuit) + return backend.execute_circuit(circuit, shots=shots)["counts"] -# Test across backends -results = test_algorithm_across_backends(simple_bell_state, test_backends) +for name in ["simulator", "pennylane", "qiskit", "cirq", "braket", "tket"]: + print(name, bell_counts(name)) ``` -### Backend Fallback Strategy +## Fallback Selection ```python -def get_backend_with_fallback(preferences, **kwargs): - """Get backend with fallback strategy.""" - - for backend_name in preferences: - try: - backend = sqx.get_backend(backend_name, **kwargs) - if backend.is_available(): - print(f"Using backend: {backend_name}") - return backend - except Exception as e: - print(f"Backend {backend_name} failed: {e}") - continue - - raise RuntimeError("No backends available") - -# Usage -backend = get_backend_with_fallback([ - 'qiskit', # Try IBM first - 'pennylane', # Fallback to PennyLane - 'simulator' # Final fallback -], shots=1024) -``` - -### Performance Benchmarking - -```python -import time -import numpy as np - -def benchmark_backends(backends, circuit_sizes=[2, 4, 6, 8]): - """Benchmark quantum backends across different circuit sizes.""" - - results = {} - - for backend_name, backend in backends.items(): - print(f"\nBenchmarking {backend_name}:") - results[backend_name] = {} - - for n_qubits in circuit_sizes: - if n_qubits > backend.get_backend_info().get('capabilities', {}).get('max_qubits', 32): - continue - - # Create test circuit - circuit = backend.create_circuit(n_qubits) - - # Add random gates - for _ in range(n_qubits * 2): - qubit = np.random.randint(0, n_qubits) - circuit = backend.add_gate(circuit, 'h', qubit) - - for _ in range(n_qubits - 1): - q1, q2 = np.random.choice(n_qubits, 2, replace=False) - circuit = backend.add_gate(circuit, 'cx', [q1, q2]) - - # Benchmark execution - start_time = time.time() - try: - result = backend.execute_circuit(circuit, shots=1000) - execution_time = time.time() - start_time - - results[backend_name][n_qubits] = { - 'time': execution_time, - 'success': result.get('success', True), - 'total_counts': sum(result.get('counts', {}).values()) - } - - print(f" {n_qubits} qubits: {execution_time:.3f}s") - - except Exception as e: - print(f" {n_qubits} qubits: Failed - {e}") - results[backend_name][n_qubits] = {'error': str(e)} - - return results - -# Run benchmark -benchmark_backends({ - 'simulator': sqx.get_backend('simulator'), - 'pennylane': sqx.get_backend('pennylane'), -}) -``` - -## Backend Configuration - -### Environment Setup - -```python -import os import superquantx as sqx -# Configure backends via environment variables -os.environ['QISKIT_IBMQ_TOKEN'] = 'your-ibm-token' -os.environ['BRAKET_AWS_REGION'] = 'us-east-1' -os.environ['DWAVE_API_TOKEN'] = 'your-dwave-token' - -# Test configurations -def validate_backend_config(): - """Validate backend configurations.""" - - configs = { - 'qiskit': { - 'required_env': ['QISKIT_IBMQ_TOKEN'], - 'test_device': 'ibmq_qasm_simulator' - }, - 'braket': { - 'required_env': ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'], - 'test_device': 'braket_sv' - }, - 'ocean': { - 'required_env': ['DWAVE_API_TOKEN'], - 'test_device': 'simulator' - } - } - - for backend_name, config in configs.items(): - print(f"Validating {backend_name}:") - - # Check environment variables - missing_env = [env for env in config['required_env'] - if not os.getenv(env)] - - if missing_env: - print(f" ✗ Missing environment variables: {missing_env}") - continue - - # Test backend creation +def first_working(names): + for name in names: try: - backend = sqx.get_backend(backend_name, device=config['test_device']) - if backend.is_available(): - print(f" ✓ Backend available") - else: - print(f" ✗ Backend not available") + return sqx.get_backend(name) except Exception as e: - print(f" ✗ Configuration error: {e}") - -validate_backend_config() -``` - -### Custom Backend Configuration - -```python -# Advanced backend configuration -backend_configs = { - 'qiskit_optimized': { - 'backend_type': 'qiskit', - 'device': 'ibmq_montreal', - 'shots': 4096, - 'optimization_level': 3, - 'error_mitigation': True, - 'noise_model': 'device_noise' - }, - - 'pennylane_gpu': { - 'backend_type': 'pennylane', - 'device': 'lightning.gpu', - 'shots': 100000, - 'batch_size': 1024 - }, - - 'braket_cost_optimized': { - 'backend_type': 'braket', - 'device': 'sv1', # Simulator for cost optimization - 'shots': 1000, - 'max_parallel_tasks': 5 - } -} - -def create_configured_backend(config_name): - """Create backend from configuration.""" - config = backend_configs[config_name] - backend_type = config.pop('backend_type') - return sqx.get_backend(backend_type, **config) -``` - -## Error Handling - -### Backend-Specific Error Handling - -```python -from superquantx.exceptions import ( - QuantumBackendError, - DeviceOfflineError, - AuthenticationError, - ResourceExhaustedError -) - -def robust_backend_execution(backend, circuit, max_retries=3): - """Execute circuit with comprehensive error handling.""" - - for attempt in range(max_retries): - try: - result = backend.execute_circuit(circuit) - return result - - except AuthenticationError: - print("Authentication failed - check API tokens") - raise # Don't retry auth errors - - except DeviceOfflineError as e: - print(f"Device offline: {e}") - if attempt < max_retries - 1: - print("Waiting 30s before retry...") - time.sleep(30) - - except ResourceExhaustedError as e: - print(f"Resources exhausted: {e}") - # Reduce shots and retry - circuit.shots = max(circuit.shots // 2, 100) - - except QuantumBackendError as e: - print(f"Backend error on attempt {attempt + 1}: {e}") - if attempt == max_retries - 1: - raise - - raise RuntimeError("All execution attempts failed") + print(f"{name} unavailable: {type(e).__name__}") + raise RuntimeError("no backend available") -# Usage with error handling -try: - backend = sqx.get_backend('qiskit', device='ibmq_manila') - result = robust_backend_execution(backend, circuit) -except Exception as e: - print(f"Execution failed: {e}") - # Fallback to simulator - fallback_backend = sqx.get_backend('simulator') - result = fallback_backend.execute_circuit(circuit) +backend = first_working(["pennylane", "qiskit", "simulator"]) +print(type(backend).__name__) ``` -## Best Practices - -### Backend Selection Strategy +## Hardware (credentials required) -1. **Development Phase**: Use `simulator` or `pennylane` for rapid iteration -2. **Testing Phase**: Use cloud simulators (`braket_sv`, `qiskit_aer`) for validation -3. **Production Phase**: Use real hardware with appropriate error mitigation -4. **Cost Optimization**: Use free simulators when possible, batch hardware jobs - -### Performance Optimization +!!! note "Requires credentials" + Not run in the docs checker. + ```python -# Optimize circuit for specific backend -def optimize_for_backend(circuit, backend): - """Optimize circuit for specific backend capabilities.""" - - backend_info = backend.get_backend_info() - - if 'qiskit' in backend_info.get('backend_name', ''): - # Use Qiskit-specific optimizations - return backend.transpile_circuit(circuit, optimization_level=2) - - elif 'tket' in backend_info.get('backend_name', ''): - # Use TKET optimizations - return backend.optimize_circuit(circuit, optimization_level=3) - - elif 'ocean' in backend_info.get('backend_name', ''): - # Ocean backends use different problem formulations - return backend.convert_to_qubo(circuit) - - else: - # Generic optimization - return circuit +import superquantx as sqx -# Batch processing for hardware backends -def batch_execute_circuits(backend, circuits, max_batch_size=10): - """Execute circuits in batches for efficiency.""" - - results = [] - - for i in range(0, len(circuits), max_batch_size): - batch = circuits[i:i + max_batch_size] - - if hasattr(backend, 'execute_batch'): - # Use native batch execution if available - batch_results = backend.execute_batch(batch) - else: - # Sequential execution fallback - batch_results = [backend.execute_circuit(c) for c in batch] - - results.extend(batch_results) - - return results +ibm = sqx.get_backend("qiskit", device="ibm_brisbane") +braket = sqx.BraketBackend( + device="arn:aws:braket:us-east-1::device/qpu/ionq/Forte-1", + s3_folder=("my-braket-bucket", "runs"), +) +ocean = sqx.get_backend("ocean", device="advantage", token="YOUR_DWAVE_LEAP_TOKEN") ``` ---- +## See Also -For detailed backend integration guides, see: -- [Qiskit Integration](../backends/qiskit.md) -- [PennyLane Integration](../backends/pennylane.md) -- [Cirq Integration](../backends/cirq.md) -- [Braket Integration](../backends/braket.md) -- [TKET Integration](../backends/tket.md) -- [Ocean Integration](../backends/ocean.md) -- [Simulator Backend](../backends/simulator.md) \ No newline at end of file +- [BACKENDS overview](../BACKENDS.md) +- [User guide](../user-guide/backends.md) +- Per-backend pages under `docs/backends/` diff --git a/docs/api/circuits.md b/docs/api/circuits.md index febe37f..28d736c 100644 --- a/docs/api/circuits.md +++ b/docs/api/circuits.md @@ -1,10 +1,10 @@ # 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). +This page covers circuit construction, gate matrices, Pauli strings and Hamiltonians, measurement results and noise channels. The usage examples at the end run on SuperQuantX 0.3.0. - -SuperQuantX provides comprehensive quantum circuit construction, manipulation, and execution capabilities. This API reference covers quantum circuits, gates, measurements, and noise modeling. +!!! info "Two kinds of circuit" + - **Backend circuits** come from `backend.create_circuit(n)` and are built with `backend.add_gate(...)` or, on the simulator, with methods such as `circuit.h(0)`. These are what `backend.execute_circuit` runs. + - **`superquantx.QuantumCircuit`** is a backend-independent circuit description that can be drawn, composed, inverted and serialised to JSON. In 0.3.0 no backend executes it directly. ## Quantum Circuits @@ -150,398 +150,207 @@ SuperQuantX provides comprehensive quantum circuit construction, manipulation, a ## Usage Examples -### Basic Circuit Construction +### Building and running a circuit ```python -import superquantx as sqx import numpy as np +import superquantx as sqx -# Create quantum circuit -circuit = sqx.QuantumCircuit(n_qubits=3, n_classical=3) - -# Add quantum gates -circuit.h(0) # Hadamard gate -circuit.cx(0, 1) # CNOT gate -circuit.ry(np.pi/4, 2) # Y-rotation +backend = sqx.get_backend('simulator') # or 'qiskit', 'pennylane', 'cirq', 'braket', 'tket' -# Add measurements -circuit.measure(0, 0) # Measure qubit 0 to classical bit 0 -circuit.measure_all() # Measure all qubits +circuit = backend.create_circuit(3) +backend.add_gate(circuit, 'H', 0) +backend.add_gate(circuit, 'CNOT', [0, 1]) +backend.add_gate(circuit, 'RY', 2, [np.pi / 4]) +backend.add_measurement(circuit) -print(circuit) +result = backend.execute_circuit(circuit, shots=1000) +print(result['counts']) # qubit 0 is the rightmost bit +print(backend.counts_big_endian(result['counts'])) # qubit 0 first ``` -### Advanced Gate Operations - -```python -from superquantx.gates import GateMatrix, PauliString - -# Custom rotation gates -theta = np.pi/3 -rx_gate = GateMatrix.rx(theta) -ry_gate = GateMatrix.ry(theta) -rz_gate = GateMatrix.rz(theta) - -# Pauli string operations -pauli_str = PauliString('XYZX') # X⊗Y⊗Z⊗X -print(f"Pauli string: {pauli_str}") -print(f"Matrix shape: {pauli_str.to_matrix().shape}") +`add_gate(circuit, gate, qubits, params=None)` uses the same gate names on every gate-model backend, so this code runs unchanged on any of them. -# Hamiltonian construction -from superquantx.gates import Hamiltonian, PauliString - -# Create Heisenberg model Hamiltonian -hamiltonian = Hamiltonian.heisenberg_model(num_qubits=4, Jx=1.0, Jy=1.0, Jz=1.0) -print(f"Hamiltonian: {hamiltonian}") - -# Time evolution -time_evolution_op = hamiltonian.time_evolution(time=0.1) -circuit.unitary(time_evolution_op, range(4)) -``` - -### Measurement Analysis +### Describing a circuit with QuantumCircuit ```python -# Execute circuit and analyze results -backend = sqx.get_backend('simulator') -result = backend.execute_circuit(circuit, shots=1000) - -# Create measurement result object -measurement = sqx.MeasurementResult( - counts=result['counts'], - shots=result['shots'], - metadata=result.get('metadata', {}) -) - -# Analyze measurements -print(f"Most frequent outcome: {measurement.most_frequent}") -print(f"Measurement probabilities: {measurement.probabilities}") - -# Marginal analysis -marginal = measurement.marginal_counts([0, 1]) # Marginalize over qubits 0,1 -print(f"Marginal counts: {marginal}") - -# Statistical analysis -entropy = measurement.measurement_entropy() -print(f"Measurement entropy: {entropy:.4f}") +qc = sqx.QuantumCircuit(3, name='ghz') +qc.h(0) +qc.cx(0, 1) +qc.cx(1, 2) +qc.ry(np.pi / 4, 2) +qc.measure_all() + +print(qc.draw()) +print("Gates:", len(qc.gates)) + +# Serialise and restore +restored = sqx.QuantumCircuit.from_json(qc.to_json()) +print("Round trip keeps gates:", len(restored.gates) == len(qc.gates)) + +# Inverse (without measurements) and composition +unitary_part = sqx.QuantumCircuit(3) +unitary_part.h(0) +unitary_part.cx(0, 1) +print(unitary_part.compose(unitary_part.inverse()).draw()) ``` -### Expectation Value Calculations +### Gate matrices, Pauli strings and Hamiltonians ```python -from superquantx.measurements import QuantumMeasurement -from superquantx.gates import PauliString - -# Create measurement system -measurement = QuantumMeasurement(backend="simulator") - -# Define observable -observable = 'ZZ' # Z⊗Z measurement - -# Calculate expectation value -exp_value = measurement.measure_observable( - circuit=circuit, - observable=observable, - shots=5000 -) +from superquantx.gates import GateMatrix, Hamiltonian, PauliString -print(f"⟨ZZ⟩ = {exp_value:.4f}") +theta = np.pi / 3 +print("RX(pi/3) =\n", np.round(GateMatrix.rx(theta), 3)) +print("H is unitary:", np.allclose(GateMatrix.H @ GateMatrix.H.conj().T, np.eye(2))) -# Multiple observables -observables = ['XX', 'YY', 'ZZ'] +pauli = PauliString('XYZX') # X (x) Y (x) Z (x) X +print("Pauli string matrix shape:", pauli.matrix().shape) +print("XYZX commutes with ZZZZ:", pauli.commutes_with(PauliString('ZZZZ'))) -exp_values = [] -for obs in observables: - val = measurement.measure_observable(circuit, obs, shots=5000) - exp_values.append(val) - print(f"⟨{obs}⟩ = {val:.4f}") +heisenberg = Hamiltonian.heisenberg_model(num_qubits=4, Jx=1.0, Jy=1.0, Jz=1.0) +print(f"Heisenberg ground-state energy: {heisenberg.ground_state_energy():.4f}") +U = heisenberg.time_evolution(time=0.1) +print("exp(-iHt) is unitary:", np.allclose(U @ U.conj().T, np.eye(16))) ``` -### Quantum State Tomography - -```python -from superquantx.measurements import QuantumMeasurement - -# Create measurement system -measurement = QuantumMeasurement(backend="simulator") - -# Perform tomography measurements -tomography_results = measurement.tomography_measurements( - circuit=circuit, - qubits=[0, 1], # Reconstruct 2-qubit state - shots_per_measurement=1000 -) - -# Reconstruct density matrix -density_matrix = measurement.reconstruct_state(tomography_results) -print(f"Reconstructed density matrix:\n{density_matrix}") - -# Calculate fidelity with target state -bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2) # |Φ⁺⟩ -fidelity = measurement.fidelity(density_matrix, bell_state) - -print(f"Fidelity with |Φ⁺⟩: {fidelity:.4f}") -print(f"State purity: {np.trace(density_matrix @ density_matrix).real:.4f}") -``` +### Measurement analysis -### Noise Modeling +`MeasurementResult` wraps a counts dictionary from any backend. ```python -from superquantx.noise import ( - NoiseModel, BitFlipChannel, PhaseFlipChannel, - DepolarizingChannel, AmplitudeDampingChannel -) - -# Create noise channels -bit_flip = BitFlipChannel(probability=0.01) -phase_flip = PhaseFlipChannel(probability=0.01) -depolarizing = DepolarizingChannel(probability=0.02) -amplitude_damping = AmplitudeDampingChannel(probability=0.05) +from superquantx.measurements import MeasurementResult + +bell = backend.create_circuit(2) +backend.add_gate(bell, 'H', 0) +backend.add_gate(bell, 'CNOT', [0, 1]) +backend.add_measurement(bell) +raw = backend.execute_circuit(bell, shots=1000) + +measurement = MeasurementResult(counts=raw['counts'], shots=raw['shots']) +print("Most frequent:", measurement.most_frequent) +print("Probabilities:", measurement.probabilities) +print("Marginal on qubit 0:", measurement.marginal_counts([0])) +print(f"Entropy: {measurement.entropy():.4f} bits") +print(f" from counts: {measurement.expectation_value('ZZ'):.4f}") +``` -# Combine into noise model -noise_model = NoiseModel() +### Exact expectation values -# Add gate-specific noise -noise_model.add_gate_noise('X', bit_flip) -noise_model.add_gate_noise('H', depolarizing) -noise_model.add_gate_noise('CNOT', phase_flip) +For exact values on the simulator, combine the statevector with a `Hamiltonian`: -# Add readout noise -noise_model.add_readout_noise( - p0_given_1=0.02, # Probability of measuring 0 given |1⟩ - p1_given_0=0.03 # Probability of measuring 1 given |0⟩ -) +```python +bell = backend.create_circuit(2) +backend.add_gate(bell, 'H', 0) +backend.add_gate(bell, 'CNOT', [0, 1]) +state = backend.statevector_big_endian(bell) -# Apply noise model to backend -noisy_backend = sqx.get_backend('simulator', noise_model=noise_model) +for label in ['XX', 'YY', 'ZZ']: + observable = Hamiltonian.from_dict({label: 1.0}) + print(f"<{label}> = {np.real(observable.expectation_value(state)):+.4f}") -# Execute noisy simulation -noisy_result = noisy_backend.execute_circuit(circuit, shots=1000) -print("Noisy simulation results:", noisy_result['counts']) +target = np.array([1, 0, 0, 1]) / np.sqrt(2) +print(f"Fidelity with |Phi+>: {abs(np.vdot(target, state)) ** 2:.4f}") ``` -### Error Mitigation - -```python -from superquantx.measurements import ResultAnalyzer +`backend.compute_expectation(circuit, hamiltonian)` gives the same numbers through the backend interface. -# Zero-noise extrapolation -noise_levels = [1, 2, 3] -measurement_results = [] - -# Collect measurements at different noise levels -for noise_level in noise_levels: - # Create noisy backend (implementation dependent) - result = measurement.measure_circuit(circuit, shots=1000) - measurement_results.append(result) - -# Perform extrapolation -zero_noise_value, fit_info = ResultAnalyzer.error_mitigation_zero_noise_extrapolation( - noise_levels=noise_levels, - measurement_results=measurement_results, - observable='Z' -) - -print(f"Zero-noise extrapolated value: {zero_noise_value:.4f}") -print(f"Fit R²: {fit_info.get('r_squared', 'N/A'):.4f}") - -# Readout error mitigation -calibration_results = {"0": result, "1": result} # Calibration measurements -corrected_result = ResultAnalyzer.readout_error_mitigation( - calibration_results=calibration_results, - measurement_result=result -) -print(f"Corrected counts: {corrected_result.counts}") -``` +### Noise channels -### Circuit Optimization +The channel classes give Kraus operators and act on density matrices. ```python -from superquantx.circuits import CircuitOptimizer - -# Create optimizer -optimizer = CircuitOptimizer( - optimization_level=2, - target_backend=backend +from superquantx.noise import ( + AmplitudeDampingChannel, DepolarizingChannel, NoiseModel, PhaseDampingChannel, ) -# Optimize circuit -optimized_circuit = optimizer.optimize(circuit) +rho_plus = np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex) # |+><+| +for channel in [DepolarizingChannel(0.1), AmplitudeDampingChannel(0.1), PhaseDampingChannel(0.1)]: + out = channel.apply_to_density_matrix(rho_plus) + purity = np.real(np.trace(out @ out)) + print(f"{type(channel).__name__:24s} purity {purity:.3f}, coherence {abs(out[0, 1]):.3f}") -print(f"Original circuit: {circuit.depth()} depth, {circuit.count_ops()} gates") -print(f"Optimized circuit: {optimized_circuit.depth()} depth, {optimized_circuit.count_ops()} gates") - -# Specific optimizations -optimized_circuit = optimizer.apply_passes([ - 'RemoveRedundantGates', - 'CombineRotations', - 'CancelInverses', - 'CommuteThroughClifford' -]) +# A NoiseModel records error rates, for example for documentation or a qiskit noise model +model = NoiseModel.basic_device_noise(single_qubit_error=0.001, two_qubit_error=0.01, readout_error=0.02) +print(model.single_qubit_error_rates, model.two_qubit_error_rates) ``` -### Parameterized Circuits - -```python -from superquantx.circuits import Parameter, ParameterVector - -# Create parameters -theta = Parameter('theta') -phi_vec = ParameterVector('phi', 3) - -# Build parameterized circuit -param_circuit = sqx.QuantumCircuit(3) - -param_circuit.ry(theta, 0) -param_circuit.rx(phi_vec[0], 1) -param_circuit.rz(phi_vec[1], 2) -param_circuit.cx(0, 1) -param_circuit.cry(phi_vec[2], 1, 2) +!!! bug "Known issue in 0.3.0" + `BitFlipChannel` and `PhaseFlipChannel` raise `AttributeError` (they reference a missing `GateMatrix.I`). `DepolarizingChannel`, `AmplitudeDampingChannel` and `PhaseDampingChannel` work. -# Bind parameters -bound_circuit = param_circuit.bind_parameters({ - theta: np.pi/4, - phi_vec: [np.pi/3, np.pi/6, np.pi/2] -}) +!!! note "Noisy simulation" + The built-in simulator is noiseless and does not apply a `NoiseModel`. For noisy circuit simulation use the Qiskit backend with an Aer noise model (see the [Qiskit backend guide](../backends/qiskit.md)). -# Execute bound circuit -result = backend.execute_circuit(bound_circuit) -``` +### Zero-noise extrapolation -### Quantum Circuit Libraries +`ResultAnalyzer.error_mitigation_zero_noise_extrapolation` fits measurements taken at several noise scale factors and extrapolates to zero noise. ```python -from superquantx.circuits.library import ( - EfficientSU2, - RealAmplitudes, - ZZFeatureMap, - PauliFeatureMap -) - -# Variational ansatz circuits -ansatz1 = EfficientSU2(num_qubits=4, reps=3) -ansatz2 = RealAmplitudes(num_qubits=4, reps=2) - -# Feature map circuits for quantum machine learning -feature_map1 = ZZFeatureMap(feature_dimension=4, reps=2) -feature_map2 = PauliFeatureMap(feature_dimension=4, reps=1) - -# Combine feature map and ansatz -ml_circuit = feature_map1.compose(ansatz1) - -# Bind training data -training_data = [0.1, 0.5, -0.3, 0.8] -bound_ml_circuit = ml_circuit.bind_parameters({ - **feature_map1.parameter_dict(training_data), - **ansatz1.random_parameters() -}) -``` - -### Circuit Simulation and Debugging +from superquantx.measurements import ResultAnalyzer -```python -from superquantx.circuits import CircuitSimulator - -# Create detailed simulator -sim = CircuitSimulator(backend='statevector') - -# Step-by-step execution -sim.initialize_circuit(circuit) - -for step, gate in enumerate(circuit.data): - print(f"Step {step}: Applying {gate}") - - # Apply gate - sim.apply_gate(gate) - - # Get current state - current_state = sim.get_statevector() - print(f" Statevector norm: {np.linalg.norm(current_state):.6f}") - - # Check entanglement - entanglement = sim.calculate_entanglement() - print(f" Entanglement entropy: {entanglement:.4f}") - -# Final state analysis -final_state = sim.get_statevector() -final_density_matrix = sim.get_density_matrix() - -print("Final state analysis:") -print(f" Purity: {np.trace(final_density_matrix @ final_density_matrix).real:.4f}") -print(f" Von Neumann entropy: {sim.von_neumann_entropy():.4f}") +# measured at noise scale factors 1, 2 and 3 (0.8, 0.6, 0.4) +results = [ + MeasurementResult(counts={'0': 900, '1': 100}, shots=1000), + MeasurementResult(counts={'0': 800, '1': 200}, shots=1000), + MeasurementResult(counts={'0': 700, '1': 300}, shots=1000), +] +value, info = ResultAnalyzer.error_mitigation_zero_noise_extrapolation([1, 2, 3], results, observable='Z') +print(f"Zero-noise estimate of : {value:.3f} (fit: {info['method']})") ``` -## Performance Optimization +### Parameterised circuits -### Circuit Compilation +There is no symbolic `Parameter` type in 0.3.0. Pass numbers when you build the circuit, or use the ansatz helpers, which take a parameter array: ```python -from superquantx.circuits import QuantumCompiler - -# Create compiler for specific backend -compiler = QuantumCompiler(target_backend=backend) +n_qubits = 3 +n_params = backend.ansatz_param_count('RealAmplitudes', n_qubits, reps=2) +params = np.random.default_rng(0).uniform(0, 2 * np.pi, n_params) -# Compile circuit -compiled_circuit = compiler.compile( - circuit=circuit, - optimization_level=3, - scheduling='as_late_as_possible', - layout='dense' -) +ansatz = backend.create_ansatz('RealAmplitudes', n_qubits, params, reps=2) +print(f"RealAmplitudes with {n_params} parameters, norm {np.linalg.norm(backend.get_statevector(ansatz)):.6f}") -# Analysis compilation results -print(f"Compilation report:") -print(f" Original gates: {circuit.count_ops()}") -print(f" Compiled gates: {compiled_circuit.count_ops()}") -print(f" Gate reduction: {(1 - compiled_circuit.count_ops()/circuit.count_ops())*100:.1f}%") +feature_map = backend.create_feature_map(n_features=3, feature_map='ZZFeatureMap', reps=2) +encoded = backend.build_feature_map_circuit(np.array([0.1, 0.5, -0.3]), feature_map) +print("Encoded state norm:", round(float(np.linalg.norm(backend.get_statevector(encoded))), 6)) ``` -### Batch Circuit Execution +### Running many circuits ```python -# Execute multiple circuits efficiently -circuits = [create_random_circuit(n_qubits=4) for _ in range(10)] - -# Parallel execution -results = backend.execute_circuits_parallel( - circuits=circuits, - shots=1000, - max_workers=4 -) - -# Batch analysis -success_rate = sum(1 for r in results if r['success']) / len(results) -avg_execution_time = np.mean([r.get('execution_time', 0) for r in results]) - -print(f"Batch execution: {success_rate*100:.1f}% success rate") -print(f"Average execution time: {avg_execution_time:.3f}s") +def random_circuit(n_qubits, depth, rng): + circuit = backend.create_circuit(n_qubits) + for _ in range(depth): + q = int(rng.integers(n_qubits)) + backend.add_gate(circuit, 'RY', q, [float(rng.uniform(0, np.pi))]) + backend.add_gate(circuit, 'CNOT', [q, (q + 1) % n_qubits]) + backend.add_measurement(circuit) + return circuit + + +rng = np.random.default_rng(1) +circuits = [random_circuit(4, 5, rng) for _ in range(10)] +results = [backend.execute_circuit(c, shots=500) for c in circuits] +print("Executed", len(results), "circuits; first counts:", results[0]['counts']) ``` +!!! note "Not available in 0.3.0" + `CircuitOptimizer`, `QuantumCompiler`, `CircuitSimulator`, `Parameter` / `ParameterVector`, the `superquantx.circuits.library` module and `execute_circuits_parallel` do not exist. `QuantumMeasurement.measure_circuit`, `measure_observable` and the tomography helpers return placeholder outcomes rather than simulating the circuit, and `ResultAnalyzer.readout_error_mitigation` returns the counts unchanged. For circuit compilation use the TKET backend (see the [TKET guide](../backends/tket.md)). + ## Best Practices ### Circuit Construction -1. **Use Native Gates**: Prefer gates supported by target backend -2. **Minimize Depth**: Reduce circuit depth for better fidelity -3. **Optimize Layout**: Consider qubit connectivity constraints -4. **Parameter Management**: Use symbolic parameters for flexibility +1. **Use native gates**: prefer gates supported by the target backend +2. **Minimise depth**: shorter circuits keep more fidelity on hardware +3. **Mind connectivity**: two-qubit gates between distant qubits cost extra swaps on hardware ### Measurement Strategy -1. **Statistical Significance**: Use sufficient shots for reliable statistics -2. **Marginal Analysis**: Focus on relevant qubit subsets -3. **Error Bars**: Always include measurement uncertainties -4. **Baseline Comparison**: Compare with theoretical expectations - -### Noise Handling - -1. **Realistic Models**: Use device-specific noise parameters -2. **Error Mitigation**: Apply appropriate mitigation techniques -3. **Validation**: Compare noisy vs. noiseless simulations -4. **Calibration**: Regularly update noise models from hardware data +1. **Use enough shots**: the standard error of a probability p is sqrt(p(1-p)/shots) +2. **Report uncertainties** next to sampled values +3. **Compare with exact values** from the statevector when the circuit is small --- -For more detailed examples and tutorials, see: -- [Circuit Construction Tutorial](../tutorials/basic-quantum.md) -- [Backend Integration](../backends/) \ No newline at end of file +For more examples see the [basic quantum computing tutorial](../tutorials/basic-quantum.md). diff --git a/docs/api/core.md b/docs/api/core.md index 6b782cb..54ba6c0 100644 --- a/docs/api/core.md +++ b/docs/api/core.md @@ -1,9 +1,5 @@ # 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 @@ -82,21 +78,13 @@ The core API provides fundamental functionality for SuperQuantX, including backe docstring_style: google show_source: true -## Quick Start Examples - -### Basic Usage +## Basic Usage ```python import superquantx as sqx -# Get version information -print(f"SuperQuantX version: {sqx.get_version()}") - -# Check available backends -backends = sqx.list_available_backends() -print(f"Available backends: {backends}") - -# Get system information +print(sqx.get_version()) +print(sqx.list_available_backends()) sqx.print_system_info() ``` @@ -105,409 +93,75 @@ sqx.print_system_info() ```python import superquantx as sqx -# Automatic backend selection -backend = sqx.get_backend('auto') - -# Specific backend with configuration -qiskit_backend = sqx.get_backend('qiskit', - device='ibmq_qasm_simulator', - shots=1000) - -# Check backend compatibility -is_compatible = sqx.check_backend_compatibility('qiskit') -print(f"Qiskit compatible: {is_compatible}") -``` - -### Configuration Management - -```python -import superquantx as sqx +backend = sqx.get_backend("auto") +print(type(backend).__name__) -# View current configuration -print("Current config:", sqx.config) - -# Update configuration -sqx.configure({ - 'default_backend': 'simulator', - 'default_shots': 1024, - 'optimization_level': 2, - 'visualization': { - 'style': 'dark', - 'dpi': 300 - } -}) +sim = sqx.get_backend("simulator", max_qubits=8, shots=512) +print(sim.get_backend_info()["backend_name"]) +print(sqx.check_backend_compatibility("qiskit")["compatible"]) ``` -## Available Backends - -SuperQuantX supports multiple quantum computing backends: - -### Hardware Backends -- **IBM Quantum** (`qiskit`): Access to IBM Quantum devices -- **Google Quantum AI** (`cirq`): Integration with Google's quantum hardware -- **Amazon Braket** (`braket`): AWS quantum computing service -- **Quantinuum** (`tket`): H-Series trapped-ion quantum computers -- **D-Wave** (`ocean`): Quantum annealing systems - -### Simulator Backends -- **Python Simulator** (`simulator`): Pure Python quantum simulation -- **Local Simulators**: High-performance local quantum simulators -- **Classical Emulation**: Classical algorithms for quantum-inspired computations - -### Example Backend Usage +### Configuration ```python import superquantx as sqx -# Initialize different backends -backends = {} +cfg = sqx.get_config() +print(sorted(cfg.keys())[:8]) -# Simulator for development -backends['sim'] = sqx.get_backend('simulator', max_qubits=10) - -# IBM Quantum for real hardware -backends['ibm'] = sqx.get_backend('qiskit', - device='ibmq_manila', - token='your-ibm-token') - -# Amazon Braket for cloud quantum computing -backends['aws'] = sqx.get_backend('braket', - device_arn='arn:aws:braket:::device/quantum-simulator/amazon/sv1', - s3_bucket='my-braket-bucket') - -# D-Wave for optimization problems -backends['dwave'] = sqx.get_backend('ocean', - device='advantage', - token='your-dwave-token') - -# Use backends -for name, backend in backends.items(): - if backend.is_available(): - info = backend.get_backend_info() - print(f"{name}: {info['provider']} - {info['device']}") +sqx.configure(backend="simulator", shots=512) +print(sqx.get_default_backend()) ``` -## Error Handling - -SuperQuantX provides comprehensive error handling for backend operations: +### Portable Circuit Across Backends ```python import superquantx as sqx -from superquantx.exceptions import QuantumBackendError - -try: - # Attempt to initialize backend - backend = sqx.get_backend('qiskit', device='fake_device') - -except QuantumBackendError as e: - print(f"Backend error: {e}") - # Fallback to simulator - backend = sqx.get_backend('simulator') - -except ImportError as e: - print(f"Missing dependency: {e}") - print("Install with: pip install superquantx[qiskit]") - -# Check backend availability -if backend.is_available(): - print("Backend ready for use") -else: - print("Backend not available, check configuration") -``` -## Advanced Configuration - -### Environment Variables - -SuperQuantX respects environment variables for configuration: - -```bash -# Default backend selection -export SUPERQUANTX_BACKEND=qiskit - -# IBM Quantum credentials -export QISKIT_IBMQ_TOKEN=your-token-here - -# AWS credentials for Braket -export AWS_ACCESS_KEY_ID=your-access-key -export AWS_SECRET_ACCESS_KEY=your-secret-key - -# D-Wave credentials -export DWAVE_API_TOKEN=your-dwave-token - -# Quantinuum credentials -export QUANTINUUM_API_KEY=your-quantinuum-key +results = {} +for name in ["simulator", "pennylane", "qiskit"]: + backend = sqx.get_backend(name) + circuit = backend.create_circuit(2) + backend.add_gate(circuit, "H", 0) + backend.add_gate(circuit, "CNOT", [0, 1]) + backend.add_measurement(circuit) + results[name] = backend.execute_circuit(circuit, shots=200)["counts"] +print(results) ``` -### Configuration Files - -Create `~/.superquantx/config.yaml` for persistent configuration: - -```yaml -default_backend: simulator -default_shots: 1024 -optimization_level: 2 - -backends: - qiskit: - token: your-ibm-token - hub: ibm-q - group: open - project: main - - braket: - s3_bucket: my-quantum-bucket - s3_prefix: experiments - - ocean: - token: your-dwave-token - solver: Advantage_system4.1 - -logging: - level: INFO - format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - -visualization: - backend: matplotlib - style: seaborn - figsize: [10, 6] - dpi: 300 -``` - -### Programmatic Configuration - -```python -import superquantx as sqx - -# Advanced configuration -config = { - 'default_backend': 'qiskit', - 'default_shots': 2048, - 'optimization': { - 'level': 3, - 'passes': ['cx_cancellation', 'commutative_cancellation'], - 'coupling_map': 'heavy_hex', - }, - 'error_mitigation': { - 'enabled': True, - 'method': 'zero_noise_extrapolation', - 'noise_factors': [1, 3, 5], - }, - 'caching': { - 'enabled': True, - 'backend': 'file', - 'ttl': 3600, # 1 hour - } -} - -sqx.configure(config) - -# Access nested configuration -print(f"Optimization level: {sqx.config.optimization.level}") -print(f"Error mitigation enabled: {sqx.config.error_mitigation.enabled}") -``` - -## Package Information - -### Metadata +### Error Handling ```python import superquantx as sqx +from superquantx.exceptions import BackendError, BackendNotAvailableError -# Package metadata -print(f"Title: {sqx.__title__}") -print(f"Description: {sqx.__description__}") -print(f"Author: {sqx.__author__}") -print(f"License: {sqx.__license__}") -print(f"URL: {sqx.__url__}") -``` - -### Version Compatibility - -SuperQuantX maintains compatibility with major quantum computing frameworks: - -| Framework | Supported Versions | Backend Class | -|-----------|-------------------|---------------| -| Qiskit | 0.45+ | `QiskitBackend` | -| PennyLane | 0.32+ | `PennyLaneBackend` | -| Cirq | 1.0+ | `CirqBackend` | -| Amazon Braket | 1.50+ | `BraketBackend` | -| TKET/Pytket | 1.20+ | `TKETBackend` | -| D-Wave Ocean | 6.0+ | `OceanBackend` | - -### Checking Dependencies - -```python -import superquantx as sqx - -# Get detailed backend information -backend_info = sqx.get_backend_info() - -for backend_name, version in backend_info.items(): - if version: - print(f"✓ {backend_name}: {version}") - else: - print(f"✗ {backend_name}: Not installed") - -# Check specific backend availability -backends_to_check = ['qiskit', 'pennylane', 'cirq', 'braket'] - -for backend in backends_to_check: - try: - test_backend = sqx.get_backend(backend) - print(f"✓ {backend}: Available") - except Exception as e: - print(f"✗ {backend}: {e}") -``` - -## Module Structure - -The core SuperQuantX package is organized as follows: - -``` -superquantx/ -├── __init__.py # Main package initialization -├── algorithms/ # Quantum algorithms and ML models -├── backends/ # Quantum backend implementations -├── datasets/ # Quantum datasets and data utilities -├── utils/ # Utility functions and tools -├── cli/ # Command-line interface -├── config.py # Configuration management -├── exceptions.py # Custom exception classes -├── logging_config.py # Logging configuration -└── version.py # Version information +try: + backend = sqx.get_backend("simulator") + print(backend.is_available() if hasattr(backend, "is_available") else True) +except (BackendError, BackendNotAvailableError, ImportError) as e: + print(type(e).__name__, e) + backend = sqx.get_backend("simulator") ``` -## Integration Examples +### Hardware Backends (credentials required) -### With Jupyter Notebooks +!!! note "Requires credentials" + IBM, AWS, D-Wave and similar constructors need accounts; not run in CI. + ```python -# Cell 1: Setup import superquantx as sqx -import numpy as np -import matplotlib.pyplot as plt - -# Configure for notebook use -sqx.configure({ - 'visualization': { - 'inline': True, - 'style': 'notebook' - } -}) - -# Cell 2: System information -sqx.print_system_info() -# Cell 3: Backend comparison -backends = ['simulator', 'qiskit'] -for backend_name in backends: - try: - backend = sqx.get_backend(backend_name) - print(f"{backend_name}: {backend.get_backend_info()}") - except Exception as e: - print(f"{backend_name}: Not available - {e}") +ibm = sqx.QiskitBackend(device="ibm_brisbane", shots=1024) +braket = sqx.BraketBackend( + device="arn:aws:braket:::device/quantum-simulator/amazon/sv1", + s3_folder=("my-braket-bucket", "runs"), +) +ocean = sqx.OceanBackend(device="advantage", token="YOUR_DWAVE_LEAP_TOKEN") ``` -### With External Libraries - -```python -import superquantx as sqx -import pandas as pd -import plotly.graph_objects as go - -# Create backend comparison dashboard -def create_backend_dashboard(): - backend_data = [] - - for backend_name in ['simulator', 'qiskit', 'cirq', 'braket']: - try: - backend = sqx.get_backend(backend_name) - info = backend.get_backend_info() - - backend_data.append({ - 'Backend': backend_name, - 'Provider': info.get('provider', 'Unknown'), - 'Available': backend.is_available(), - 'Max Qubits': info.get('capabilities', {}).get('max_qubits', 'N/A') - }) - except: - backend_data.append({ - 'Backend': backend_name, - 'Provider': 'N/A', - 'Available': False, - 'Max Qubits': 'N/A' - }) - - df = pd.DataFrame(backend_data) - - # Create interactive table - fig = go.Figure(data=[go.Table( - header=dict(values=list(df.columns)), - cells=dict(values=[df[col] for col in df.columns]) - )]) - - fig.update_layout(title="SuperQuantX Backend Status") - return fig - -# Display dashboard -dashboard = create_backend_dashboard() -dashboard.show() -``` - -## Best Practices - -### Backend Selection +## See Also -1. **Use Auto Backend for Development**: - ```python - backend = sqx.get_backend('auto') # Automatically selects best available - ``` - -2. **Specify Backend for Production**: - ```python - backend = sqx.get_backend('qiskit', device='ibmq_manila') - ``` - -3. **Check Availability Before Use**: - ```python - if backend.is_available(): - result = run_quantum_algorithm(backend) - else: - logger.warning("Backend not available, using fallback") - backend = sqx.get_backend('simulator') - ``` - -### Configuration Management - -1. **Use Environment Variables for Credentials**: - ```bash - export QISKIT_IBMQ_TOKEN=your-token - ``` - -2. **Separate Development and Production Configs**: - ```python - if os.getenv('ENVIRONMENT') == 'production': - sqx.configure(production_config) - else: - sqx.configure(development_config) - ``` - -3. **Validate Configuration**: - ```python - def validate_config(): - required_backends = ['qiskit', 'simulator'] - for backend in required_backends: - if not sqx.check_backend_compatibility(backend): - raise ValueError(f"Required backend {backend} not available") - - validate_config() - ``` - ---- - -For more detailed information about specific modules, see the dedicated API reference sections: -- [Algorithms API](algorithms.md) -- [Backends API](backends.md) -- [Circuits API](circuits.md) -- [Utilities API](utilities.md) \ No newline at end of file +- [Backends guide](../user-guide/backends.md) +- [Per-backend pages](../backends/simulator.md) +- [BACKENDS overview](../BACKENDS.md) diff --git a/docs/api/utilities.md b/docs/api/utilities.md index ff15260..51f3ff4 100644 --- a/docs/api/utilities.md +++ b/docs/api/utilities.md @@ -1,691 +1,74 @@ # 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). +Helpers for feature maps, benchmarking and entanglement measures. - -SuperQuantX provides comprehensive utility modules for optimization, visualization, benchmarking, data handling, and command-line operations. This API reference covers all utility functions and classes. - -## Optimization Utilities - -### Circuit Optimization - -::: superquantx.utils.optimization.optimize_circuit - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.optimization.optimize_parameters - handler: python - options: - docstring_style: google - show_source: true - -### Optimizers - -::: superquantx.utils.optimization.gradient_descent - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.optimization.adam_optimizer - handler: python - options: - docstring_style: google - show_source: true - -## Visualization Utilities - -### Result Visualization - -::: superquantx.utils.visualization.visualize_results - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.visualization.plot_optimization_history - handler: python - options: - docstring_style: google - show_source: true - -### Quantum State Visualization - -::: superquantx.utils.visualization.plot_circuit - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.visualization.plot_quantum_state - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.visualization.plot_bloch_sphere - handler: python - options: - docstring_style: google - show_source: true - -## Benchmarking Utilities - -### Algorithm Benchmarking - -::: superquantx.utils.benchmarking.benchmark_algorithm - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.benchmarking.benchmark_backend - handler: python - options: - docstring_style: google - show_source: true - -### Performance Analysis - -::: superquantx.utils.benchmarking.performance_metrics - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.benchmarking.compare_algorithms - handler: python - options: - docstring_style: google - show_source: true - -## Feature Mapping Utilities - -### Quantum Feature Maps - -::: superquantx.utils.feature_mapping.QuantumFeatureMap - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -::: superquantx.utils.feature_mapping.create_feature_map - handler: python - options: - docstring_style: google - show_source: true - -### Specific Feature Maps - -::: superquantx.utils.feature_mapping.pauli_feature_map - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.feature_mapping.zz_feature_map - handler: python - options: - docstring_style: google - show_source: true - -## Quantum Utilities - -### Quantum Information Measures - -::: superquantx.utils.quantum_utils.fidelity - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.quantum_utils.trace_distance - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.quantum_utils.quantum_mutual_information - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.quantum_utils.entanglement_measure - handler: python - options: - docstring_style: google - show_source: true - -## Classical Utilities - -### Machine Learning Utilities - -::: superquantx.utils.classical_utils.cross_validation - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.classical_utils.hyperparameter_search - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.classical_utils.model_selection - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.utils.classical_utils.data_splitting - handler: python - options: - docstring_style: google - show_source: true - -## Datasets - -### Quantum-Adapted Classical Datasets - -::: superquantx.datasets.load_iris_quantum - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_wine_quantum - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_digits_quantum - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_breast_cancer_quantum - handler: python - options: - docstring_style: google - show_source: true - -### Synthetic Data Generators - -::: superquantx.datasets.generate_classification_data - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.generate_regression_data - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.generate_clustering_data - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.generate_portfolio_data - handler: python - options: - docstring_style: google - show_source: true - -### Molecular Datasets - -::: superquantx.datasets.load_molecule - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_h2_molecule - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_lih_molecule - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.datasets.load_beh2_molecule - handler: python - options: - docstring_style: google - show_source: true - -### Data Preprocessing - -::: superquantx.datasets.QuantumFeatureEncoder - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - show_root_toc_entry: true - -::: superquantx.datasets.AmplitudeEncoder - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - -::: superquantx.datasets.AngleEncoder - handler: python - options: - docstring_style: google - show_source: true - show_root_heading: true - -::: superquantx.datasets.normalize_quantum_data - handler: python - options: - docstring_style: google - show_source: true - -## Command Line Interface - -### Main CLI Application - -::: superquantx.cli.main - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.create_app - handler: python - options: - docstring_style: google - show_source: true - -### CLI Commands - -::: superquantx.cli.run_algorithm - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.list_algorithms - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.list_backends - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.benchmark - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.configure - handler: python - options: - docstring_style: google - show_source: true - -::: superquantx.cli.info - handler: python - options: - docstring_style: google - show_source: true - -## Usage Examples - -### Optimization Workflow +## Feature Maps ```python -import superquantx as sqx import numpy as np +import superquantx as sqx -# Create parameterized circuit -backend = sqx.get_backend('simulator') -circuit = backend.create_circuit(4) - -# Add parameterized gates -params = sqx.Parameter('theta', shape=(8,)) -for i in range(4): - circuit = backend.add_gate(circuit, 'ry', i, [params[i]]) - -for i in range(3): - circuit = backend.add_gate(circuit, 'cx', [i, i+1]) - -for i in range(4): - circuit = backend.add_gate(circuit, 'ry', i, [params[i+4]]) - -# Define cost function -def cost_function(parameters): - bound_circuit = circuit.bind_parameters({params: parameters}) - result = backend.execute_circuit(bound_circuit) - # Calculate some cost based on measurement results - counts = result['counts'] - return -sum(int(bitstring, 2) * count for bitstring, count in counts.items()) - -# Optimize parameters -from superquantx.utils import optimize_parameters, adam_optimizer +backend = sqx.get_backend("simulator") +X = np.array([[0.1, 0.2], [0.4, 0.8], [0.7, 0.3]]) -optimal_params = optimize_parameters( - cost_function=cost_function, - initial_params=np.random.random(8) * 2 * np.pi, - optimizer=adam_optimizer(learning_rate=0.01), - max_iterations=100 -) +spec = backend.create_feature_map(n_features=2, feature_map="ZZFeatureMap", reps=1) +circuit = backend.build_feature_map_circuit(X[0], spec) +print(spec.name, backend.get_statevector(circuit).shape) -print(f"Optimal parameters: {optimal_params}") +K = backend.compute_kernel_matrix(X, X, feature_map="ZFeatureMap", shots=100) +print(np.round(K, 3)) ``` -### Visualization Example +Concrete feature-map classes also live under `superquantx.utils.feature_mapping` +(`ZFeatureMap`, `ZZFeatureMap`, …). Prefer the backend helpers above for portable +code. -```python -from superquantx.utils import visualize_results, plot_optimization_history +## Benchmarking -# Execute circuit with optimal parameters -final_circuit = circuit.bind_parameters({params: optimal_params}) -result = backend.execute_circuit(final_circuit, shots=1000) - -# Visualize measurement results -fig = visualize_results( - result['counts'], - title='Optimized Circuit Results', - plot_type='histogram' -) -fig.show() - -# Plot optimization history -history = { - 'iteration': list(range(100)), - 'cost': [cost_function(p) for p in optimization_history], - 'gradient_norm': [np.linalg.norm(g) for g in gradient_history] -} - -plot_optimization_history(history, metrics=['cost', 'gradient_norm']) -``` - -### Benchmarking Example +`sqx.benchmark_algorithm` exists in 0.3.0 but assumes `algorithm.backend` is a +dict with a `name` key. Real algorithm instances store a backend object, so the +helper raises `AttributeError` today. Time a fit yourself instead: ```python -from superquantx.utils import benchmark_algorithm, compare_algorithms - -# Define test problem -def test_classification_problem(): - X, y = sqx.datasets.load_iris_quantum() - return X[:100], y[:100] # Use subset for faster benchmarking - -# Benchmark single algorithm -qsvm_metrics = benchmark_algorithm( - algorithm_class=sqx.QuantumSVM, - problem_generator=test_classification_problem, - backend='simulator', - n_trials=5, - metrics=['accuracy', 'training_time', 'inference_time'] -) - -print("QSVM Benchmarks:") -for metric, value in qsvm_metrics.items(): - print(f" {metric}: {value:.4f} ± {qsvm_metrics[f'{metric}_std']:.4f}") - -# Compare multiple algorithms -algorithms = { - 'QSVM': sqx.QuantumSVM, - 'QNN': sqx.QuantumNN, - 'Hybrid': sqx.HybridClassifier -} - -comparison = compare_algorithms( - algorithms=algorithms, - problem_generator=test_classification_problem, - backend='simulator', - n_trials=3 -) - -# Print comparison table -print("\nAlgorithm Comparison:") -print("Algorithm | Accuracy | Training Time | Inference Time") -print("-" * 50) -for algo_name, metrics in comparison.items(): - print(f"{algo_name:9} | {metrics['accuracy']:.3f} | {metrics['training_time']:.3f}s | {metrics['inference_time']:.3f}s") -``` - -### Feature Mapping Example - -```python -from superquantx.utils import QuantumFeatureMap, zz_feature_map +import time +import numpy as np +from sklearn.datasets import make_classification +import superquantx as sqx -# Create custom feature map -feature_map = QuantumFeatureMap( - feature_dimension=4, - reps=2, - entanglement='linear', - rotation_gates=['ry', 'rz'] +X, y = make_classification( + n_samples=30, n_features=2, n_informative=2, n_redundant=0, random_state=0 ) - -# Sample data -X = np.random.random((10, 4)) - -# Encode data into quantum circuits -encoded_circuits = [] -for x in X: - circuit = feature_map.encode(x, backend=backend) - encoded_circuits.append(circuit) - -# Pre-built ZZ feature map -zz_map = zz_feature_map(feature_dimension=4, reps=2) -zz_circuit = zz_map.encode(X[0], backend=backend) - -# Calculate quantum kernel matrix -def quantum_kernel(x1, x2, feature_map, backend): - """Calculate quantum kernel between two data points.""" - circuit1 = feature_map.encode(x1, backend) - circuit2 = feature_map.encode(x2, backend) - - # Create kernel circuit: |0⟩ -> U†(x2) U(x1) |0⟩ - kernel_circuit = circuit1.compose(circuit2.inverse()) - - # Measure overlap - result = backend.execute_circuit(kernel_circuit) - prob_zero = result['counts'].get('0' * kernel_circuit.n_qubits, 0) / sum(result['counts'].values()) - - return prob_zero - -# Compute kernel matrix -kernel_matrix = np.zeros((len(X), len(X))) -for i in range(len(X)): - for j in range(i, len(X)): - kernel_val = quantum_kernel(X[i], X[j], feature_map, backend) - kernel_matrix[i, j] = kernel_val - kernel_matrix[j, i] = kernel_val - -print(f"Quantum kernel matrix shape: {kernel_matrix.shape}") +model = sqx.QuantumSVM(backend="simulator", feature_map="ZFeatureMap") +t0 = time.time() +model.fit(X, y) +acc = float(np.mean(model.predict(X) == y)) +print(f"accuracy={acc:.3f} in {time.time() - t0:.2f}s") ``` -### Dataset Usage Example +## Entanglement Measure ```python -# Load quantum-adapted datasets -X_iris, y_iris = sqx.datasets.load_iris_quantum() -X_wine, y_wine = sqx.datasets.load_wine_quantum() - -print(f"Iris dataset: {X_iris.shape} features, {len(set(y_iris))} classes") -print(f"Wine dataset: {X_wine.shape} features, {len(set(y_wine))} classes") - -# Generate synthetic data -X_synthetic, y_synthetic = sqx.datasets.generate_classification_data( - n_samples=200, - n_features=4, - n_classes=3, - n_informative=3, - n_clusters_per_class=1, - random_state=42 -) - -# Portfolio data for financial applications -portfolio_data = sqx.datasets.generate_portfolio_data( - n_assets=10, - n_time_periods=100, - correlation_structure='block', - volatility_regime='changing' -) - -print(f"Portfolio returns shape: {portfolio_data['returns'].shape}") -print(f"Risk factors: {list(portfolio_data['risk_factors'].keys())}") +import numpy as np +from superquantx.utils import entanglement_measure -# Molecular datasets for quantum chemistry -h2_data = sqx.datasets.load_h2_molecule(bond_length=0.735) -print(f"H2 molecule: {h2_data['n_qubits']} qubits, {h2_data['n_orbitals']} orbitals") -print(f"Ground state energy: {h2_data['ground_energy']:.6f} Ha") +# Bell state |00>+|11> as a 4-amplitude statevector +bell = np.array([1, 0, 0, 1], dtype=complex) / np.sqrt(2) +value = entanglement_measure(bell, subsystem_dims=(2, 2), measure="negativity") +print(value) ``` -### Data Preprocessing Example +## Dataset Helpers ```python -from superquantx.datasets import QuantumFeatureEncoder, AmplitudeEncoder, AngleEncoder - -# Amplitude encoding -amplitude_encoder = AmplitudeEncoder() -X_normalized = amplitude_encoder.fit_transform(X_iris) - -print(f"Original range: [{X_iris.min():.3f}, {X_iris.max():.3f}]") -print(f"Encoded range: [{X_normalized.min():.3f}, {X_normalized.max():.3f}]") - -# Angle encoding -angle_encoder = AngleEncoder(encoding_type='linear') -X_angles = angle_encoder.fit_transform(X_iris) - -print(f"Angle encoding shape: {X_angles.shape}") -print(f"Angle range: [{X_angles.min():.3f}, {X_angles.max():.3f}]") +import superquantx as sqx -# Quantum feature encoding with dimensionality reduction -quantum_encoder = QuantumFeatureEncoder( - target_dimension=8, # Reduce to 8 features for quantum circuit - encoding_method='pca', - normalization='standard' +X_train, X_test, y_train, y_test, meta = sqx.load_iris_quantum( + n_features=2, encoding="angle" ) - -X_quantum = quantum_encoder.fit_transform(X_iris) -print(f"Quantum encoding: {X_iris.shape} -> {X_quantum.shape}") -``` - -### Command Line Usage - -```bash -# List available algorithms -superquantx list-algorithms - -# List available backends -superquantx list-backends - -# Run algorithm from command line -superquantx run-algorithm QSVM \ - --data iris \ - --backend simulator \ - --feature-map ZZFeatureMap \ - --shots 1000 \ - --output results.json - -# Benchmark algorithms -superquantx benchmark \ - --algorithms QSVM,QNN,HybridClassifier \ - --dataset wine \ - --backend simulator \ - --trials 5 \ - --output benchmark_results.csv - -# Configure SuperQuantX -superquantx configure \ - --backend-preference "pennylane,qiskit,simulator" \ - --default-shots 1024 \ - --optimization-level 2 - -# Get system information -superquantx info --backends --versions --capabilities +print(X_train.shape, y_train.shape, meta.get("n_features")) ``` -### Quantum Information Analysis - -```python -from superquantx.utils import fidelity, trace_distance, entanglement_measure - -# Create two quantum states -backend = sqx.get_backend('simulator') - -# Bell state -bell_circuit = backend.create_circuit(2) -bell_circuit = backend.add_gate(bell_circuit, 'h', 0) -bell_circuit = backend.add_gate(bell_circuit, 'cx', [0, 1]) -bell_state = backend.get_statevector(bell_circuit) - -# Random state -random_circuit = backend.create_circuit(2) -random_circuit = backend.add_gate(random_circuit, 'ry', 0, [np.pi/3]) -random_circuit = backend.add_gate(random_circuit, 'rz', 1, [np.pi/4]) -random_state = backend.get_statevector(random_circuit) - -# Calculate quantum information measures -state_fidelity = fidelity(bell_state, random_state) -trace_dist = trace_distance(bell_state, random_state) -entanglement = entanglement_measure(bell_state) - -print(f"Fidelity: {state_fidelity:.4f}") -print(f"Trace distance: {trace_dist:.4f}") -print(f"Entanglement (Bell state): {entanglement:.4f}") -``` - -## Best Practices - -### Optimization Guidelines - -1. **Start Simple**: Begin with basic optimizers before advanced methods -2. **Monitor Convergence**: Track optimization metrics throughout training -3. **Parameter Initialization**: Use informed initial parameter guesses -4. **Early Stopping**: Implement convergence criteria to avoid overfitting - -### Visualization Standards - -1. **Consistent Styling**: Use consistent color schemes and layouts -2. **Clear Labels**: Always include axis labels and titles -3. **Error Bars**: Show confidence intervals when appropriate -4. **Interactive Plots**: Use interactive visualizations for complex data - -### Benchmarking Protocol - -1. **Multiple Trials**: Run multiple independent trials for statistical significance -2. **Controlled Environment**: Fix random seeds for reproducible results -3. **Baseline Comparison**: Always compare against classical baselines -4. **Resource Tracking**: Monitor computational resources (time, memory, shots) - -### Data Handling - -1. **Preprocessing**: Always preprocess data appropriately for quantum algorithms -2. **Validation**: Use proper train/validation/test splits -3. **Feature Scaling**: Normalize features to appropriate ranges -4. **Dimensionality**: Consider quantum-appropriate feature dimensions - ---- +## See Also -For additional examples and advanced usage patterns, see: -- [Optimization Tutorial](../user-guide/algorithms.md) -- [Benchmarking Best Practices](../user-guide/benchmarking.md) +- [Algorithms API](algorithms.md) +- [Circuits API](circuits.md) diff --git a/docs/backends/braket.md b/docs/backends/braket.md index 8220fb0..a80df1f 100644 --- a/docs/backends/braket.md +++ b/docs/backends/braket.md @@ -1,9 +1,5 @@ # 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 @@ -88,93 +84,63 @@ print(result["counts"]) # about 500 each of '00' and '11' ### Cloud Simulation +!!! note "Requires credentials" + Needs AWS credentials and an S3 bucket; checked against the 0.3.0 constructor, not run. + + ```python -# Use AWS cloud simulators +# AWS managed state-vector simulator backend = sqx.BraketBackend( - device_arn='arn:aws:braket:::device/quantum-simulator/amazon/sv1', - s3_bucket='my-braket-bucket', - s3_prefix='my-experiments', - shots=1000 + device='arn:aws:braket:::device/quantum-simulator/amazon/sv1', + s3_folder=('my-braket-bucket', 'my-experiments'), + shots=1000, ) -result = backend.run(circuit, shots=1000) -print(f"Cloud simulation results: {result.get_counts()}") +result = backend.execute_circuit(circuit, shots=1000) +print(f"Cloud simulation results: {result['counts']}") ``` ### Quantum Hardware Access +!!! note "Requires credentials" + Needs AWS credentials, Braket access in the device's region and an S3 bucket; checked against the 0.3.0 constructor, not run. + + ```python -# Access IonQ quantum computer +# Access an IonQ quantum computer ionq_backend = sqx.BraketBackend( - device_arn='arn:aws:braket:::device/qpu/ionq/ionQdevice', - s3_bucket='my-braket-bucket', - s3_prefix='ionq-experiments', - shots=100 # Reduced shots for cost control + device='arn:aws:braket:us-east-1::device/qpu/ionq/Forte-1', + s3_folder=('my-braket-bucket', 'ionq-experiments'), + shots=100, # fewer shots to control cost ) - -# Execute on real quantum hardware -try: - result = ionq_backend.run(circuit, shots=100) - print(f"IonQ hardware results: {result.get_counts()}") -except Exception as e: - print(f"Hardware execution requires active device: {e}") +result = ionq_backend.execute_circuit(circuit, shots=100) +print(f"IonQ hardware results: {result['counts']} (task {result['task_arn']})") ``` ## Device Selection ### Available Devices +!!! note "Requires credentials" + Lists devices through `AwsDevice.get_devices()`, which needs AWS credentials; not run. + + ```python def list_braket_devices(): - """List all available Braket devices.""" - - try: - from braket.aws import AwsDevice - from braket.device_schema import DeviceActionType - - print("Available Amazon Braket Devices:") - print("=" * 40) - - # Get all devices - devices = AwsDevice.get_devices() - - # Group by provider - providers = {} - for device in devices: - provider = device.provider_name - if provider not in providers: - providers[provider] = [] - providers[provider].append(device) - - for provider, device_list in providers.items(): - print(f"\n{provider}:") - for device in device_list: - status = "ONLINE" if device.is_available else "OFFLINE" - device_type = device.type.value - - print(f" {device.name} ({device_type}): {status}") - print(f" ARN: {device.arn}") - - # Show device properties - if hasattr(device, 'properties'): - props = device.properties - if hasattr(props, 'paradigm'): - if hasattr(props.paradigm, 'qubitCount'): - print(f" Qubits: {props.paradigm.qubitCount}") - if hasattr(props.paradigm, 'connectivity'): - connectivity = props.paradigm.connectivity - if hasattr(connectivity, 'fullyConnected'): - if connectivity.fullyConnected: - print(f" Connectivity: Fully connected") - else: - print(f" Connectivity: Limited") - - print() - - except ImportError: - print("Braket device listing requires: pip install amazon-braket-sdk") - except Exception as e: - print(f"Error listing devices: {e}") + """List Amazon Braket devices grouped by provider.""" + from braket.aws import AwsDevice + + providers = {} + for device in AwsDevice.get_devices(): + providers.setdefault(device.provider_name, []).append(device) + + for provider, device_list in providers.items(): + print(f"\n{provider}:") + for device in device_list: + status = "ONLINE" if device.is_available else "OFFLINE" + print(f" {device.name} ({device.type.value}): {status}") + print(f" ARN: {device.arn}") + list_braket_devices() ``` @@ -182,207 +148,107 @@ list_braket_devices() ### Device-Specific Configuration ```python -def configure_for_device(device_type='simulator'): - """Configure backend for specific device types.""" - - if device_type == 'ionq': - return sqx.BraketBackend( - device_arn='arn:aws:braket:::device/qpu/ionq/ionQdevice', - s3_bucket='my-braket-bucket', - s3_prefix='ionq-jobs', - shots=100, # Cost control - max_parallel_threads=1 - ) - - elif device_type == 'rigetti': - return sqx.BraketBackend( - device_arn='arn:aws:braket:::device/qpu/rigetti/Aspen-M-3', - s3_bucket='my-braket-bucket', - s3_prefix='rigetti-jobs', - shots=1000, - poll_timeout_seconds=86400 # 24 hours for queue - ) - - elif device_type == 'sv1': - # State vector simulator (up to 34 qubits) - return sqx.BraketBackend( - device_arn='arn:aws:braket:::device/quantum-simulator/amazon/sv1', - s3_bucket='my-braket-bucket', - s3_prefix='sv1-jobs', - shots=0 # Exact simulation - ) - - elif device_type == 'tn1': - # Tensor network simulator (up to 50 qubits) - return sqx.BraketBackend( - device_arn='arn:aws:braket:::device/quantum-simulator/amazon/tn1', - s3_bucket='my-braket-bucket', - s3_prefix='tn1-jobs', - shots=1000 - ) - - else: - # Local simulator - return sqx.BraketBackend( - device_arn='local:braket/braket.devices.LocalSimulator', - shots=1000 - ) +# Device strings understood by BraketBackend(device=...) +DEVICES = { + 'local_sv': 'local:braket/braket_sv', # free local state-vector simulator + 'local_dm': 'local:braket/braket_dm', # free local density-matrix simulator + 'sv1': 'arn:aws:braket:::device/quantum-simulator/amazon/sv1', + 'tn1': 'arn:aws:braket:::device/quantum-simulator/amazon/tn1', + 'dm1': 'arn:aws:braket:::device/quantum-simulator/amazon/dm1', + 'ionq': 'arn:aws:braket:us-east-1::device/qpu/ionq/Forte-1', +} -# Test different devices -devices = ['simulator', 'sv1', 'tn1'] -for device in devices: - try: - backend = configure_for_device(device) - print(f"✅ {device} backend configured successfully") - except Exception as e: - print(f"❌ {device} configuration failed: {e}") + +def configure_for_device(name='local_sv', shots=1000, s3_folder=None): + """Managed simulators and QPUs (ARNs) need AWS credentials and an S3 folder.""" + return sqx.BraketBackend(device=DEVICES[name], shots=shots, s3_folder=s3_folder) + + +for name in ['local_sv', 'local_dm']: + backend = configure_for_device(name) + print(f"{name}: configured, max qubits {backend.capabilities['max_qubits']}") ``` +Cloud devices are configured the same way with an ARN and `s3_folder=('bucket', 'prefix')` (requires credentials; not run here). Options such as `max_parallel_threads` or `poll_timeout_seconds` are not available on `BraketBackend` in 0.3.0. + ## Working with Circuits ### Native Braket Gates ```python +import numpy as np + + def demonstrate_braket_gates(): - """Show Braket-native gate operations.""" - + """Portable gate names on the Braket backend.""" backend = sqx.get_backend('braket') - - # Create circuit with native Braket gates - circuit = backend.create_circuit(4) - - # Single-qubit gates - circuit.h(0) # Hadamard - circuit.x(1) # Pauli-X - circuit.y(2) # Pauli-Y - circuit.z(3) # Pauli-Z - - # Rotation gates - import numpy as np - circuit.rx(np.pi/4, 0) # Rx rotation - circuit.ry(np.pi/3, 1) # Ry rotation - circuit.rz(np.pi/6, 2) # Rz rotation - - # Phase gates - circuit.s(0) # S gate - circuit.t(1) # T gate - - # Two-qubit gates - circuit.cx(0, 1) # CNOT - circuit.cz(1, 2) # Controlled-Z - circuit.swap(2, 3) # SWAP - - # Parametric gates - circuit.phaseshift(np.pi/4, 0) # Phase shift - - # Add measurements - circuit.measure_all() - - # Execute circuit - result = backend.run(circuit, shots=1000) - print(f"Braket gates demonstration: {result.get_counts()}") - + circuit = backend.create_circuit(4) # a braket.circuits.Circuit + + for gate, qubit in [('H', 0), ('X', 1), ('Y', 2), ('Z', 3), ('S', 0), ('T', 1)]: + circuit = backend.add_gate(circuit, gate, qubit) + circuit = backend.add_gate(circuit, 'RX', 0, [np.pi / 4]) + circuit = backend.add_gate(circuit, 'RY', 1, [np.pi / 3]) + circuit = backend.add_gate(circuit, 'RZ', 2, [np.pi / 6]) + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + circuit = backend.add_gate(circuit, 'CZ', [1, 2]) + circuit = backend.add_gate(circuit, 'SWAP', [2, 3]) + + # Native Braket methods work too (target first, then angle) + circuit.phaseshift(0, np.pi / 4) + + result = backend.execute_circuit(circuit, shots=1000) + print(f"Counts (qubit 0 is the leftmost bit): {result['counts']}") return circuit + demo_circuit = demonstrate_braket_gates() ``` ### Advanced Circuit Features ```python -def braket_advanced_circuits(): - """Demonstrate advanced Braket circuit features.""" - - from braket.circuits import Circuit - from braket.circuits.gates import * +def braket_advanced_circuits(seed=0): + """Native Braket circuit features: parameterised ansatz, noise and result types.""" import numpy as np - - print("Advanced Braket Circuit Features") - print("=" * 35) - - # 1. Parameterized circuits + from braket.circuits import Circuit, Noise, observables + from braket.devices import LocalSimulator + + # 1. Parameterised ansatz written directly in Braket def create_parameterized_ansatz(params, n_qubits=4, depth=2): - """Create parameterized ansatz for VQE.""" circuit = Circuit() - - param_idx = 0 - - # Initial layer + idx = 0 for i in range(n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - - # Entangling layers - for layer in range(depth): - # Two-qubit gates + circuit.ry(i, params[idx]) + idx += 1 + for _ in range(depth): for i in range(n_qubits - 1): circuit.cnot(i, i + 1) - - # Parameterized single-qubit gates for i in range(n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - circuit.rz(params[param_idx], i) - param_idx += 1 - + circuit.ry(i, params[idx]).rz(i, params[idx + 1]) + idx += 2 return circuit - - # Generate parameters - n_params = 4 + 2 * 2 * 4 # Initial + depth * 2 * qubits - params = np.random.random(n_params) * 2 * np.pi - - ansatz = create_parameterized_ansatz(params) - print(f"Parameterized ansatz created with {n_params} parameters") - - # 2. Noise modeling - def add_noise_to_circuit(circuit): - """Add noise to circuit.""" - from braket.circuits.noises import * - - noisy_circuit = circuit.copy() - - # Add depolarizing noise after each gate - for instruction in circuit.instructions: - if len(instruction.target) == 1: # Single-qubit gate - qubit = instruction.target[0] - noisy_circuit.depolarizing(qubit, probability=0.001) - elif len(instruction.target) == 2: # Two-qubit gate - for qubit in instruction.target: - noisy_circuit.depolarizing(qubit, probability=0.005) - - return noisy_circuit - - # Create test circuit and add noise - test_circuit = Circuit() - test_circuit.h(0).cnot(0, 1).ry(np.pi/4, 0) - - noisy_circuit = add_noise_to_circuit(test_circuit) - print(f"Added noise to circuit with {len(test_circuit.instructions)} instructions") - - # 3. Result types - def demonstrate_result_types(): - """Show different measurement result types.""" - from braket.circuits import observables - - circuit = Circuit() - circuit.h(0).cnot(0, 1) - - # Probability measurement - circuit.probability(target=[0, 1]) - - # Expectation value measurement - circuit.expectation(observable=observables.Z(), target=0) - - # Variance measurement - circuit.variance(observable=observables.X(), target=0) - - # Sample measurement (default) - circuit.sample(observable=observables.Z(), target=[0, 1]) - - return circuit - - result_circuit = demonstrate_result_types() - print(f"Circuit with multiple result types created") + + n_params = 4 + 2 * 2 * 4 + ansatz = create_parameterized_ansatz(np.random.default_rng(seed).random(n_params) * 2 * np.pi) + print(f"Ansatz with {n_params} parameters, depth {ansatz.depth}") + + # 2. Noise: apply depolarizing noise to every gate, run on the density-matrix simulator + bell = Circuit().h(0).cnot(0, 1) + noisy = bell.copy().apply_gate_noise(Noise.Depolarizing(probability=0.02)) + counts = LocalSimulator('braket_dm').run(noisy, shots=2000).result().measurement_counts + print(f"Noisy Bell counts: {dict(counts)}") + + # 3. Result types (exact on the state-vector simulator with shots=0) + rt = Circuit().h(0).cnot(0, 1) + rt.probability(target=[0, 1]) + rt.expectation(observable=observables.Z(), target=[0]) + rt.variance(observable=observables.X(), target=[0]) + values = LocalSimulator().run(rt, shots=0).result().values + print(f"Probabilities {values[0]}, = {values[1]:.3f}, Var(X0) = {values[2]:.3f}") + + # Any of these Braket circuits can also go through the SuperQuantX backend + print(sqx.BraketBackend().execute_circuit(bell, shots=100)['counts']) + braket_advanced_circuits() ``` @@ -461,7 +327,7 @@ def optimize_braket_usage(): def development_workflow(): """Use free local simulator for development.""" local_backend = sqx.BraketBackend( - device_arn='local:braket/braket.devices.LocalSimulator', + device='local:braket/braket_sv', shots=10000 # No cost for shots ) @@ -553,138 +419,62 @@ optimize_braket_usage() ### Classical-Quantum Integration ```python -def braket_hybrid_algorithm_example(): - """Demonstrate hybrid classical-quantum algorithm.""" - - from braket.circuits import Circuit - from braket.circuits.gates import * +def braket_hybrid_algorithm_example(seed=0): + """VQE written by hand on the Braket backend, with shot-based Pauli measurements.""" import numpy as np from scipy.optimize import minimize - - print("Hybrid Algorithm: VQE with Braket") - print("=" * 35) - - class BraketVQE: - """Variational Quantum Eigensolver using Braket.""" - - def __init__(self, hamiltonian, backend_arn='local:braket/braket.devices.LocalSimulator'): - self.hamiltonian = hamiltonian # List of (coeff, pauli_string) tuples - self.backend = sqx.BraketBackend(device_arn=backend_arn) - self.n_qubits = len(hamiltonian[0][1]) # Length of Pauli string - - def create_ansatz(self, params): - """Create variational ansatz circuit.""" - circuit = Circuit() - - param_idx = 0 - - # Initial Y rotations - for i in range(self.n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - - # Entangling layer - for i in range(self.n_qubits - 1): - circuit.cnot(i, i + 1) - - # Final rotations - for i in range(self.n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - circuit.rz(params[param_idx], i) - param_idx += 1 - - return circuit - - def measure_pauli_expectation(self, circuit, pauli_string): - """Measure expectation value of Pauli string.""" - # Convert Pauli string to measurements - measurement_circuit = circuit.copy() - - # Add basis rotations for X and Y measurements - for i, pauli in enumerate(pauli_string): - if pauli == 'X': - measurement_circuit.ry(-np.pi/2, i) # Rotate Y basis to Z - elif pauli == 'Y': - measurement_circuit.rx(np.pi/2, i) # Rotate X basis to Z - # Z measurements need no rotation - - # Add measurements - for i in range(self.n_qubits): - measurement_circuit.sample(observable=observables.Z(), target=i) - - # Execute circuit - result = self.backend.run(measurement_circuit, shots=1000) - - # Calculate expectation value (simplified) - # In practice, you'd need to properly handle the measurement results - # This is a placeholder for the actual calculation - return np.random.random() * 2 - 1 # Random value in [-1, 1] - - def compute_energy(self, params): - """Compute energy expectation value.""" - ansatz = self.create_ansatz(params) - - energy = 0.0 - for coeff, pauli_string in self.hamiltonian: - expectation = self.measure_pauli_expectation(ansatz, pauli_string) - energy += coeff * expectation - - return energy - - def optimize(self, initial_params=None, method='COBYLA', maxiter=100): - """Optimize VQE parameters.""" - if initial_params is None: - n_params = 2 * self.n_qubits + self.n_qubits # RY + RY + RZ - initial_params = np.random.random(n_params) * 2 * np.pi - - print(f"Starting VQE optimization...") - print(f" Hamiltonian terms: {len(self.hamiltonian)}") - print(f" Parameters: {len(initial_params)}") - print(f" Optimizer: {method}") - - def cost_function(params): - energy = self.compute_energy(params) - print(f" Energy: {energy:.6f}") - return energy - - result = minimize( - cost_function, - initial_params, - method=method, - options={'maxiter': maxiter} - ) - - return result - - # Example: H2 molecule Hamiltonian + + backend = sqx.BraketBackend(device='local:braket/braket_sv', shots=2000) + + # H2 Hamiltonian (STO-3G, 0.74 Angstrom) as (coefficient, Pauli string) h2_hamiltonian = [ - (-1.0523732, 'II'), # Identity - (0.39793742, 'ZI'), # Z on qubit 0 - (-0.39793742, 'IZ'), # Z on qubit 1 - (-0.01128010, 'ZZ'), # Z on both qubits - (0.18093119, 'XX') # X on both qubits + (-1.0523732, 'II'), (0.39793742, 'ZI'), (-0.39793742, 'IZ'), + (-0.01128010, 'ZZ'), (0.18093119, 'XX'), ] - - # Run VQE - vqe = BraketVQE(h2_hamiltonian) - - # Optimize (using fewer iterations for demo) - result = vqe.optimize(maxiter=5) - - print(f"\nVQE Results:") - print(f" Ground state energy: {result.fun:.6f}") - print(f" Optimization success: {result.success}") - print(f" Function evaluations: {result.nfev}") - - # Compare with classical result - classical_energy = -1.8 # Approximate H2 ground state - quantum_energy = result.fun - - if abs(quantum_energy - classical_energy) < 0.1: - print(f"✅ Quantum result close to classical expectation") - else: - print(f"⚠️ Quantum result differs from classical (normal for demo)") + n_qubits = 2 + + def create_ansatz(params): + circuit = backend.create_circuit(n_qubits) + for i in range(n_qubits): + circuit = backend.add_gate(circuit, 'RY', i, [params[i]]) + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + for i in range(n_qubits): + circuit = backend.add_gate(circuit, 'RY', i, [params[n_qubits + i]]) + return circuit + + def pauli_expectation(params, pauli): + """Rotate into the Pauli basis, sample, and average the parity.""" + circuit = create_ansatz(params) + for i, p in enumerate(pauli): + if p == 'X': + circuit = backend.add_gate(circuit, 'H', i) + elif p == 'Y': + circuit = backend.add_gate(circuit, 'RX', i, [np.pi / 2]) + counts = backend.execute_circuit(circuit)['counts'] # qubit 0 is the leftmost bit + total = sum(counts.values()) + return sum( + c * (-1) ** sum(int(bits[i]) for i, p in enumerate(pauli) if p != 'I') + for bits, c in counts.items() + ) / total + + def energy(params): + return sum( + coeff if pauli == 'II' else coeff * pauli_expectation(params, pauli) + for coeff, pauli in h2_hamiltonian + ) + + rng = np.random.default_rng(seed) + result = minimize(energy, rng.uniform(0, np.pi, 2 * n_qubits), + method='COBYLA', options={'maxiter': 60}) + + exact = sqx.Hamiltonian.from_dict({p: c for c, p in h2_hamiltonian}).ground_state_energy() + print(f"VQE energy (shots): {result.fun:.4f} exact: {exact:.4f}") + + # The built-in VQE does the same with exact expectation values + vqe = sqx.VQE(hamiltonian=sqx.Hamiltonian.from_dict({p: c for c, p in h2_hamiltonian}), + backend=backend, seed=seed) + print(f"sqx.VQE on Braket: {vqe.find_ground_state():.4f}") + braket_hybrid_algorithm_example() ``` @@ -721,14 +511,13 @@ def braket_job_management(): print(f"Attempt {attempt + 1}: Submitting job...") backend = sqx.BraketBackend( - device_arn=self.device_arn, - s3_bucket=self.s3_bucket, - s3_prefix=f'attempt_{attempt}', + device=self.device_arn, + s3_folder=(self.s3_bucket, f'attempt_{attempt}'), shots=shots ) start_time = time.time() - result = backend.run(circuit, shots=shots) + result = backend.execute_circuit(circuit, shots=shots) execution_time = time.time() - start_time # Record successful job @@ -787,8 +576,8 @@ def braket_job_management(): # Example usage executor = RobustBraketExecutor( - device_arn='local:braket/braket.devices.LocalSimulator', - s3_bucket='my-braket-experiments' # Would be real S3 bucket + device_arn='local:braket/braket_sv', # an ARN plus a real bucket for AWS + s3_bucket='my-braket-experiments' ) # Create test circuit @@ -798,7 +587,7 @@ def braket_job_management(): # Submit job with retry logic try: result = executor.submit_with_retry(test_circuit, shots=1000) - print(f"Job result: {len(result.get_counts() if hasattr(result, 'get_counts') else {})} outcomes") + print(f"Job result: {result['counts']}") except Exception as e: print(f"Final job failure: {e}") @@ -874,13 +663,12 @@ def braket_security_best_practices(): print(f"\nExample Secure Configuration:") print(f"```python") print(f"backend = sqx.BraketBackend(") - print(f" device_arn='arn:aws:braket:::device/quantum-simulator/amazon/sv1',") - print(f" s3_bucket='my-secure-braket-bucket-{{region}}-{{account}}',") - print(f" s3_prefix='quantum-experiments/{{project}}/{{date}}',") - print(f" kms_key='arn:aws:kms:region:account:key/key-id',") + print(f" device='arn:aws:braket:::device/quantum-simulator/amazon/sv1',") + print(f" s3_folder=('my-secure-braket-bucket-{{region}}-{{account}}', 'quantum-experiments/{{project}}'),") + print(f" aws_session=session, # a braket.aws.AwsSession built from a least-privilege role") print(f" shots=1000,") - print(f" tags={{'Project': 'QuantumML', 'Owner': 'TeamName'}}") print(f")") + print(f"# Encryption (KMS) and tags are set on the S3 bucket and IAM side, not on the backend") print(f"```") braket_security_best_practices() diff --git a/docs/backends/cirq.md b/docs/backends/cirq.md index a3be02f..cef7fe7 100644 --- a/docs/backends/cirq.md +++ b/docs/backends/cirq.md @@ -1,9 +1,5 @@ # 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 @@ -48,29 +44,15 @@ print(result["counts"]) # about 500 each of '00' and '11' ### Google Quantum Hardware -```python -# Note: Requires Google Quantum AI access -# This is for demonstration - actual access requires approval +!!! note "Requires credentials" + Needs `cirq-google` and Google Quantum AI processor access; checked against the 0.3.0 constructor, not run. -# Connect to Google quantum processor -try: - import cirq_google - - # Get Google quantum engine service - engine = cirq_google.get_engine() - - # Use Google processor - backend = sqx.CirqBackend( - processor_id='rainbow', # Example processor - shots=1000 - ) - - # Execute on Google hardware - result = backend.run(circuit, shots=1000) - print(f"Google quantum result: {result.get_counts()}") - -except Exception as e: - print(f"Google Quantum access requires setup: {e}") + +```python +# processor_id switches CirqBackend to cirq_google.get_engine() +backend = sqx.CirqBackend(processor_id='rainbow', shots=1000) +result = backend.execute_circuit(circuit, shots=1000) +print(f"Google quantum result: {result['counts']}") ``` ## Configuration Options @@ -78,58 +60,40 @@ except Exception as e: ### Simulator Configuration ```python -# Different Cirq simulators -simulators = { - 'simulator': 'Basic state vector simulator', - 'density_matrix_simulator': 'Density matrix with noise support', - 'sparse_simulator': 'Sparse state vector simulator', - 'clifford_simulator': 'Efficient Clifford simulation', -} - -# Create backend with specific simulator -backend = sqx.CirqBackend( - simulator='density_matrix_simulator', - shots=2048, - seed=42 -) +# CirqBackend runs on cirq.Simulator +backend = sqx.CirqBackend(device='simulator', shots=2048) -# Custom simulator configuration -backend = sqx.CirqBackend( - simulator='simulator', - shots=1000, - noise_model=None, # Custom noise model - initial_state=None, # Custom initial state - qubit_order=None # Custom qubit ordering +# For other Cirq simulators (density matrix, Clifford), use Cirq directly +import cirq + +dm_result = cirq.DensityMatrixSimulator(seed=42).simulate( + cirq.Circuit(cirq.H(cirq.LineQubit(0))) ) +print(dm_result.final_density_matrix.round(3)) ``` +`CirqBackend` takes `device`, `processor_id` and `shots`. Options such as `simulator=`, `noise_model=`, `qubits=` or `seed=` are not available in 0.3.0. + ### Advanced Configuration ```python import cirq import numpy as np -# Custom qubit layout (Google Sycamore-like) + +# Custom qubit layouts are built with Cirq directly def create_sycamore_qubits(rows=5, cols=6): - """Create Sycamore-like qubit layout.""" - qubits = [] - for row in range(rows): - for col in range(cols): - # Skip some qubits to match Sycamore pattern - if (row % 2 == 0 and col % 2 == 1) or (row % 2 == 1 and col % 2 == 0): - continue - qubits.append(cirq.GridQubit(row, col)) - return qubits - -# Create backend with custom qubits + """Sycamore-like checkerboard of GridQubits.""" + return [cirq.GridQubit(r, c) for r in range(rows) for c in range(cols) if (r + c) % 2 == 0] + + custom_qubits = create_sycamore_qubits(3, 4) -backend = sqx.CirqBackend( - qubits=custom_qubits, - simulator='simulator', - shots=1000 -) +circuit = cirq.Circuit(cirq.H(custom_qubits[0]), cirq.CNOT(custom_qubits[0], custom_qubits[1])) +# execute_circuit also accepts a plain cirq.Circuit (qubits taken in sorted order) +backend = sqx.CirqBackend(shots=1000) print(f"Custom qubit layout: {len(custom_qubits)} qubits") +print(backend.execute_circuit(circuit)['counts']) ``` ## Working with Circuits @@ -137,50 +101,31 @@ print(f"Custom qubit layout: {len(custom_qubits)} qubits") ### Circuit Construction ```python +import numpy as np + + def demonstrate_cirq_circuits(): - """Show Cirq circuit construction features.""" - + """Portable gate names on the Cirq backend.""" backend = sqx.get_backend('cirq') - - # Create circuit with 4 qubits - circuit = backend.create_circuit(4) - - # Basic single-qubit gates - circuit.h(0) # Hadamard - circuit.x(1) # Pauli-X - circuit.y(2) # Pauli-Y - circuit.z(3) # Pauli-Z - - # Rotation gates - circuit.rx(np.pi/4, 0) # X rotation - circuit.ry(np.pi/3, 1) # Y rotation - circuit.rz(np.pi/6, 2) # Z rotation - - # Phase gates - circuit.s(0) # S gate - circuit.t(1) # T gate - - # Two-qubit gates - circuit.cx(0, 1) # CNOT - circuit.cz(1, 2) # Controlled-Z - circuit.swap(2, 3) # SWAP - - # Controlled operations - circuit.cz(0, 3) # Controlled-Z - - # Add measurement - circuit.measure_all() - - # Execute circuit - result = backend.run(circuit, shots=1000) - print(f"Cirq circuit results: {result.get_counts()}") - - # Display circuit structure (if available) - try: - print("Circuit structure:") - print(circuit) - except: - print("Circuit visualization not available") + circuit = backend.create_circuit(4) # (cirq.Circuit, [LineQubit(0), ...]) + + for gate, qubit in [('H', 0), ('X', 1), ('Y', 2), ('Z', 3), ('S', 0), ('T', 1)]: + circuit = backend.add_gate(circuit, gate, qubit) + circuit = backend.add_gate(circuit, 'RX', 0, [np.pi / 4]) + circuit = backend.add_gate(circuit, 'RY', 1, [np.pi / 3]) + circuit = backend.add_gate(circuit, 'RZ', 2, [np.pi / 6]) + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + circuit = backend.add_gate(circuit, 'CZ', [1, 2]) + circuit = backend.add_gate(circuit, 'SWAP', [2, 3]) + circuit = backend.add_gate(circuit, 'CZ', [0, 3]) + + circuit = backend.add_measurement(circuit) + result = backend.execute_circuit(circuit, shots=1000) + print(f"Cirq results (qubit 0 is the leftmost bit): {result['counts']}") + + cirq_circuit, qubits = circuit + print(cirq_circuit) # native Cirq diagram + demonstrate_cirq_circuits() ``` @@ -643,88 +588,41 @@ cirq_noise_modeling() ```python def cirq_circuit_optimization(): - """Demonstrate Cirq's circuit optimization capabilities.""" - + """Cirq transformers (cirq >= 1.0) on a circuit with removable gates.""" import cirq - - print("Circuit Optimization with Cirq") - print("=" * 32) - - # Create unoptimized circuit - qubits = [cirq.GridQubit(0, i) for i in range(4)] - unoptimized_circuit = cirq.Circuit() - - # Add redundant operations that can be optimized - unoptimized_circuit.append([ - cirq.H(qubits[0]), - cirq.X(qubits[0]), # H-X can be optimized - cirq.H(qubits[0]), # H-X-H = Z-H - - cirq.Y(qubits[1]), - cirq.Y(qubits[1]), # Y-Y = I (cancels out) - - cirq.CZ(qubits[0], qubits[1]), - cirq.CZ(qubits[0], qubits[1]), # CZ-CZ = I - - cirq.SWAP(qubits[2], qubits[3]), - cirq.SWAP(qubits[2], qubits[3]), # SWAP-SWAP = I + + qubits = cirq.LineQubit.range(4) + unoptimized = cirq.Circuit([ + cirq.H(qubits[0]), cirq.X(qubits[0]), cirq.H(qubits[0]), # H X H = Z + cirq.Y(qubits[1]), cirq.Y(qubits[1]), # Y Y = I + cirq.CZ(qubits[0], qubits[1]), cirq.CZ(qubits[0], qubits[1]), + cirq.SWAP(qubits[2], qubits[3]), cirq.SWAP(qubits[2], qubits[3]), ]) - - unoptimized_circuit.append(cirq.measure_each(*qubits)) - - print("Original circuit:") - print(f" Moments: {len(unoptimized_circuit)}") - print(f" Operations: {len(list(unoptimized_circuit.all_operations()))}") - - # Apply various optimization strategies - optimizers = [ - ("Merge Single-Qubit Gates", cirq.MergeSingleQubitGates()), - ("Drop Empty Moments", cirq.DropEmptyMoments()), - ("Drop Negligible Operations", cirq.DropNegligible()), - ("Eject Z", cirq.EjectZ()), - ("Eject PhasedPaulis", cirq.EjectPhasedPaulis()), + + def stats(c): + return f"{len(c)} moments, {len(list(c.all_operations()))} operations" + + print("Original:", stats(unoptimized)) + transformers = [ + ("Merge single-qubit gates", cirq.merge_single_qubit_gates_to_phxz), + ("Merge two-qubit blocks", lambda c: cirq.optimize_for_target_gateset( + c, gateset=cirq.CZTargetGateset())), + ("Eject Z", cirq.eject_z), + ("Eject phased Paulis", cirq.eject_phased_paulis), + ("Drop negligible operations", cirq.drop_negligible_operations), + ("Drop empty moments", cirq.drop_empty_moments), ] - - current_circuit = unoptimized_circuit.copy() - - for name, optimizer in optimizers: - try: - optimizer.optimize_circuit(current_circuit) - print(f"\nAfter {name}:") - print(f" Moments: {len(current_circuit)}") - print(f" Operations: {len(list(current_circuit.all_operations()))}") - except Exception as e: - print(f" {name} failed: {e}") - - # Compare execution results - simulator = cirq.Simulator() - - # Execute original circuit - original_result = simulator.run(unoptimized_circuit, repetitions=1000) - original_counts = {} - for i in range(1000): - measurement = ''.join([str(original_result.measurements[f'{qubit}'][i][0]) for qubit in qubits]) - original_counts[measurement] = original_counts.get(measurement, 0) + 1 - - # Execute optimized circuit - optimized_result = simulator.run(current_circuit, repetitions=1000) - optimized_counts = {} - for i in range(1000): - measurement = ''.join([str(optimized_result.measurements[f'{qubit}'][i][0]) for qubit in qubits]) - optimized_counts[measurement] = optimized_counts.get(measurement, 0) + 1 - - print(f"\nExecution Results Comparison:") - print(f"Original circuit outcomes: {len(original_counts)}") - print(f"Optimized circuit outcomes: {len(optimized_counts)}") - - # Check if results are equivalent - outcomes_match = (set(original_counts.keys()) == set(optimized_counts.keys())) - print(f"Outcomes match: {outcomes_match}") - - if outcomes_match: - max_diff = max(abs(original_counts.get(outcome, 0) - optimized_counts.get(outcome, 0)) - for outcome in original_counts.keys()) - print(f"Maximum count difference: {max_diff}") + optimized = unoptimized + for name, transform in transformers: + optimized = transform(optimized) + print(f"After {name}: {stats(optimized)}") + + # The optimised circuit implements the same unitary (up to global phase) + cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent( + unoptimized, optimized, atol=1e-6 + ) + print("Equivalent: True") + cirq_circuit_optimization() ``` @@ -978,179 +876,28 @@ cirq_performance_benchmarking() ```python def cirq_quantum_ml_example(): - """Implement quantum ML using Cirq backend.""" - + """Quantum classifiers on the Cirq backend, against a classical SVM.""" from sklearn.datasets import make_moons + from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler - from sklearn.metrics import accuracy_score - import cirq - - print("Quantum ML with Cirq Backend") - print("=" * 30) - - # Generate dataset - X, y = make_moons(n_samples=100, noise=0.1, random_state=42) - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) - - # Scale features - scaler = StandardScaler() - X_train_scaled = scaler.fit_transform(X_train) - X_test_scaled = scaler.transform(X_test) - - print(f"Dataset: {len(X)} samples, {X.shape[1]} features, 2 classes") - - # Create variational quantum classifier - class CirqVariationalClassifier: - def __init__(self, n_qubits=2, n_layers=2): - self.n_qubits = n_qubits - self.n_layers = n_layers - self.qubits = [cirq.GridQubit(0, i) for i in range(n_qubits)] - self.n_params = n_qubits * n_layers * 2 # RY and RZ per qubit per layer - self.params = np.random.random(self.n_params) * 2 * np.pi - - def create_ansatz(self, x_data, params): - """Create variational ansatz circuit.""" - circuit = cirq.Circuit() - - # Data encoding - for i, xi in enumerate(x_data[:self.n_qubits]): - circuit.append(cirq.ry(np.pi * xi)(self.qubits[i])) - - # Variational layers - param_idx = 0 - for layer in range(self.n_layers): - # Parameterized rotations - for i in range(self.n_qubits): - circuit.append(cirq.ry(params[param_idx])(self.qubits[i])) - param_idx += 1 - circuit.append(cirq.rz(params[param_idx])(self.qubits[i])) - param_idx += 1 - - # Entangling gates - if layer < self.n_layers - 1: - for i in range(self.n_qubits - 1): - circuit.append(cirq.CZ(self.qubits[i], self.qubits[i + 1])) - - return circuit - - def measure_expectation(self, x_data, params): - """Measure expectation value for classification.""" - circuit = self.create_ansatz(x_data, params) - - # Add measurement - circuit.append(cirq.measure(self.qubits[0], key='measurement')) - - simulator = cirq.Simulator() - result = simulator.run(circuit, repetitions=1000) - - # Calculate expectation value of first qubit - measurements = result.measurements['measurement'] - expectation = np.mean(1 - 2 * measurements) # Convert {0,1} to {1,-1} - - return expectation - - def predict_single(self, x_data, params=None): - """Predict single sample.""" - if params is None: - params = self.params - - expectation = self.measure_expectation(x_data, params) - return 1 if expectation > 0 else 0 - - def cost_function(self, params, X, y): - """Cost function for training.""" - predictions = [] - for xi in X: - pred = self.predict_single(xi, params) - predictions.append(pred) - - # Binary cross-entropy loss - predictions = np.array(predictions, dtype=float) - y = np.array(y, dtype=float) - - # Add small epsilon to prevent log(0) - epsilon = 1e-10 - predictions = np.clip(predictions, epsilon, 1 - epsilon) - - loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) - return loss - - def train(self, X, y, epochs=30, learning_rate=0.1): - """Train using parameter-shift rule.""" - print(f"Training VQC for {epochs} epochs...") - - cost_history = [] - - for epoch in range(epochs): - # Compute gradients using parameter-shift rule - gradients = np.zeros_like(self.params) - - for i in range(len(self.params)): - # Forward shift - params_plus = self.params.copy() - params_plus[i] += np.pi / 2 - cost_plus = self.cost_function(params_plus, X, y) - - # Backward shift - params_minus = self.params.copy() - params_minus[i] -= np.pi / 2 - cost_minus = self.cost_function(params_minus, X, y) - - # Parameter-shift gradient - gradients[i] = (cost_plus - cost_minus) / 2 - - # Update parameters - self.params = self.params - learning_rate * gradients - - # Record cost - current_cost = self.cost_function(self.params, X, y) - cost_history.append(current_cost) - - if epoch % 10 == 0: - print(f" Epoch {epoch}: Cost = {current_cost:.4f}") - - return cost_history - - def predict(self, X): - """Predict multiple samples.""" - predictions = [] - for xi in X: - pred = self.predict_single(xi) - predictions.append(pred) - return np.array(predictions) - - # Create and train classifier - vqc = CirqVariationalClassifier(n_qubits=2, n_layers=2) - cost_history = vqc.train(X_train_scaled, y_train, epochs=25, learning_rate=0.3) - - # Make predictions - train_pred = vqc.predict(X_train_scaled) - test_pred = vqc.predict(X_test_scaled) - - train_acc = accuracy_score(y_train, train_pred) - test_acc = accuracy_score(y_test, test_pred) - - print(f"\nResults:") - print(f"Training Accuracy: {train_acc:.3f}") - print(f"Test Accuracy: {test_acc:.3f}") - - # Compare with classical ML from sklearn.svm import SVC - classical_svm = SVC(kernel='rbf') - classical_svm.fit(X_train_scaled, y_train) - classical_pred = classical_svm.predict(X_test_scaled) - classical_acc = accuracy_score(y_test, classical_pred) - - print(f"Classical SVM Accuracy: {classical_acc:.3f}") - - # Performance comparison - if test_acc > classical_acc: - print("✅ Quantum classifier outperforms classical!") - elif test_acc > classical_acc - 0.05: - print("🤔 Quantum classifier is competitive") - else: - print("📈 Classical method currently better") + + X, y = make_moons(n_samples=60, noise=0.1, random_state=42) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) + scaler = StandardScaler().fit(X_train) + X_train, X_test = scaler.transform(X_train), scaler.transform(X_test) + + models = { + 'QuantumSVM (cirq)': sqx.QuantumSVM(backend='cirq', feature_map='ZFeatureMap'), + 'QuantumNN (cirq)': sqx.QuantumNN(backend='cirq', n_layers=2, learning_rate=0.1, + max_epochs=15, seed=0), + 'Classical SVM': SVC(kernel='rbf'), + } + for name, model in models.items(): + model.fit(X_train, y_train) + print(f"{name}: test accuracy {accuracy_score(y_test, model.predict(X_test)):.3f}") + cirq_quantum_ml_example() ``` @@ -1164,61 +911,43 @@ cirq_quantum_ml_example() import cirq import numpy as np + class CirqUtils: """Utility functions for Cirq backend operations.""" - + @staticmethod def create_grid_qubits(rows, cols): - """Create grid qubit layout.""" return [cirq.GridQubit(r, c) for r in range(rows) for c in range(cols)] - + @staticmethod def create_line_qubits(n): - """Create line qubit layout.""" return [cirq.LineQubit(i) for i in range(n)] - + @staticmethod def create_connectivity_map(qubits, topology='linear'): - """Create qubit connectivity map.""" connections = [] - if topology == 'linear': - for i in range(len(qubits) - 1): - connections.append((qubits[i], qubits[i + 1])) - + connections = [(qubits[i], qubits[i + 1]) for i in range(len(qubits) - 1)] elif topology == 'circular': - for i in range(len(qubits)): - connections.append((qubits[i], qubits[(i + 1) % len(qubits)])) - + connections = [(qubits[i], qubits[(i + 1) % len(qubits)]) for i in range(len(qubits))] elif topology == 'grid': - # Assumes qubits are GridQubits for qubit in qubits: - if isinstance(qubit, cirq.GridQubit): - neighbors = [ - cirq.GridQubit(qubit.row + dr, qubit.col + dc) - for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)] - ] - for neighbor in neighbors: - if neighbor in qubits and (qubit, neighbor) not in connections: - connections.append((qubit, neighbor)) - + for dr, dc in [(0, 1), (1, 0)]: + neighbor = cirq.GridQubit(qubit.row + dr, qubit.col + dc) + if neighbor in qubits: + connections.append((qubit, neighbor)) return connections - + @staticmethod - def optimize_circuit_for_device(circuit, device_connectivity): - """Optimize circuit for specific device connectivity.""" - # Apply basic optimizations - optimizers = [ - cirq.MergeSingleQubitGates(), - cirq.DropEmptyMoments(), - cirq.DropNegligible() - ] - - optimized_circuit = circuit.copy() - for optimizer in optimizers: - optimizer.optimize_circuit(optimized_circuit) - - return optimized_circuit + def optimize_circuit(circuit): + """Basic optimisation with Cirq transformers.""" + circuit = cirq.merge_single_qubit_gates_to_phxz(circuit) + circuit = cirq.drop_negligible_operations(circuit) + return cirq.drop_empty_moments(circuit) + + +grid = CirqUtils.create_grid_qubits(2, 2) +print(len(CirqUtils.create_connectivity_map(grid, 'grid'))) # 4 edges ``` ### Error Handling @@ -1274,7 +1003,7 @@ def robust_cirq_execution(circuit, simulator_type='Simulator', max_retries=3): *Cirq's integration with SuperQuantX brings Google's quantum computing expertise to your applications. With its focus on NISQ algorithms and flexible circuit construction, Cirq is ideal for near-term quantum applications and research.* !!! tip "Circuit Optimization" - Use Cirq's moment structure and optimization passes to create efficient circuits. The `MergeSingleQubitGates` optimizer can significantly reduce circuit depth. + Use Cirq's moment structure and optimization passes to create efficient circuits. Transformers such as `cirq.merge_single_qubit_gates_to_phxz` can significantly reduce circuit depth. !!! warning "Memory Scaling" Density matrix simulation scales as O(4^n) in memory. For circuits with >10 qubits, prefer state vector simulation when possible. diff --git a/docs/backends/ocean.md b/docs/backends/ocean.md index b85df43..6b279db 100644 --- a/docs/backends/ocean.md +++ b/docs/backends/ocean.md @@ -1,1182 +1,141 @@ # 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. +D-Wave Ocean targets quantum annealing and classical simulated annealing. +Problems are QUBO or Ising models, not gate-model circuits. ## Overview -The Ocean backend in SuperQuantX provides: +`OceanBackend` provides: -- **Quantum Annealing**: Access to D-Wave's quantum annealing processors -- **QUBO/Ising Solving**: Direct support for optimization problem formulations -- **Hybrid Algorithms**: Classical-quantum hybrid problem solving -- **Simulated Annealing**: Local testing without quantum hardware -- **Optimization Problems**: Built-in solvers for common combinatorial problems -- **Embedding**: Automatic minor-embedding for hardware constraints +- Local simulated annealing (`device='simulator'`) for offline work +- D-Wave Advantage / hybrid solvers when a Leap token is configured +- Helpers for MaxCut, TSP and generic QUBO / Ising problems -!!! note "Quantum Annealing vs Gate Model" - D-Wave systems are quantum annealers, not gate-model quantum computers. They excel at optimization problems but don't run traditional quantum circuits. +Gate-model methods such as `add_gate` / `execute_circuit` are not meaningful +on this backend. ## Installation -### Basic Ocean Installation - ```bash -# Install D-Wave Ocean SDK -pip install dwave-ocean-sdk - -# Install SuperQuantX with Ocean support uv add "superquantx[ocean]==0.3.0" ``` -### Extended Ocean Tools - -```bash -# Additional D-Wave tools -pip install dwave-inspector # Problem visualization -pip install dwave-preprocessing # Problem preprocessing -pip install dwave-hybrid # Hybrid algorithms -pip install minorminer # Advanced embedding - -# For graph problems -pip install networkx -``` - ### Verify Installation ```python import superquantx as sqx -# Check Ocean availability -backend = sqx.get_backend('ocean') +backend = sqx.get_backend("ocean", device="simulator") print(backend.get_version_info()) +print(backend.is_available()) ``` ## Quick Start -### Basic QUBO Problem +### QUBO on the Local Simulator ```python import superquantx as sqx -# Initialize Ocean backend (simulator) -backend = sqx.get_backend('ocean', device='simulator') +backend = sqx.get_backend("ocean", device="simulator") -# Define a simple QUBO problem -# Minimize: x₀ - 2x₁ + x₀x₁ +# Minimise x0 - 2 x1 + x0 x1 Q = { - (0, 0): 1, # x₀ term - (1, 1): -2, # x₁ term - (0, 1): 1 # x₀x₁ term + (0, 0): 1, + (1, 1): -2, + (0, 1): 1, } -# Solve the problem result = backend.solve_qubo(Q, num_reads=1000) - -print("Best solution:") -print("Variables:", result['samples'][0]) -print("Energy:", result['energies'][0]) -print("Occurrences:", result['num_occurrences'][0]) +print(result["samples"][0], result["energies"][0]) ``` -### Basic Ising Model +### Ising Model ```python -# Define Ising model: H = ∑h_i*s_i + ∑J_ij*s_i*s_j -h = {0: -1, 1: -1} # Linear terms (bias) -J = {(0, 1): -1} # Quadratic terms (coupling) +import superquantx as sqx -result = backend.solve_ising(h, J, num_reads=1000) +backend = sqx.get_backend("ocean", device="simulator") +h = {0: -1, 1: -1} +J = {(0, 1): -1} -print("Ising solution:") -for i, sample in enumerate(result['samples'][:3]): - print(f"Solution {i+1}: {sample}, Energy: {result['energies'][i]}") +result = backend.solve_ising(h, J, num_reads=1000) +for sample, energy in zip(result["samples"][:3], result["energies"][:3]): + print(sample, energy) ``` ## Configuration -### Backend Initialization Options +### Local Simulator ```python -# Local simulator (no hardware required) -backend = sqx.OceanBackend(device='simulator', shots=1000) +import superquantx as sqx -# D-Wave Advantage hardware -backend = sqx.OceanBackend( - device='advantage', - token='your-dwave-leap-token', - shots=100 # Called "num_reads" in D-Wave -) +backend = sqx.OceanBackend(device="simulator", shots=1000) +print(backend.get_device_info()) +``` + +### D-Wave Hardware and Hybrid + +!!! note "Requires credentials" + Needs a D-Wave Leap API token. Checked against the 0.3.0 constructor, not run. + + +```python +import superquantx as sqx -# D-Wave Hybrid solver (classical-quantum hybrid) -backend = sqx.OceanBackend( - device='hybrid', - token='your-token', - shots=1 +# Advantage QPU +advantage = sqx.OceanBackend( + device="advantage", + token="YOUR_DWAVE_LEAP_TOKEN", + shots=100, ) -# Specific solver selection -backend = sqx.OceanBackend( - device='advantage', - solver='Advantage_system4.1', - token='your-token' +# Hybrid solver +hybrid = sqx.OceanBackend( + device="hybrid", + token="YOUR_DWAVE_LEAP_TOKEN", + shots=1, ) ``` -### Environment Configuration +Set the token via the environment if you prefer: ```bash -# Set up D-Wave Leap credentials export DWAVE_API_TOKEN="your-api-token-here" - -# Configure default endpoint -export DWAVE_API_ENDPOINT="https://cloud.dwavesys.com/sapi" - -# Set solver preferences -export DWAVE_DEFAULT_SOLVER="Advantage_system4.1" ``` -### Configuration File +Optional D-Wave config file (`~/.dwave/config`): -```python -# ~/.dwave/config +```ini [defaults] endpoint = https://cloud.dwavesys.com/sapi token = your-api-token-here solver = Advantage_system4.1 ``` -## Hardware Integration - -### D-Wave Quantum Annealers - -D-Wave offers several quantum annealing systems: - -```python -# Advantage Systems (5000+ qubits) -backend_advantage = sqx.OceanBackend( - device='advantage', - solver='Advantage_system4.1', # or Advantage_system6.1 - token='your-token' -) - -# Check available solvers -from dwave.system import DWaveSampler -sampler = DWaveSampler(token='your-token') -available_solvers = sampler.client.get_solvers() - -for solver in available_solvers: - print(f"Solver: {solver['id']}") - print(f"Qubits: {len(solver['properties']['qubits'])}") - print(f"Topology: {solver['properties']['topology']['type']}") - print("---") -``` - -### Hardware Topologies - -D-Wave systems use specific qubit connectivity patterns: - -```python -def analyze_hardware_topology(backend): - """Analyze D-Wave hardware topology.""" - - if hasattr(backend._sampler, 'properties'): - props = backend._sampler.properties - - # Get qubit connectivity - qubits = props['qubits'] - couplers = props['couplers'] - - print(f"Active qubits: {len(qubits)}") - print(f"Active couplers: {len(couplers)}") - - # Analyze topology - if 'topology' in props: - topology = props['topology'] - print(f"Topology: {topology['type']}") - if topology['type'] == 'pegasus': - print(f"Pegasus P{topology['shape'][0]} topology") - elif topology['type'] == 'zephyr': - print(f"Zephyr Z{topology['shape'][0]} topology") - - return props - -# Analyze current hardware -if backend.device_name != 'simulator': - topology_info = analyze_hardware_topology(backend) -``` - -### Cost Management for Hardware - -```python -def cost_aware_solving(backend, problem, budget_reads=1000): - """Solve problem with cost awareness.""" - - # Start with small sample for testing - test_reads = 10 - test_result = backend.solve_qubo(problem, num_reads=test_reads) - - if not test_result['success']: - print("Test run failed, aborting") - return test_result - - # Analyze solution quality - energies = test_result['energies'] - best_energy = min(energies) - energy_spread = max(energies) - min(energies) - - print(f"Test run: Best energy = {best_energy}, Spread = {energy_spread}") - - # Determine optimal read count based on test - if energy_spread < 0.1: - # Problem seems easy, fewer reads needed - optimal_reads = min(100, budget_reads) - else: - # Problem seems hard, use more reads - optimal_reads = budget_reads - - print(f"Running {optimal_reads} reads on hardware") - final_result = backend.solve_qubo(problem, num_reads=optimal_reads) - - return final_result -``` - -## Problem Formulations - -### QUBO Problems - -QUBO (Quadratic Unconstrained Binary Optimization) problems have the form: -minimize x^T Q x where x ∈ {0,1}^n - -```python -def formulate_number_partitioning(numbers): - """Formulate number partitioning as QUBO.""" - n = len(numbers) - S = sum(numbers) - - # QUBO formulation for minimizing |∑x_i*numbers[i] - S/2|² - Q = {} - - for i in range(n): - for j in range(n): - if i == j: - Q[(i, i)] = (numbers[i] - S/2) ** 2 - else: - Q[(i, j)] = Q.get((i, j), 0) + numbers[i] * numbers[j] - - return Q - -# Example: Partition {3, 1, 1, 2, 2, 1} -numbers = [3, 1, 1, 2, 2, 1] -Q = formulate_number_partitioning(numbers) -result = backend.solve_qubo(Q) - -print("Partition result:") -partition_0 = [numbers[i] for i, x in result['samples'][0].items() if x == 0] -partition_1 = [numbers[i] for i, x in result['samples'][0].items() if x == 1] -print(f"Set 0: {partition_0} (sum: {sum(partition_0)})") -print(f"Set 1: {partition_1} (sum: {sum(partition_1)})") -``` - -### Ising Model Problems - -Ising models have the form: E = ∑h_i*s_i + ∑J_ij*s_i*s_j where s_i ∈ {-1,+1} - -```python -def create_frustrated_ising_model(size=3): - """Create a frustrated triangular Ising model.""" - h = {} # No external fields - J = {} # Antiferromagnetic interactions - - # Triangle with antiferromagnetic couplings - for i in range(size): - for j in range(i+1, size): - J[(i, j)] = 1 # Positive coupling = antiferromagnetic - - return h, J - -# Solve frustrated system -h, J = create_frustrated_ising_model(4) -result = backend.solve_ising(h, J) - -print("Frustrated Ising solutions:") -for i, sample in enumerate(result['samples'][:5]): - spins = [sample[j] for j in sorted(sample.keys())] - print(f"Solution {i+1}: {spins}, Energy: {result['energies'][i]}") -``` - -### Constraint Handling - -```python -def add_equality_constraint(Q, variables, target_sum, penalty=10.0): - """Add equality constraint to QUBO: ∑x_i = target_sum.""" - - # Constraint: (∑x_i - target_sum)² = penalty - n = len(variables) - - # Expand (∑x_i - target_sum)² - for i in variables: - Q[(i, i)] = Q.get((i, i), 0) + penalty - - for i in variables: - for j in variables: - if i != j: - Q[(i, j)] = Q.get((i, j), 0) + penalty - - # Linear terms from -2*target_sum*∑x_i - for i in variables: - Q[(i, i)] = Q.get((i, i), 0) - 2 * penalty * target_sum - - # Constant term (target_sum)² is not needed in QUBO dict - - return Q - -# Example: Constrained knapsack problem -def constrained_knapsack(values, weights, capacity): - """Knapsack with capacity constraint.""" - n = len(values) - - # Maximize value (minimize negative value) - Q = {} - for i in range(n): - Q[(i, i)] = -values[i] - - # Add capacity constraint with penalty - penalty = max(values) * 2 # Strong penalty - - # Constraint: ∑weights[i]*x_i ≤ capacity - # Convert to equality by adding slack variables - # This is a simplified version - full implementation needs slack variables - - for i in range(n): - Q[(i, i)] = Q.get((i, i), 0) + penalty * weights[i] ** 2 - - for i in range(n): - for j in range(i+1, n): - Q[(i, j)] = penalty * weights[i] * weights[j] - - return Q - -# Solve constrained knapsack -values = [10, 40, 30, 50] -weights = [5, 4, 6, 3] -capacity = 10 - -Q = constrained_knapsack(values, weights, capacity) -result = backend.solve_qubo(Q) -print("Knapsack solution:", result['samples'][0]) -``` - -## Advanced Features - -### Hybrid Quantum-Classical Algorithms - -```python -def hybrid_decomposition(backend, large_problem, subproblem_size=100): - """Decompose large problem for hybrid solving.""" - - if backend.device_name != 'hybrid': - print("Switching to hybrid sampler for large problem") - backend = sqx.OceanBackend(device='hybrid', token=backend.token) - - # For very large problems, use D-Wave's hybrid solvers - result = backend.solve_qubo(large_problem, time_limit=60) - - return result - -# Example: Large random QUBO -def generate_random_qubo(n_vars, density=0.1): - """Generate random QUBO problem.""" - import random - - Q = {} - num_terms = int(n_vars * (n_vars + 1) * density / 2) - - for _ in range(num_terms): - i = random.randint(0, n_vars - 1) - j = random.randint(i, n_vars - 1) - Q[(i, j)] = random.uniform(-1, 1) - - return Q - -# Solve large problem with hybrid approach -large_Q = generate_random_qubo(1000, density=0.05) -hybrid_result = hybrid_decomposition(backend, large_Q) -``` - -### Problem Preprocessing - -```python -from dwave.preprocessing import ScaleComposite, FixVariablesComposite - -def preprocess_problem(backend, Q, preprocessing_steps=None): - """Apply preprocessing to improve problem solving.""" - - preprocessing_steps = preprocessing_steps or ['scale', 'roof_dual'] - - # Wrap sampler with preprocessing - sampler = backend._sampler - - if 'scale' in preprocessing_steps: - # Scale problem for better numerical properties - sampler = ScaleComposite(sampler) - - if 'fix_variables' in preprocessing_steps: - # Fix variables using preprocessing heuristics - sampler = FixVariablesComposite(sampler) - - # Create BQM and solve - import dimod - bqm = dimod.BinaryQuadraticModel.from_qubo(Q) - sampleset = sampler.sample(bqm, num_reads=1000) - - return backend._convert_sampleset(sampleset, 'QUBO') - -# Example with preprocessing -Q = generate_random_qubo(50, density=0.2) -preprocessed_result = preprocess_problem(backend, Q) -``` - -### Minor Embedding - -```python -def analyze_embedding(backend, problem): - """Analyze embedding quality for D-Wave hardware.""" - - if backend.device_name == 'simulator': - print("Embedding not relevant for simulator") - return - - import dimod - from minorminer import find_embedding - - # Get hardware topology - if hasattr(backend._sampler, 'target_graph'): - target_graph = backend._sampler.target_graph - else: - print("Cannot access target graph") - return - - # Create problem graph - bqm = dimod.BinaryQuadraticModel.from_qubo(problem) - source_graph = bqm.binary.to_networkx_graph() - - # Find embedding - embedding = find_embedding(source_graph, target_graph) - - if embedding: - # Analyze embedding quality - chain_lengths = [len(chain) for chain in embedding.values()] - avg_chain_length = sum(chain_lengths) / len(chain_lengths) - max_chain_length = max(chain_lengths) - - print(f"Embedding found:") - print(f" Average chain length: {avg_chain_length:.2f}") - print(f" Maximum chain length: {max_chain_length}") - print(f" Total physical qubits used: {sum(chain_lengths)}") - - return embedding - else: - print("No embedding found - problem may be too large or dense") - return None - -# Test embedding for medium problem -medium_Q = generate_random_qubo(20, density=0.3) -embedding = analyze_embedding(backend, medium_Q) -``` - -## Common Optimization Problems +## Built-in Problems -### Maximum Cut Problem +### MaxCut ```python -def solve_max_cut_problem(backend, graph_edges, visualize=False): - """Solve Maximum Cut problem.""" - - # Use built-in max cut solver - result = backend.solve_max_cut(graph_edges) - - if result['success']: - best_cut = result['samples'][0] - - # Calculate cut value - cut_value = 0 - for u, v in graph_edges: - if best_cut.get(u, 0) != best_cut.get(v, 0): - cut_value += 1 - - print(f"Maximum cut value: {cut_value} out of {len(graph_edges)} edges") - - # Show partition - set_0 = [node for node, val in best_cut.items() if val == 0] - set_1 = [node for node, val in best_cut.items() if val == 1] - - print(f"Partition 0: {set_0}") - print(f"Partition 1: {set_1}") - - if visualize: - try: - import matplotlib.pyplot as plt - import networkx as nx - - # Create and visualize graph - G = nx.Graph(graph_edges) - pos = nx.spring_layout(G) - - # Color nodes by partition - colors = ['red' if best_cut.get(node, 0) == 0 else 'blue' - for node in G.nodes()] - - plt.figure(figsize=(10, 6)) - nx.draw(G, pos, node_color=colors, with_labels=True) - plt.title(f"Maximum Cut Solution (Cut Value: {cut_value})") - plt.show() - - except ImportError: - print("Visualization requires matplotlib and networkx") - - return result - -# Example: Solve Max Cut on a small graph -edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)] -max_cut_result = solve_max_cut_problem(backend, edges, visualize=True) -``` - -### Traveling Salesman Problem - -```python -def solve_tsp_simplified(backend, cities, distance_func=None): - """Solve simplified TSP formulation.""" - - n = len(cities) - - # Calculate distance matrix - if distance_func is None: - # Euclidean distance for 2D coordinates - distance_matrix = np.zeros((n, n)) - for i, city_i in enumerate(cities): - for j, city_j in enumerate(cities): - if i != j: - dx = city_i[0] - city_j[0] - dy = city_i[1] - city_j[1] - distance_matrix[i, j] = np.sqrt(dx*dx + dy*dy) - else: - distance_matrix = np.array([[distance_func(cities[i], cities[j]) - for j in range(n)] for i in range(n)]) - - # Use built-in TSP solver (simplified) - result = backend.solve_tsp(distance_matrix) - - if result['success']: - # Interpret solution (this is problem-specific) - print("TSP solution found (simplified formulation)") - print("Note: Full TSP requires more sophisticated constraint handling") - - return result - -# Example cities (2D coordinates) -cities = [(0, 0), (1, 2), (3, 1), (2, 3), (4, 0)] -tsp_result = solve_tsp_simplified(backend, cities) -``` - -### Graph Coloring - -```python -def solve_graph_coloring(backend, edges, num_colors=3): - """Solve graph coloring problem as QUBO.""" - - # Determine number of nodes - nodes = set() - for u, v in edges: - nodes.add(u) - nodes.add(v) - nodes = sorted(list(nodes)) - n_nodes = len(nodes) - - # Variables: x_{i,c} = 1 if node i has color c - # Total variables: n_nodes * num_colors - - Q = {} - penalty = 10 # Constraint penalty - - # Constraint 1: Each node must have exactly one color - for node in nodes: - for c1 in range(num_colors): - for c2 in range(num_colors): - var1 = node * num_colors + c1 - var2 = node * num_colors + c2 - - if c1 == c2: - Q[(var1, var1)] = Q.get((var1, var1), 0) + penalty - else: - Q[(var1, var2)] = Q.get((var1, var2), 0) + penalty - - # Linear term from (∑x_{i,c} - 1)² - for c in range(num_colors): - var = node * num_colors + c - Q[(var, var)] = Q.get((var, var), 0) - 2 * penalty - - # Constraint 2: Adjacent nodes cannot have the same color - for u, v in edges: - for c in range(num_colors): - var_u = u * num_colors + c - var_v = v * num_colors + c - Q[(var_u, var_v)] = Q.get((var_u, var_v), 0) + penalty - - # Solve QUBO - result = backend.solve_qubo(Q) - - if result['success']: - # Decode solution - best_sample = result['samples'][0] - coloring = {} - - for node in nodes: - for c in range(num_colors): - var = node * num_colors + c - if best_sample.get(var, 0) == 1: - coloring[node] = c - break - - print(f"Graph coloring with {num_colors} colors:") - for node, color in coloring.items(): - print(f"Node {node}: Color {color}") - - # Verify solution - valid = True - for u, v in edges: - if coloring.get(u) == coloring.get(v): - print(f"Constraint violation: nodes {u} and {v} have same color") - valid = False - - if valid: - print("Valid coloring found!") - - return result - -# Example: Color a small graph -edges = [(0, 1), (1, 2), (2, 0), (1, 3), (2, 3)] -coloring_result = solve_graph_coloring(backend, edges, num_colors=3) -``` - -## Performance Optimization - -### Annealing Parameters - -```python -def optimize_annealing_schedule(backend, problem, test_schedules=None): - """Optimize annealing schedule for better results.""" - - if backend.device_name == 'simulator': - print("Annealing schedule optimization not applicable for simulator") - return - - test_schedules = test_schedules or [ - [[0, 1], [0.5, 0.5], [1, 0]], # Linear schedule - [[0, 1], [0.2, 0.8], [0.8, 0.2], [1, 0]], # Pause schedule - [[0, 1], [0.1, 0.9], [0.9, 0.1], [1, 0]] # Fast start - ] - - results = [] - - for i, schedule in enumerate(test_schedules): - print(f"Testing schedule {i+1}: {schedule}") - - # Run with custom annealing schedule - result = backend.solve_qubo( - problem, - anneal_schedule=schedule, - num_reads=100 - ) - - if result['success']: - best_energy = min(result['energies']) - avg_energy = np.mean(result['energies']) - results.append({ - 'schedule': schedule, - 'best_energy': best_energy, - 'avg_energy': avg_energy - }) - - # Find best schedule - if results: - best_schedule = min(results, key=lambda x: x['best_energy']) - print(f"Best schedule: {best_schedule['schedule']}") - print(f"Best energy: {best_schedule['best_energy']}") - return best_schedule['schedule'] - - return None -``` - -### Chain Strength Optimization - -```python -def optimize_chain_strength(backend, problem, strength_range=(0.1, 2.0), steps=10): - """Optimize chain strength for embedding.""" - - if backend.device_name == 'simulator': - print("Chain strength not applicable for simulator") - return 1.0 - - strengths = np.linspace(strength_range[0], strength_range[1], steps) - results = [] - - for strength in strengths: - print(f"Testing chain strength: {strength:.2f}") - - result = backend.solve_qubo( - problem, - chain_strength=strength, - num_reads=100 - ) - - if result['success']: - best_energy = min(result['energies']) - # Check for broken chains (simplified) - num_solutions = len(set(str(s) for s in result['samples'])) - - results.append({ - 'strength': strength, - 'best_energy': best_energy, - 'diversity': num_solutions - }) - - if results: - # Balance between energy and solution diversity - best_result = min(results, key=lambda x: x['best_energy'] - 0.1 * x['diversity']) - optimal_strength = best_result['strength'] - print(f"Optimal chain strength: {optimal_strength:.2f}") - return optimal_strength - - return 1.0 -``` - -### Parallel Problem Solving - -```python -import concurrent.futures - -def solve_problems_parallel(backend, problems, max_workers=4): - """Solve multiple problems in parallel.""" - - def solve_single_problem(prob_id, problem): - print(f"Solving problem {prob_id}") - result = backend.solve_qubo(problem) - result['problem_id'] = prob_id - return result - - with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: - futures = [executor.submit(solve_single_problem, i, prob) - for i, prob in enumerate(problems)] - - results = [] - for future in concurrent.futures.as_completed(futures): - try: - result = future.result() - results.append(result) - except Exception as e: - print(f"Problem solving failed: {e}") - - return results - -# Example: Solve multiple random problems -problems = [generate_random_qubo(20, density=0.1) for _ in range(5)] -parallel_results = solve_problems_parallel(backend, problems) - -for result in parallel_results: - if result['success']: - print(f"Problem {result['problem_id']}: Best energy = {min(result['energies'])}") -``` - -## Error Handling and Debugging - -### Comprehensive Error Management - -```python -import logging - -def robust_ocean_solving(backend, problem, problem_type='qubo', max_retries=3): - """Robust problem solving with error handling.""" - - logger = logging.getLogger('ocean_backend') - - for attempt in range(max_retries): - try: - # Validate problem size - if problem_type == 'qubo': - num_vars = len(set(var[0] for var in problem.keys()) | - set(var[1] for var in problem.keys())) - else: - num_vars = len(problem[0]) + len(problem[1]) # h, J - - max_vars = backend._get_max_variables() - if num_vars > max_vars: - logger.error(f"Problem has {num_vars} variables, backend supports {max_vars}") - return {'success': False, 'error': 'Problem too large'} - - # Attempt solving - if problem_type == 'qubo': - result = backend.solve_qubo(problem) - elif problem_type == 'ising': - h, J = problem - result = backend.solve_ising(h, J) - else: - result = backend.solve_optimization_problem(problem, problem_type) - - if result['success']: - logger.info(f"Problem solved successfully on attempt {attempt + 1}") - return result - else: - logger.warning(f"Solving failed on attempt {attempt + 1}: {result.get('error', 'Unknown')}") - - except Exception as e: - logger.error(f"Exception on attempt {attempt + 1}: {e}") - - if 'timeout' in str(e).lower(): - # Increase timeout for retry - logger.info("Increasing timeout for retry") - elif 'token' in str(e).lower(): - logger.error("Authentication error - check D-Wave token") - break - - return {'success': False, 'error': 'All retry attempts failed'} - -# Test robust solving -test_problem = generate_random_qubo(30, density=0.15) -robust_result = robust_ocean_solving(backend, test_problem) -``` - -### Problem Validation - -```python -def validate_ocean_problem(problem, problem_type='qubo'): - """Validate problem formulation before solving.""" - - validation = { - 'valid': True, - 'warnings': [], - 'errors': [] - } - - if problem_type == 'qubo': - # Validate QUBO format - if not isinstance(problem, dict): - validation['errors'].append("QUBO must be a dictionary") - validation['valid'] = False - return validation - - # Check key format - for key in problem.keys(): - if not isinstance(key, tuple) or len(key) != 2: - validation['errors'].append(f"Invalid QUBO key format: {key}") - validation['valid'] = False - elif not all(isinstance(i, int) for i in key): - validation['errors'].append(f"QUBO keys must be integer pairs: {key}") - validation['valid'] = False - - # Check for diagonal dominance (good for annealing) - diagonal_terms = {i: problem.get((i, i), 0) for i in - set(k[0] for k in problem.keys()) | set(k[1] for k in problem.keys())} - - off_diagonal_sum = {} - for (i, j), val in problem.items(): - if i != j: - off_diagonal_sum[i] = off_diagonal_sum.get(i, 0) + abs(val) - off_diagonal_sum[j] = off_diagonal_sum.get(j, 0) + abs(val) - - for var in diagonal_terms: - diagonal = abs(diagonal_terms[var]) - off_diag = off_diagonal_sum.get(var, 0) - - if diagonal < off_diag: - validation['warnings'].append( - f"Variable {var}: weak diagonal dominance may affect convergence" - ) - - elif problem_type == 'ising': - h, J = problem - - # Validate Ising format - if not isinstance(h, dict) or not isinstance(J, dict): - validation['errors'].append("Ising model requires h (dict) and J (dict)") - validation['valid'] = False - - # Check variable consistency - h_vars = set(h.keys()) - j_vars = set() - for (i, j) in J.keys(): - j_vars.add(i) - j_vars.add(j) - - if h_vars != j_vars: - validation['warnings'].append("Inconsistent variables between h and J") - - return validation - -# Validate problems before solving -qubo_validation = validate_ocean_problem(test_problem, 'qubo') -print("QUBO validation:", qubo_validation) - -if qubo_validation['valid']: - result = backend.solve_qubo(test_problem) -else: - print("Problem validation failed, not solving") -``` - -## Best Practices - -### Problem Design - -1. **Start Small**: Test with small problems before scaling up -2. **Use Constraints Carefully**: High penalty terms can dominate the objective -3. **Balance Problem Terms**: Avoid extreme coefficient ranges -4. **Consider Problem Structure**: Sparse problems embed better - -### Annealing Strategy - -1. **Tune Chain Strength**: Balance embedding integrity with problem solving -2. **Use Multiple Reads**: Quantum annealing is probabilistic -3. **Analyze Energy Histograms**: Look for clear energy gaps -4. **Consider Hybrid Approaches**: For large or hard problems - -### Cost Optimization - -1. **Test Locally**: Use simulator for development -2. **Batch Problems**: Solve multiple variants together -3. **Monitor Usage**: Track D-Wave Leap usage and credits -4. **Use Appropriate Solvers**: Match solver to problem size/type - -## Troubleshooting - -### Common Issues - -**ImportError: No module named 'dwave'** -```bash -pip install dwave-ocean-sdk -``` - -**Authentication Error** -```python -# Check token configuration -import os -print("Token:", os.getenv('DWAVE_API_TOKEN')) - -# Test connection -from dwave.system import DWaveSampler -try: - sampler = DWaveSampler(token='your-token') - print("Connection successful") -except Exception as e: - print(f"Connection failed: {e}") -``` - -**No Embedding Found** -```python -# Reduce problem size or density -smaller_problem = {k: v for i, (k, v) in enumerate(problem.items()) if i < 10} - -# Or use hybrid solver -hybrid_backend = sqx.OceanBackend(device='hybrid', token='your-token') -result = hybrid_backend.solve_qubo(problem) -``` - -**Poor Solution Quality** -```python -# Increase number of reads -result = backend.solve_qubo(problem, num_reads=5000) - -# Tune chain strength -result = backend.solve_qubo(problem, chain_strength=2.0) - -# Use custom annealing schedule -schedule = [[0, 1], [0.2, 0.8], [0.8, 0.2], [1, 0]] -result = backend.solve_qubo(problem, anneal_schedule=schedule) -``` - -### Performance Issues - -**Slow Embedding** -- Reduce problem connectivity -- Use preprocessing to simplify problem -- Consider problem decomposition - -**High Error Rates** -- Increase chain strength -- Reduce annealing time -- Use error correction techniques - -**Inconsistent Results** -- Increase number of reads -- Check for broken chains -- Validate problem formulation - -## Integration Examples - -### Hybrid VQE-Annealing Algorithm - -```python -def hybrid_vqe_annealing(backend_gate, backend_ocean, hamiltonian, ansatz_params): - """Combine VQE with annealing for parameter optimization.""" - - def evaluate_energy(params): - # Use gate-model backend for VQE energy evaluation - circuit = create_vqe_circuit(backend_gate, params) - energy = calculate_expectation_value(circuit, hamiltonian) - return energy - - # Create QUBO for parameter optimization using annealing - # This is a simplified example - real implementation more complex - - param_space = np.linspace(0, 2*np.pi, 10) # Discretize parameters - n_params = len(ansatz_params) - - # QUBO terms for parameter optimization - Q = {} - for i in range(n_params): - for p1, param_val1 in enumerate(param_space): - for p2, param_val2 in enumerate(param_space): - if p1 <= p2: - # Evaluate energy for these parameter values - test_params = ansatz_params.copy() - test_params[i] = param_val1 - if i != len(test_params) - 1: - test_params[i+1] = param_val2 - - energy = evaluate_energy(test_params) - var1 = i * len(param_space) + p1 - var2 = i * len(param_space) + p2 - - Q[(var1, var2)] = energy - - # Solve parameter optimization with annealing - result = backend_ocean.solve_qubo(Q) - - return result - -# This would require both gate and annealing backends -# gate_backend = sqx.get_backend('qiskit') -# ocean_backend = sqx.get_backend('ocean') -# hybrid_result = hybrid_vqe_annealing(gate_backend, ocean_backend, h2_hamiltonian, [0.5, 1.0]) -``` - -### Portfolio Optimization - -```python -def portfolio_optimization_ocean(returns, risks, budget=1.0, risk_tolerance=0.1): - """Portfolio optimization using quantum annealing.""" - - n_assets = len(returns) - - # Discretize investment levels (e.g., 0%, 25%, 50%, 75%, 100%) - levels = [0, 0.25, 0.5, 0.75, 1.0] - n_levels = len(levels) - - # Variables: x_{i,l} = 1 if asset i gets investment level l - Q = {} - - # Objective: maximize return, minimize risk - for asset in range(n_assets): - for level in range(n_levels): - var = asset * n_levels + level - - # Return term (negative for maximization) - return_coeff = -returns[asset] * levels[level] - Q[(var, var)] = Q.get((var, var), 0) + return_coeff - - # Risk term (quadratic in investment levels) - risk_coeff = risk_tolerance * risks[asset] * (levels[level] ** 2) - Q[(var, var)] = Q.get((var, var), 0) + risk_coeff - - # Constraint: Each asset gets exactly one investment level - penalty = 10.0 - for asset in range(n_assets): - # (∑_{l} x_{asset,l} - 1)² = penalty - for l1 in range(n_levels): - for l2 in range(n_levels): - var1 = asset * n_levels + l1 - var2 = asset * n_levels + l2 - - if l1 == l2: - Q[(var1, var1)] = Q.get((var1, var1), 0) + penalty - else: - Q[(var1, var2)] = Q.get((var1, var2), 0) + penalty - - # Linear terms - for level in range(n_levels): - var = asset * n_levels + level - Q[(var, var)] = Q.get((var, var), 0) - 2 * penalty - - # Budget constraint (simplified) - budget_penalty = 10.0 - for a1 in range(n_assets): - for l1 in range(n_levels): - for a2 in range(n_assets): - for l2 in range(n_levels): - if a1 <= a2: - var1 = a1 * n_levels + l1 - var2 = a2 * n_levels + l2 - - coeff = budget_penalty * levels[l1] * levels[l2] - Q[(var1, var2)] = Q.get((var1, var2), 0) + coeff - - # Solve portfolio optimization - result = backend.solve_qubo(Q) - - if result['success']: - # Decode portfolio allocation - best_sample = result['samples'][0] - portfolio = {} - - for asset in range(n_assets): - for level in range(n_levels): - var = asset * n_levels + level - if best_sample.get(var, 0) == 1: - portfolio[asset] = levels[level] - break - - print("Optimal portfolio allocation:") - total_investment = 0 - expected_return = 0 - expected_risk = 0 - - for asset, allocation in portfolio.items(): - print(f"Asset {asset}: {allocation*100:.1f}%") - total_investment += allocation - expected_return += allocation * returns[asset] - expected_risk += allocation * risks[asset] - - print(f"Total investment: {total_investment*100:.1f}%") - print(f"Expected return: {expected_return:.4f}") - print(f"Expected risk: {expected_risk:.4f}") - - return portfolio - - return None - -# Example portfolio optimization -returns = [0.1, 0.15, 0.08, 0.12, 0.20] # Expected returns -risks = [0.05, 0.10, 0.03, 0.08, 0.15] # Risk levels +import superquantx as sqx -optimal_portfolio = portfolio_optimization_ocean(returns, risks) +backend = sqx.get_backend("ocean", device="simulator") +edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] +result = backend.solve_max_cut(edges, num_reads=500) +print(result["samples"][0], result["energies"][0]) ``` -## API Reference - -The Ocean backend provides these key methods: - -- `solve_qubo(Q, **kwargs)`: Solve QUBO optimization problems -- `solve_ising(h, J, **kwargs)`: Solve Ising model problems -- `solve_optimization_problem(problem, type)`: Generic problem solver -- `solve_max_cut(graph, **kwargs)`: Maximum cut problem solver -- `solve_tsp(distance_matrix, **kwargs)`: Traveling salesman problem -- `get_backend_info()`: Backend and hardware information -- `get_version_info()`: Ocean SDK version information +### TSP -For complete API documentation, see the [API Reference](../api/backends.md#ocean-backend) section. +`OceanBackend.solve_tsp` raises `NotImplementedError` in 0.3.0. Build a QUBO +with one-hot city/position penalties and call `solve_qubo` instead. ---- +## Tips -*For more information about D-Wave Ocean, visit the [Ocean Documentation](https://docs.ocean.dwavesys.com/en/stable/).* \ No newline at end of file +- Always develop against `device='simulator'` first; it needs no token. +- Annealers do not run Hadamard / CNOT circuits. Convert the problem to QUBO + or Ising, or use a gate-model backend instead. +- Hardware and hybrid calls are skipped by `scripts/check_docs_examples.py` + via ``. diff --git a/docs/backends/pennylane.md b/docs/backends/pennylane.md index c00fdc6..270e1b2 100644 --- a/docs/backends/pennylane.md +++ b/docs/backends/pennylane.md @@ -1,40 +1,36 @@ # 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 focused on +variational circuits and differentiable programming. SuperQuantX wraps it +behind the same gate-model API used by the other backends. +## Overview -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. +The PennyLane backend is a good fit when you want: -## 📋 Overview +- Variational circuits and hybrid quantum-classical loops +- Local simulators (`default.qubit`, `lightning.qubit`) +- The same portable circuit API as Qiskit, Cirq, Braket and TKET -PennyLane's strengths make it ideal for: -- **Quantum Machine Learning**: Variational circuits and differentiable programming -- **Hybrid Algorithms**: Seamless quantum-classical optimization -- **Multiple Hardware Backends**: Support for various quantum devices -- **Automatic Differentiation**: Built-in gradient computation - -## 🚀 Quick Start - -### Installation +## Installation ```bash -# Install SuperQuantX with PennyLane support uv add "superquantx[pennylane]==0.3.0" -# Or install PennyLane directly -pip install pennylane pennylane-qiskit pennylane-cirq +# Optional: faster local simulator +uv add pennylane-lightning ``` +## Quick Start + ### Basic Usage ```python import superquantx as sqx -# Get the PennyLane backend (local simulator by default) +# Local PennyLane simulator (default.qubit) backend = sqx.get_backend("pennylane") -# Bell state through the unified circuit API circuit = backend.create_circuit(2) circuit = backend.add_gate(circuit, "H", 0) circuit = backend.add_gate(circuit, "CNOT", [0, 1]) @@ -44,1449 +40,182 @@ result = backend.execute_circuit(circuit, shots=1000) print(result["counts"]) # about 500 each of '00' and '11' ``` -## 🔧 Configuration +PennyLane circuits are `PennyLaneCircuit` objects. They do **not** expose +methods such as `circuit.h(0)`. Always build them with `backend.add_gate` / +`backend.add_measurement`, or with the higher-level helpers below. -### Device Selection +## Configuration -PennyLane supports multiple devices. Configure your preferred device: +### Device Selection ```python import superquantx as sqx -# Different PennyLane devices +# Devices PennyLaneBackend understands out of the box devices = { - 'default.qubit': 'CPU simulator (default)', - 'lightning.qubit': 'Fast C++ simulator', - 'qiskit.aer': 'Qiskit Aer simulator', - 'qiskit.ibmq': 'IBM quantum hardware', - 'cirq.simulator': 'Cirq simulator', - 'strawberryfields.fock': 'Photonic simulator' + "default.qubit": "Pure-Python PennyLane simulator (default)", + "lightning.qubit": "C++ simulator (needs pennylane-lightning)", } -# Create backend with specific device -backend = sqx.PennyLaneBackend(device='lightning.qubit', shots=1024) - -# Or use device-specific parameters -backend = sqx.PennyLaneBackend( - device='qiskit.ibmq', - shots=1024, - backend_name='ibmq_qasm_simulator', - hub='ibm-q', - group='open', - project='main' -) +backend = sqx.PennyLaneBackend(device="lightning.qubit", wires=8, shots=1024) +print(backend.get_device_info()) +print(backend.device) # underlying PennyLane device name ``` -### Advanced Configuration - -```python -import pennylane as qml - -# Custom PennyLane device configuration -device_config = { - 'name': 'default.qubit', - 'wires': 4, - 'shots': 2048, - 'analytic': False # Use sampling instead of exact computation -} +Plugins such as `qiskit.aer` or IBM hardware devices are not configured +through `PennyLaneBackend` in 0.3.0. Use the Qiskit backend for IBM access, +or build a native PennyLane device yourself and drive it outside SuperQuantX. -# Create backend with custom config -backend = sqx.PennyLaneBackend(**device_config) +### Constructor Arguments -# Access underlying PennyLane device -pennylane_device = backend.device -print(f"Device capabilities: {pennylane_device.capabilities()}") -``` +`PennyLaneBackend(device='default.qubit', wires=16, shots=1024, **kwargs)`: -## 📊 Quantum Machine Learning +- `device`: PennyLane device name +- `wires`: maximum number of qubits the device is created with +- `shots`: default shot count for `execute_circuit` -PennyLane excels at quantum ML. Here are comprehensive examples: +## Working with Circuits -### Variational Quantum Classifier +### Portable Gate API ```python import numpy as np -import matplotlib.pyplot as plt -from sklearn.datasets import make_moons -from sklearn.model_selection import train_test_split - -def pennylane_vqc_example(): - """Complete VQC example using PennyLane backend.""" - - print("PennyLane VQC Example") - print("=" * 25) - - # Generate dataset - X, y = make_moons(n_samples=200, noise=0.1, random_state=42) - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) - - # Create VQC with PennyLane backend - vqc = sqx.VariationalQuantumClassifier( - n_qubits=2, - n_layers=3, - backend='pennylane', - optimizer='adam' - ) - - # Configure and train - vqc.compile( - optimizer='adam', - learning_rate=0.01, - loss='binary_crossentropy' - ) - - print("Training VQC with PennyLane...") - history = vqc.fit( - X_train, y_train, - epochs=50, - validation_data=(X_test, y_test), - verbose=1 - ) - - # Evaluate - train_accuracy = vqc.score(X_train, y_train) - test_accuracy = vqc.score(X_test, y_test) - - print(f"\nResults:") - print(f"Training Accuracy: {train_accuracy:.3f}") - print(f"Test Accuracy: {test_accuracy:.3f}") - - # Plot training history - plt.figure(figsize=(12, 4)) - - plt.subplot(1, 2, 1) - plt.plot(history['loss'], label='Training Loss') - if 'val_loss' in history: - plt.plot(history['val_loss'], label='Validation Loss') - plt.title('Training History') - plt.xlabel('Epoch') - plt.ylabel('Loss') - plt.legend() - plt.grid(True) - - # Visualize decision boundary - plt.subplot(1, 2, 2) - - # Create a mesh for plotting - h = 0.02 - x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 - y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 - xx, yy = np.meshgrid(np.arange(x_min, x_max, h), - np.arange(y_min, y_max, h)) - - # Make predictions on mesh - mesh_points = np.c_[xx.ravel(), yy.ravel()] - try: - Z = vqc.predict_proba(mesh_points)[:, 1] - Z = Z.reshape(xx.shape) - - plt.contourf(xx, yy, Z, levels=50, alpha=0.8, cmap='RdBu') - plt.colorbar(label='Probability') - except: - print("Skipping decision boundary plot - requires probability prediction") - - # Plot data points - scatter = plt.scatter(X[:, 0], X[:, 1], c=y, cmap='RdBu', edgecolors='black') - plt.title(f'VQC Decision Boundary (Acc: {test_accuracy:.2f})') - plt.xlabel('Feature 1') - plt.ylabel('Feature 2') - plt.colorbar(scatter, label='Class') - - plt.tight_layout() - plt.show() - -pennylane_vqc_example() -``` - -### Quantum Neural Network with PennyLane - -```python -def pennylane_qnn_example(): - """Advanced QNN example showcasing PennyLane's capabilities.""" - - print("PennyLane Quantum Neural Network") - print("=" * 35) - - # Create custom QNN architecture - class PennyLaneQNN: - def __init__(self, n_qubits, n_layers, backend='pennylane'): - self.n_qubits = n_qubits - self.n_layers = n_layers - self.backend = sqx.get_backend(backend) - - # Initialize parameters - self.n_params = n_qubits * n_layers * 3 # 3 rotations per layer - self.params = np.random.random(self.n_params) * 2 * np.pi - - def create_variational_circuit(self, inputs, params): - """Create variational quantum circuit.""" - circuit = self.backend.create_circuit(self.n_qubits) - - # Data encoding - for i, inp in enumerate(inputs): - if i < self.n_qubits: - circuit.ry(np.pi * inp, i) - - # Variational layers - param_idx = 0 - for layer in range(self.n_layers): - # Rotation gates - for qubit in range(self.n_qubits): - circuit.rx(params[param_idx], qubit) - param_idx += 1 - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling gates - for qubit in range(self.n_qubits - 1): - circuit.cx(qubit, qubit + 1) - if self.n_qubits > 2: - circuit.cx(self.n_qubits - 1, 0) # Ring connectivity - - return circuit - - def forward(self, inputs, params=None): - """Forward pass through QNN.""" - if params is None: - params = self.params - - # Create and run circuit - circuit = self.create_variational_circuit(inputs, params) - - # Measure expectation values - result = self.measure_expectation(circuit) - return result - - def measure_expectation(self, circuit): - """Measure expectation value for classification.""" - circuit.measure_all() - result = self.backend.run(circuit, shots=1000) - counts = result.get_counts() - - # Calculate expectation of first qubit - expectation = 0 - total_shots = sum(counts.values()) - - for bitstring, count in counts.items(): - first_bit = int(bitstring[0]) - sign = 1 if first_bit == 0 else -1 - expectation += sign * count / total_shots - - return expectation - - def cost_function(self, params, X, y): - """Cost function for training.""" - predictions = [] - for xi in X: - output = self.forward(xi, params) - pred = 1 if output > 0 else 0 - predictions.append(pred) - - # Binary cross-entropy loss - predictions = np.array(predictions) - y = np.array(y) - - # Avoid log(0) by adding small epsilon - epsilon = 1e-15 - predictions = np.clip(predictions, epsilon, 1 - epsilon) - - loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) - return loss - - def train(self, X, y, epochs=50, learning_rate=0.1): - """Train QNN using parameter-shift rule.""" - print(f"Training QNN with {epochs} epochs...") - - params = self.params.copy() - cost_history = [] - - for epoch in range(epochs): - # Compute gradients using parameter-shift rule - gradients = np.zeros_like(params) - - for i in range(len(params)): - # Forward and backward shifts - params_plus = params.copy() - params_plus[i] += np.pi / 2 - cost_plus = self.cost_function(params_plus, X, y) - - params_minus = params.copy() - params_minus[i] -= np.pi / 2 - cost_minus = self.cost_function(params_minus, X, y) - - # Parameter-shift rule - gradients[i] = (cost_plus - cost_minus) / 2 - - # Update parameters - params = params - learning_rate * gradients - - # Record cost - current_cost = self.cost_function(params, X, y) - cost_history.append(current_cost) - - if epoch % 10 == 0: - print(f" Epoch {epoch}: Cost = {current_cost:.4f}") - - self.params = params - return cost_history - - def predict(self, X): - """Make predictions.""" - predictions = [] - for xi in X: - output = self.forward(xi) - pred = 1 if output > 0 else 0 - predictions.append(pred) - return np.array(predictions) - - # Test the QNN - from sklearn.datasets import make_classification - - # Generate dataset - X, y = make_classification(n_samples=100, n_features=4, n_classes=2, - n_redundant=0, random_state=42) - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - - # Normalize features to [-1, 1] - X_train = 2 * (X_train - X_train.min()) / (X_train.max() - X_train.min()) - 1 - X_test = 2 * (X_test - X_test.min()) / (X_test.max() - X_test.min()) - 1 - - # Create and train QNN - qnn = PennyLaneQNN(n_qubits=4, n_layers=2) - - cost_history = qnn.train(X_train, y_train, epochs=30, learning_rate=0.3) - - # Evaluate - train_preds = qnn.predict(X_train) - test_preds = qnn.predict(X_test) - - train_acc = np.mean(train_preds == y_train) - test_acc = np.mean(test_preds == y_test) - - print(f"\nQNN Results:") - print(f"Training Accuracy: {train_acc:.3f}") - print(f"Test Accuracy: {test_acc:.3f}") - - # Plot training curve - plt.figure(figsize=(10, 5)) - - plt.subplot(1, 2, 1) - plt.plot(cost_history, 'b-', linewidth=2) - plt.title('QNN Training Curve') - plt.xlabel('Epoch') - plt.ylabel('Cost') - plt.grid(True) - - plt.subplot(1, 2, 2) - # Confusion matrix - from sklearn.metrics import confusion_matrix - cm = confusion_matrix(y_test, test_preds) - - plt.imshow(cm, interpolation='nearest', cmap='Blues') - plt.title('Confusion Matrix') - plt.colorbar() - - # Add text annotations - for i in range(cm.shape[0]): - for j in range(cm.shape[1]): - plt.text(j, i, cm[i, j], ha='center', va='center') - - plt.xlabel('Predicted') - plt.ylabel('Actual') - - plt.tight_layout() - plt.show() - -pennylane_qnn_example() -``` +import superquantx as sqx -### Quantum Transfer Learning +backend = sqx.get_backend("pennylane") +circuit = backend.create_circuit(3) -```python -def pennylane_transfer_learning(): - """Quantum transfer learning with PennyLane.""" - - print("Quantum Transfer Learning") - print("=" * 28) - - class QuantumTransferLearning: - def __init__(self, pretrained_params=None): - self.backend = sqx.get_backend('pennylane') - self.n_qubits = 4 - self.n_layers = 2 - - # Use pretrained parameters or initialize randomly - if pretrained_params is not None: - self.params = pretrained_params - else: - self.params = np.random.random(self.n_qubits * self.n_layers * 2) * 2 * np.pi - - # Freeze some parameters for transfer learning - self.freeze_mask = np.ones_like(self.params, dtype=bool) - self.freeze_mask[:len(self.params)//2] = False # Freeze first half - - def create_feature_extractor(self, inputs, params): - """Pretrained feature extraction layers.""" - circuit = self.backend.create_circuit(self.n_qubits) - - # Data encoding - for i, inp in enumerate(inputs[:self.n_qubits]): - circuit.ry(np.pi * inp, i) - - # Pretrained layers (frozen) - param_idx = 0 - for layer in range(self.n_layers // 2): - for qubit in range(self.n_qubits): - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling - for qubit in range(self.n_qubits - 1): - circuit.cx(qubit, qubit + 1) - - return circuit, param_idx - - def create_classifier_head(self, circuit, params, param_idx): - """Trainable classifier head.""" - # Additional trainable layers - for layer in range(self.n_layers // 2): - for qubit in range(self.n_qubits): - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling - for qubit in range(self.n_qubits - 1): - circuit.cx(qubit, qubit + 1) - - return circuit - - def forward(self, inputs, params=None): - if params is None: - params = self.params - - # Feature extraction - circuit, param_idx = self.create_feature_extractor(inputs, params) - - # Classification head - circuit = self.create_classifier_head(circuit, params, param_idx) - - # Measure - circuit.measure_all() - result = self.backend.run(circuit, shots=1000) - counts = result.get_counts() - - # Expectation value - expectation = 0 - total = sum(counts.values()) - for bitstring, count in counts.items(): - parity = sum(int(bit) for bit in bitstring) % 2 - sign = 1 if parity == 0 else -1 - expectation += sign * count / total - - return expectation - - def fine_tune(self, X, y, epochs=20, learning_rate=0.1): - """Fine-tune only unfrozen parameters.""" - print(f"Fine-tuning with {np.sum(self.freeze_mask)} trainable parameters...") - - params = self.params.copy() - cost_history = [] - - for epoch in range(epochs): - gradients = np.zeros_like(params) - - # Only compute gradients for unfrozen parameters - for i in range(len(params)): - if self.freeze_mask[i]: # Only update unfrozen params - params_plus = params.copy() - params_plus[i] += np.pi / 2 - - params_minus = params.copy() - params_minus[i] -= np.pi / 2 - - # Compute cost difference - cost_plus = self.compute_cost(X, y, params_plus) - cost_minus = self.compute_cost(X, y, params_minus) - - gradients[i] = (cost_plus - cost_minus) / 2 - - # Update only unfrozen parameters - params[self.freeze_mask] -= learning_rate * gradients[self.freeze_mask] - - current_cost = self.compute_cost(X, y, params) - cost_history.append(current_cost) - - if epoch % 5 == 0: - print(f" Epoch {epoch}: Cost = {current_cost:.4f}") - - self.params = params - return cost_history - - def compute_cost(self, X, y, params): - """Compute classification cost.""" - total_cost = 0 - for xi, yi in zip(X, y): - output = self.forward(xi, params) - pred = 1 if output > 0 else 0 - cost = (pred - yi) ** 2 # Squared error - total_cost += cost - return total_cost / len(X) - - def predict(self, X): - predictions = [] - for xi in X: - output = self.forward(xi) - pred = 1 if output > 0 else 0 - predictions.append(pred) - return np.array(predictions) - - # Simulate pretrained model - print("Step 1: Creating pretrained model...") - pretrained_params = np.random.random(16) * 2 * np.pi - print("Pretrained model created (simulated)") - - # Create transfer learning model - transfer_model = QuantumTransferLearning(pretrained_params) - - # Generate new task data - print("\nStep 2: Generating new task data...") - X_new, y_new = make_classification(n_samples=50, n_features=4, n_classes=2, random_state=123) - X_new = 2 * (X_new - X_new.min()) / (X_new.max() - X_new.min()) - 1 - - X_train_new, X_test_new, y_train_new, y_test_new = train_test_split( - X_new, y_new, test_size=0.3, random_state=42 - ) - - # Fine-tune on new task - print("Step 3: Fine-tuning on new task...") - fine_tune_history = transfer_model.fine_tune(X_train_new, y_train_new, epochs=25) - - # Evaluate - train_preds = transfer_model.predict(X_train_new) - test_preds = transfer_model.predict(X_test_new) - - train_acc = np.mean(train_preds == y_train_new) - test_acc = np.mean(test_preds == y_test_new) - - print(f"\nTransfer Learning Results:") - print(f"Training Accuracy: {train_acc:.3f}") - print(f"Test Accuracy: {test_acc:.3f}") - - # Compare with training from scratch - print("\nStep 4: Comparing with training from scratch...") - scratch_model = QuantumTransferLearning() # No pretrained params - scratch_model.freeze_mask[:] = True # Train all parameters - - scratch_history = scratch_model.fine_tune(X_train_new, y_train_new, epochs=25) - scratch_preds = scratch_model.predict(X_test_new) - scratch_acc = np.mean(scratch_preds == y_test_new) - - print(f"From Scratch Accuracy: {scratch_acc:.3f}") - - # Visualization - plt.figure(figsize=(12, 5)) - - plt.subplot(1, 2, 1) - plt.plot(fine_tune_history, 'b-', label='Transfer Learning', linewidth=2) - plt.plot(scratch_history, 'r--', label='From Scratch', linewidth=2) - plt.title('Training Comparison') - plt.xlabel('Epoch') - plt.ylabel('Cost') - plt.legend() - plt.grid(True) - - plt.subplot(1, 2, 2) - methods = ['Transfer Learning', 'From Scratch'] - accuracies = [test_acc, scratch_acc] - colors = ['blue', 'red'] - - bars = plt.bar(methods, accuracies, color=colors, alpha=0.7) - plt.title('Test Accuracy Comparison') - plt.ylabel('Accuracy') - plt.ylim(0, 1) - - # Add value labels on bars - for bar, acc in zip(bars, accuracies): - plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01, - f'{acc:.3f}', ha='center', va='bottom') - - plt.tight_layout() - plt.show() +backend.add_gate(circuit, "H", 0) +backend.add_gate(circuit, "RY", 1, [np.pi / 4]) +backend.add_gate(circuit, "CNOT", [0, 1]) +backend.add_gate(circuit, "CNOT", [1, 2]) +backend.add_measurement(circuit) -pennylane_transfer_learning() +counts = backend.execute_circuit(circuit, shots=1000)["counts"] +print(counts) +print(backend.counts_big_endian(counts)) # qubit 0 first ``` -## ⚡ Hardware Integration +Supported gate names match the other gate-model backends (`H`, `X`, `Y`, `Z`, +`RX`, `RY`, `RZ`, `CNOT`/`CX`, `CZ`, `SWAP`, `TOFFOLI`, …). -### IBM Quantum via PennyLane +### Feature Maps and Kernels ```python -def pennylane_ibm_integration(): - """Use IBM Quantum hardware through PennyLane.""" - - print("PennyLane IBM Quantum Integration") - print("=" * 37) - - try: - # Note: Requires IBM Quantum account setup - backend = sqx.PennyLaneBackend( - device='qiskit.ibmq', - backend_name='ibmq_qasm_simulator', # Use simulator for demo - shots=1024 - ) - - print(f"Connected to: {backend.device}") - - # Create a simple Bell state circuit - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - # Execute on IBM backend - print("Executing on IBM Quantum backend...") - result = backend.run(circuit, shots=1024) - - counts = result.get_counts() - print(f"Bell state results: {counts}") - - # Verify entanglement - prob_00 = counts.get('00', 0) / 1024 - prob_11 = counts.get('11', 0) / 1024 - prob_entangled = prob_00 + prob_11 - - print(f"Entanglement probability: {prob_entangled:.3f}") - - # Visualize results - plt.figure(figsize=(8, 6)) - states = list(counts.keys()) - probs = [counts[state] / 1024 for state in states] - - plt.bar(states, probs, color=['blue', 'red', 'green', 'orange'][:len(states)]) - plt.title('Bell State Results on IBM Quantum') - plt.xlabel('Measurement Outcome') - plt.ylabel('Probability') - plt.ylim(0, 0.6) - - # Add theoretical expectation - plt.axhline(y=0.5, color='black', linestyle='--', alpha=0.7, - label='Theoretical (0.5 each)') - plt.legend() - plt.grid(True, alpha=0.3) - plt.show() - - except Exception as e: - print(f"IBM Quantum integration requires setup: {e}") - print("Please configure IBM Quantum credentials to use real hardware") - -# Note: Uncomment to run with proper IBM Quantum setup -# pennylane_ibm_integration() -``` +import numpy as np +import superquantx as sqx -### Google Cirq via PennyLane +backend = sqx.get_backend("pennylane") +X = np.array([[0.1, 0.2], [0.4, 0.8], [0.7, 0.3], [0.9, 0.6]]) -```python -def pennylane_cirq_integration(): - """Use Google Cirq simulator through PennyLane.""" - - print("PennyLane Cirq Integration") - print("=" * 29) - - try: - # Create Cirq backend through PennyLane - backend = sqx.PennyLaneBackend( - device='cirq.simulator', - shots=1000 - ) - - print(f"Backend: {backend.device}") - - # Create quantum random walk circuit - n_qubits = 4 - circuit = backend.create_circuit(n_qubits) - - # Initialize superposition - for i in range(n_qubits): - circuit.h(i) - - # Add controlled rotations (quantum walk steps) - for step in range(3): - for i in range(n_qubits - 1): - angle = np.pi / (step + 2) - circuit.cry(angle, i, i + 1) - - circuit.measure_all() - - # Execute quantum walk - print("Executing quantum walk on Cirq...") - result = backend.run(circuit, shots=1000) - - counts = result.get_counts() - print(f"Quantum walk distribution: {dict(list(counts.items())[:5])}...") - - # Analyze distribution - bitstrings = list(counts.keys()) - probabilities = [counts[bs] / 1000 for bs in bitstrings] - - # Convert to position probabilities - positions = [int(bs, 2) for bs in bitstrings] - position_probs = {} - - for pos, prob in zip(positions, probabilities): - if pos not in position_probs: - position_probs[pos] = 0 - position_probs[pos] += prob - - # Plot quantum walk distribution - plt.figure(figsize=(12, 5)) - - plt.subplot(1, 2, 1) - sorted_positions = sorted(position_probs.keys()) - probs = [position_probs[pos] for pos in sorted_positions] - - plt.bar(sorted_positions, probs, alpha=0.7, color='green') - plt.title('Quantum Walk Position Distribution') - plt.xlabel('Position') - plt.ylabel('Probability') - plt.grid(True, alpha=0.3) - - # Compare with classical random walk - plt.subplot(1, 2, 2) - # Classical random walk would be more uniform - classical_prob = 1 / len(position_probs) - classical_probs = [classical_prob] * len(sorted_positions) - - width = 0.35 - x = np.arange(len(sorted_positions)) - - plt.bar(x - width/2, probs, width, label='Quantum Walk', alpha=0.7, color='green') - plt.bar(x + width/2, classical_probs, width, label='Classical Random', alpha=0.7, color='orange') - - plt.title('Quantum vs Classical Walk') - plt.xlabel('Position') - plt.ylabel('Probability') - plt.xticks(x, sorted_positions) - plt.legend() - plt.grid(True, alpha=0.3) - - plt.tight_layout() - plt.show() - - except Exception as e: - print(f"Cirq integration error: {e}") - print("Make sure pennylane-cirq is installed: pip install pennylane-cirq") +# create_feature_map returns a FeatureMapSpec, not a callable +spec = backend.create_feature_map(n_features=2, feature_map="ZZFeatureMap", reps=2) +encoded = backend.build_feature_map_circuit(X[0], spec) +print(type(encoded).__name__) -pennylane_cirq_integration() +# Kernel matrix used by QuantumSVM +K = backend.compute_kernel_matrix(X, X, feature_map="ZZFeatureMap", shots=200) +print(K.shape, np.round(np.diag(K), 3)) ``` -## 🔍 Advanced Features +Supported feature maps: `ZZFeatureMap`, `ZFeatureMap`, `PauliFeatureMap`, +`AngleEncoding`. -### Custom PennyLane Operations +### Ansätze ```python -def custom_pennylane_operations(): - """Create custom quantum operations with PennyLane.""" - - print("Custom PennyLane Operations") - print("=" * 31) - - import pennylane as qml - from pennylane import numpy as pnp - - # Custom parametric gate - class CustomRotation(qml.operation.Operation): - """Custom rotation gate with multiple parameters.""" - - num_wires = 1 - num_params = 3 - par_domain = "R" - - @staticmethod - def compute_matrix(theta, phi, lam): - """Compute the matrix representation.""" - c = pnp.cos(theta / 2) - s = pnp.sin(theta / 2) - - return pnp.array([ - [c, -s * pnp.exp(1j * lam)], - [s * pnp.exp(1j * phi), c * pnp.exp(1j * (phi + lam))] - ]) - - @staticmethod - def compute_decomposition(theta, phi, lam, wires): - """Decompose into basic gates.""" - return [ - qml.RZ(phi, wires=wires), - qml.RY(theta, wires=wires), - qml.RZ(lam, wires=wires) - ] - - # Use custom operation in circuit - dev = qml.device('default.qubit', wires=2, shots=1000) - - @qml.qnode(dev) - def custom_circuit(params): - # Use custom rotation - CustomRotation(params[0], params[1], params[2], wires=0) - - # Standard gates - qml.Hadamard(wires=1) - qml.CNOT(wires=[0, 1]) - - # Custom two-qubit operation - qml.ctrl(CustomRotation, control=1)(params[3], params[4], params[5], wires=0) - - return qml.probs(wires=[0, 1]) - - # Test custom circuit - params = pnp.random.random(6) * 2 * pnp.pi - probabilities = custom_circuit(params) - - print("Custom Circuit Probabilities:") - states = ['00', '01', '10', '11'] - for state, prob in zip(states, probabilities): - print(f" |{state}⟩: {prob:.3f}") - - # Visualize - plt.figure(figsize=(10, 6)) - - plt.subplot(1, 2, 1) - plt.bar(states, probabilities, color=['red', 'blue', 'green', 'orange']) - plt.title('Custom Circuit Output') - plt.xlabel('Quantum State') - plt.ylabel('Probability') - plt.ylim(0, max(probabilities) * 1.1) - - # Show parameter sensitivity - plt.subplot(1, 2, 2) - param_range = np.linspace(0, 2*np.pi, 20) - prob_evolution = [] - - for theta in param_range: - test_params = params.copy() - test_params[0] = theta # Vary first parameter - probs = custom_circuit(test_params) - prob_evolution.append(probs[0]) # Track |00⟩ probability - - plt.plot(param_range, prob_evolution, 'b-', linewidth=2) - plt.title('Parameter Sensitivity') - plt.xlabel('Parameter Value (θ)') - plt.ylabel('P(|00⟩)') - plt.grid(True) - - plt.tight_layout() - plt.show() - -custom_pennylane_operations() -``` - -### Gradient-Based Optimization - -```python -def pennylane_gradient_optimization(): - """Advanced gradient-based optimization with PennyLane.""" - - print("PennyLane Gradient Optimization") - print("=" * 35) - - import pennylane as qml - from pennylane import numpy as pnp - - # Create device - dev = qml.device('default.qubit', wires=3, shots=1000) - - @qml.qnode(dev, diff_method="parameter-shift") - def variational_circuit(params, inputs=None): - """Variational quantum circuit with gradients.""" - - # Data encoding layer - if inputs is not None: - for i, inp in enumerate(inputs): - if i < 3: - qml.RY(pnp.pi * inp, wires=i) - - # Variational layers - layers = 3 - for layer in range(layers): - # Rotation layer - for wire in range(3): - qml.RY(params[layer * 6 + wire * 2], wires=wire) - qml.RZ(params[layer * 6 + wire * 2 + 1], wires=wire) - - # Entangling layer - if layer < layers - 1: - for wire in range(2): - qml.CNOT(wires=[wire, wire + 1]) - qml.CNOT(wires=[2, 0]) - - # Measurement - return qml.expval(qml.PauliZ(0)) - - # Cost function for optimization - def cost_function(params, X, y): - """Variational quantum classifier cost.""" - predictions = [] - for xi in X: - output = variational_circuit(params, xi) - pred = 1 if output > 0 else 0 - predictions.append(pred) - - predictions = pnp.array(predictions) - - # Mean squared error - return pnp.mean((predictions - y) ** 2) - - # Generate training data - pnp.random.seed(42) - n_samples = 50 - X_train = pnp.random.uniform(-1, 1, (n_samples, 3)) - y_train = pnp.array([1 if sum(x) > 0 else 0 for x in X_train]) - - print(f"Training data: {n_samples} samples, 3 features") - print(f"Class distribution: {pnp.sum(y_train)} positive, {len(y_train) - pnp.sum(y_train)} negative") - - # Initialize parameters - n_params = 3 * 6 # 3 layers * 6 params per layer - params = pnp.random.uniform(0, 2*pnp.pi, n_params, requires_grad=True) - - # Optimization with different optimizers - optimizers = { - 'GradientDescent': qml.GradientDescentOptimizer(stepsize=0.1), - 'Adam': qml.AdamOptimizer(stepsize=0.1), - 'RMSprop': qml.RMSPropOptimizer(stepsize=0.1) - } - - results = {} - - for opt_name, optimizer in optimizers.items(): - print(f"\nOptimizing with {opt_name}...") - - current_params = params.copy() - cost_history = [] - - for epoch in range(50): - # Compute cost and gradients - cost = cost_function(current_params, X_train, y_train) - cost_history.append(cost) - - # Update parameters - current_params = optimizer.step( - lambda p: cost_function(p, X_train, y_train), - current_params - ) - - if epoch % 10 == 0: - print(f" Epoch {epoch}: Cost = {cost:.4f}") - - # Final evaluation - final_cost = cost_function(current_params, X_train, y_train) - - # Test accuracy - test_predictions = [] - for xi in X_train: - output = variational_circuit(current_params, xi) - pred = 1 if output > 0 else 0 - test_predictions.append(pred) - - accuracy = pnp.mean(pnp.array(test_predictions) == y_train) - - results[opt_name] = { - 'cost_history': cost_history, - 'final_cost': final_cost, - 'accuracy': accuracy, - 'params': current_params - } - - print(f" Final cost: {final_cost:.4f}") - print(f" Accuracy: {accuracy:.3f}") - - # Visualize optimization comparison - plt.figure(figsize=(15, 10)) - - # Cost evolution - plt.subplot(2, 3, 1) - for opt_name, result in results.items(): - plt.plot(result['cost_history'], label=opt_name, linewidth=2) - - plt.title('Cost Evolution') - plt.xlabel('Epoch') - plt.ylabel('Cost') - plt.legend() - plt.grid(True) - plt.yscale('log') - - # Final performance comparison - plt.subplot(2, 3, 2) - opt_names = list(results.keys()) - accuracies = [results[name]['accuracy'] for name in opt_names] - - bars = plt.bar(opt_names, accuracies, color=['blue', 'red', 'green']) - plt.title('Final Accuracy') - plt.ylabel('Accuracy') - plt.ylim(0, 1) - - for bar, acc in zip(bars, accuracies): - plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01, - f'{acc:.3f}', ha='center', va='bottom') - - # Parameter visualization for best optimizer - best_optimizer = max(results.keys(), key=lambda x: results[x]['accuracy']) - best_params = results[best_optimizer]['params'] - - plt.subplot(2, 3, 3) - plt.hist(best_params, bins=15, alpha=0.7, color='green') - plt.title(f'Best Parameters ({best_optimizer})') - plt.xlabel('Parameter Value') - plt.ylabel('Frequency') - plt.grid(True, alpha=0.3) - - # Gradient analysis - plt.subplot(2, 3, 4) - - # Compute gradients at final parameters - grad_fn = qml.grad(lambda p: cost_function(p, X_train, y_train)) - final_gradients = grad_fn(best_params) - - plt.plot(final_gradients, 'o-', color='red', linewidth=2) - plt.title('Final Gradient Magnitudes') - plt.xlabel('Parameter Index') - plt.ylabel('Gradient') - plt.grid(True) - - # Learning curve comparison - plt.subplot(2, 3, 5) - for opt_name, result in results.items(): - smoothed_cost = pnp.convolve(result['cost_history'], pnp.ones(5)/5, mode='valid') - plt.plot(smoothed_cost, label=f'{opt_name} (smoothed)', linewidth=2) - - plt.title('Smoothed Learning Curves') - plt.xlabel('Epoch') - plt.ylabel('Cost') - plt.legend() - plt.grid(True) - - # Parameter evolution (for best optimizer) - plt.subplot(2, 3, 6) - - # Track a few parameters during optimization - param_evolution = [] - test_params = params.copy() - optimizer = optimizers[best_optimizer] - - for epoch in range(30): # Shorter for visualization - param_evolution.append([test_params[0], test_params[5], test_params[10]]) - test_params = optimizer.step( - lambda p: cost_function(p, X_train, y_train), - test_params - ) - - param_evolution = pnp.array(param_evolution) - - for i, label in enumerate(['Param 0', 'Param 5', 'Param 10']): - plt.plot(param_evolution[:, i], label=label, linewidth=2) - - plt.title(f'Parameter Evolution ({best_optimizer})') - plt.xlabel('Epoch') - plt.ylabel('Parameter Value') - plt.legend() - plt.grid(True) - - plt.tight_layout() - plt.show() - - print(f"\nBest optimizer: {best_optimizer}") - print(f"Best accuracy: {results[best_optimizer]['accuracy']:.3f}") +import numpy as np +import superquantx as sqx -pennylane_gradient_optimization() +backend = sqx.get_backend("pennylane") +n_qubits, reps = 3, 1 +n_params = backend.ansatz_param_count("RealAmplitudes", n_qubits, reps) +params = np.zeros(n_params) + +# create_ansatz returns a ready-to-run circuit, not a factory +ansatz = backend.create_ansatz("RealAmplitudes", n_qubits, params, reps=reps) +backend.add_measurement(ansatz) +print(backend.execute_circuit(ansatz, shots=500)["counts"]) + +su2_params = np.zeros(backend.ansatz_param_count("EfficientSU2", n_qubits, reps)) +su2 = backend.create_ansatz("EfficientSU2", n_qubits, su2_params, reps=reps) +print(type(su2).__name__) ``` -## 📈 Performance Tips +## Quantum Machine Learning -### Optimization Strategies +### Quantum Neural Network ```python -def pennylane_performance_tips(): - """Performance optimization strategies for PennyLane.""" - - print("PennyLane Performance Optimization") - print("=" * 38) - - import time - - # 1. Device Selection Impact - devices = [ - ('default.qubit', 'CPU simulator'), - ('lightning.qubit', 'C++ simulator'), - # ('qiskit.aer', 'Qiskit Aer'), # If available - ] - - n_qubits = 8 - n_layers = 3 - shots = 1000 - - performance_results = {} - - for device_name, description in devices: - try: - print(f"\nTesting {device_name} ({description})...") - - # Create device - if device_name == 'lightning.qubit': - try: - backend = sqx.PennyLaneBackend(device=device_name, shots=shots) - except: - print(f" {device_name} not available, skipping...") - continue - else: - backend = sqx.PennyLaneBackend(device=device_name, shots=shots) - - # Create test circuit - circuit = backend.create_circuit(n_qubits) - - # Add parameterized layers - params = np.random.random(n_qubits * n_layers * 2) - param_idx = 0 - - for layer in range(n_layers): - for qubit in range(n_qubits): - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling layer - for qubit in range(n_qubits - 1): - circuit.cx(qubit, qubit + 1) - - circuit.measure_all() - - # Time execution - start_time = time.time() - result = backend.run(circuit, shots=shots) - execution_time = time.time() - start_time - - performance_results[device_name] = { - 'execution_time': execution_time, - 'description': description, - 'counts': result.get_counts() - } - - print(f" Execution time: {execution_time:.3f}s") - - except Exception as e: - print(f" Error with {device_name}: {e}") - - # 2. Shot Count vs Accuracy Trade-off - print(f"\n--- Shot Count Analysis ---") - - backend = sqx.PennyLaneBackend(device='default.qubit') - - # Simple Bell state circuit - bell_circuit = backend.create_circuit(2) - bell_circuit.h(0) - bell_circuit.cx(0, 1) - bell_circuit.measure_all() - - shot_counts = [100, 500, 1000, 2000, 5000] - shot_results = {} - - # Theoretical expectation: 50% |00⟩, 50% |11⟩ - theoretical_prob = 0.5 - - for shots in shot_counts: - start_time = time.time() - result = backend.run(bell_circuit, shots=shots) - exec_time = time.time() - start_time - - counts = result.get_counts() - prob_00 = counts.get('00', 0) / shots - error = abs(prob_00 - theoretical_prob) - - shot_results[shots] = { - 'execution_time': exec_time, - 'prob_00': prob_00, - 'error': error - } - - print(f" {shots:4d} shots: P(00)={prob_00:.3f}, Error={error:.3f}, Time={exec_time:.3f}s") - - # 3. Circuit Depth Impact - print(f"\n--- Circuit Depth Analysis ---") - - depths = [1, 3, 5, 10, 15] - depth_results = {} - - for depth in depths: - circuit = backend.create_circuit(4) - - # Create circuit with specified depth - params = np.random.random(4 * depth * 2) - param_idx = 0 - - for layer in range(depth): - for qubit in range(4): - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling - for qubit in range(3): - circuit.cx(qubit, qubit + 1) - - circuit.measure_all() - - start_time = time.time() - result = backend.run(circuit, shots=1000) - exec_time = time.time() - start_time - - depth_results[depth] = { - 'execution_time': exec_time, - 'n_params': len(params) - } - - print(f" Depth {depth:2d}: {len(params):2d} params, Time={exec_time:.3f}s") - - # Visualize performance results - plt.figure(figsize=(15, 10)) - - # Device performance comparison - if len(performance_results) > 1: - plt.subplot(2, 3, 1) - devices = list(performance_results.keys()) - times = [performance_results[d]['execution_time'] for d in devices] - - bars = plt.bar(devices, times, color=['blue', 'red', 'green'][:len(devices)]) - plt.title('Device Performance Comparison') - plt.ylabel('Execution Time (s)') - plt.xticks(rotation=45) - - for bar, time_val in zip(bars, times): - plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.001, - f'{time_val:.3f}s', ha='center', va='bottom') - - # Shot count vs accuracy - plt.subplot(2, 3, 2) - shots_list = list(shot_results.keys()) - errors = [shot_results[s]['error'] for s in shots_list] - - plt.loglog(shots_list, errors, 'o-', linewidth=2, markersize=8) - plt.xlabel('Number of Shots') - plt.ylabel('Error') - plt.title('Accuracy vs Shot Count') - plt.grid(True) - - # Expected 1/sqrt(N) scaling - theoretical_errors = [0.5 / np.sqrt(s) for s in shots_list] - plt.loglog(shots_list, theoretical_errors, '--', alpha=0.7, - label='1/√N scaling', color='red') - plt.legend() - - # Shot count vs time - plt.subplot(2, 3, 3) - times = [shot_results[s]['execution_time'] for s in shots_list] - - plt.plot(shots_list, times, 'o-', linewidth=2, color='green') - plt.xlabel('Number of Shots') - plt.ylabel('Execution Time (s)') - plt.title('Execution Time vs Shots') - plt.grid(True) - - # Circuit depth impact - plt.subplot(2, 3, 4) - depth_list = list(depth_results.keys()) - depth_times = [depth_results[d]['execution_time'] for d in depth_list] - - plt.semilogy(depth_list, depth_times, 'o-', linewidth=2, color='purple') - plt.xlabel('Circuit Depth') - plt.ylabel('Execution Time (s)') - plt.title('Depth vs Performance') - plt.grid(True) - - # Parameter count impact - plt.subplot(2, 3, 5) - param_counts = [depth_results[d]['n_params'] for d in depth_list] - - plt.plot(param_counts, depth_times, 'o-', linewidth=2, color='orange') - plt.xlabel('Number of Parameters') - plt.ylabel('Execution Time (s)') - plt.title('Parameters vs Performance') - plt.grid(True) - - # Performance recommendations - plt.subplot(2, 3, 6) - plt.text(0.1, 0.9, "Performance Recommendations:", fontsize=14, fontweight='bold', - transform=plt.gca().transAxes) - - recommendations = [ - "1. Use lightning.qubit for large circuits", - "2. Balance shots vs accuracy needs", - "3. Minimize circuit depth when possible", - "4. Consider parameter-shift vs finite-diff", - "5. Use analytic=True for noiseless sims", - "6. Batch circuits for efficiency", - "7. Profile different devices for your use case" - ] - - for i, rec in enumerate(recommendations): - plt.text(0.1, 0.8 - i*0.1, rec, fontsize=10, - transform=plt.gca().transAxes) - - plt.axis('off') - - plt.tight_layout() - plt.show() - - # Performance summary - print(f"\n=== Performance Summary ===") - if len(performance_results) > 0: - fastest_device = min(performance_results.keys(), - key=lambda x: performance_results[x]['execution_time']) - print(f"Fastest device: {fastest_device}") - - optimal_shots = min(shot_results.keys(), - key=lambda x: shot_results[x]['error'] * shot_results[x]['execution_time']) - print(f"Optimal shot count (error × time): {optimal_shots}") - - efficient_depth = min(depth_results.keys(), - key=lambda x: depth_results[x]['execution_time']) - print(f"Most efficient depth tested: {efficient_depth}") +import numpy as np +from sklearn.datasets import make_moons +from sklearn.model_selection import train_test_split +import superquantx as sqx + +X, y = make_moons(n_samples=60, noise=0.1, random_state=0) +X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.25, random_state=0 +) -pennylane_performance_tips() +qnn = sqx.QuantumNN( + backend="pennylane", + n_layers=2, + max_epochs=15, + seed=0, +) +qnn.fit(X_train, y_train) +acc = float(np.mean(qnn.predict(X_test) == y_test)) +print(f"QuantumNN accuracy: {acc:.3f}") ``` -## 🔧 Best Practices +There is no `VariationalQuantumClassifier` class in 0.3.0. Use +`QuantumNN` (alias `QuantumNeuralNetwork`) for variational classifiers. -### Code Organization +### Quantum SVM ```python -# pennylane_utils.py -import pennylane as qml +import numpy as np +from sklearn.datasets import make_moons +from sklearn.model_selection import train_test_split import superquantx as sqx -from pennylane import numpy as pnp -class PennyLaneUtils: - """Utility functions for PennyLane backend.""" - - @staticmethod - def create_optimized_device(n_qubits, shots=1024, device_type='auto'): - """Create optimized PennyLane device.""" - if device_type == 'auto': - if n_qubits <= 10: - device_type = 'lightning.qubit' - else: - device_type = 'default.qubit' - - try: - return sqx.PennyLaneBackend(device=device_type, shots=shots) - except: - return sqx.PennyLaneBackend(device='default.qubit', shots=shots) - - @staticmethod - def parameter_shift_gradients(circuit_func, params, shift=pnp.pi/2): - """Compute gradients using parameter-shift rule.""" - gradients = pnp.zeros_like(params) - - for i in range(len(params)): - params_plus = params.copy() - params_plus[i] += shift - - params_minus = params.copy() - params_minus[i] -= shift - - grad = (circuit_func(params_plus) - circuit_func(params_minus)) / 2 - gradients[i] = grad - - return gradients - - @staticmethod - def create_data_encoding_layer(circuit, data, encoding_type='amplitude'): - """Add data encoding layer to circuit.""" - if encoding_type == 'amplitude': - for i, val in enumerate(data): - if i < circuit.num_qubits: - circuit.ry(pnp.pi * val, i) - - elif encoding_type == 'angle': - for i, val in enumerate(data): - if i < circuit.num_qubits: - circuit.rx(val, i) - circuit.rz(val, i) - - return circuit +X, y = make_moons(n_samples=40, noise=0.1, random_state=0) +X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.25, random_state=0 +) -# Usage example -utils = PennyLaneUtils() -backend = utils.create_optimized_device(n_qubits=4) +qsvm = sqx.QuantumSVM(backend="pennylane", feature_map="ZFeatureMap") +qsvm.fit(X_train, y_train) +acc = float(np.mean(qsvm.predict(X_test) == y_test)) +print(f"QuantumSVM accuracy: {acc:.3f}") ``` -### Error Handling +## Comparison Across Backends ```python -def robust_pennylane_execution(): - """Robust PennyLane execution with error handling.""" - - def safe_circuit_execution(circuit_func, max_retries=3): - """Execute circuit with retry logic.""" - for attempt in range(max_retries): - try: - result = circuit_func() - return result - except Exception as e: - if attempt == max_retries - 1: - raise e - else: - print(f"Attempt {attempt + 1} failed: {e}") - # Reduce shots or switch device on retry - if hasattr(circuit_func, '__self__'): - circuit_func.__self__.shots = max(100, - circuit_func.__self__.shots // 2) - - # Example usage - backend = sqx.get_backend('pennylane') - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - result = safe_circuit_execution(lambda: backend.run(circuit, shots=1000)) - print(f"Robust execution result: {result.get_counts()}") - -robust_pennylane_execution() -``` - -## 📚 Resources - -### Official Documentation -- **PennyLane Documentation**: https://pennylane.ai/ -- **PennyLane Tutorials**: https://pennylane.ai/qml/ -- **API Reference**: https://pennylane.readthedocs.io/ - -### SuperQuantX Integration -- **Backend Configuration**: See `backends/` documentation -- **Quantum ML Examples**: See `tutorials/quantum-ml.md` -- **API Reference**: See `api/core.md` - -### Hardware Integration -- **IBM Quantum**: Requires IBM Quantum account -- **Google Cirq**: Available through PennyLane-Cirq plugin -- **AWS Braket**: Available through PennyLane-Braket plugin - ---- +import numpy as np +from sklearn.datasets import make_moons +from sklearn.model_selection import train_test_split +import superquantx as sqx -*PennyLane's focus on differentiable programming and quantum machine learning makes it an ideal choice for variational quantum algorithms and hybrid quantum-classical optimization. The SuperQuantX integration provides a unified interface while preserving PennyLane's unique capabilities.* +X, y = make_moons(n_samples=40, noise=0.1, random_state=0) +X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.25, random_state=0 +) -!!! tip "Optimization" - For best performance, use `lightning.qubit` device for circuits with ≤20 qubits, and consider the parameter-shift rule for gradient computation. +results = {} +for name in ["simulator", "pennylane"]: + model = sqx.QuantumSVM(backend=name, feature_map="ZFeatureMap") + model.fit(X_train, y_train) + results[name] = float(np.mean(model.predict(X_test) == y_test)) +print(results) +``` -!!! warning "Hardware Limitations" - When using real quantum hardware through PennyLane, account for device-specific constraints, noise, and queue times. +## Tips -!!! info "Compatibility" - PennyLane integrates well with PyTorch, TensorFlow, and JAX for hybrid quantum-classical machine learning workflows. \ No newline at end of file +- Prefer `backend.add_gate` over native PennyLane syntax when you want the + example to run unchanged on other SuperQuantX backends. +- `lightning.qubit` is usually faster than `default.qubit` for more than a + few qubits. +- Hardware access through PennyLane plugins is outside the 0.3.0 + `PennyLaneBackend` surface; use the matching SuperQuantX backend instead. diff --git a/docs/backends/qiskit.md b/docs/backends/qiskit.md index 224aed5..8f57235 100644 --- a/docs/backends/qiskit.md +++ b/docs/backends/qiskit.md @@ -1,9 +1,5 @@ # 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 @@ -48,25 +44,29 @@ print(result["counts"]) # about 500 each of '00' and '11' ### IBM Quantum Hardware +!!! note "Requires credentials" + Needs an IBM Quantum token; checked against the 0.3.0 constructor, not run. + + ```python -# Connect to IBM Quantum from qiskit_ibm_runtime import QiskitRuntimeService # Save your credentials (one-time setup) QiskitRuntimeService.save_account( - channel="ibm_quantum", + channel="ibm_quantum_platform", token="YOUR_IBM_QUANTUM_TOKEN", - overwrite=True + overwrite=True, ) -# Use IBM Quantum backend +# Any device name starting with "ibm" goes to IBM Quantum +backend = sqx.QiskitBackend(device='ibm_brisbane', shots=1024) +result = backend.execute_circuit(circuit, shots=1024) + +# Or pass the service arguments directly backend = sqx.QiskitBackend( - backend_name='ibmq_qasm_simulator', # or real hardware like 'ibm_osaka' - shots=1024 + device='ibm_brisbane', + provider={'channel': 'ibm_quantum_platform', 'token': 'YOUR_TOKEN', 'instance': 'YOUR_CRN'}, ) - -# Execute on IBM hardware -result = backend.run(circuit, shots=1024) ``` ## Configuration Options @@ -74,92 +74,63 @@ result = backend.run(circuit, shots=1024) ### Backend Selection ```python -# Different Qiskit backends -backends = { - 'qasm_simulator': 'Classical QASM simulator', - 'statevector_simulator': 'Statevector simulator', - 'unitary_simulator': 'Unitary matrix simulator', - 'ibmq_qasm_simulator': 'IBM cloud simulator', - 'ibm_osaka': 'IBM quantum processor (127 qubits)', - 'ibm_kyoto': 'IBM quantum processor (127 qubits)' +# Devices understood by QiskitBackend(device=...) +devices = { + 'aer_simulator': 'Local Aer simulator (default; also qasm_simulator, statevector_simulator)', + 'statevector': 'Aer with a fixed method (also density_matrix, stabilizer, matrix_product_state, ...)', + 'ibm_brisbane': 'IBM Quantum device by name (requires credentials)', } -# Create backend with specific device -backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - shots=2048, - optimization_level=3 -) +backend = sqx.QiskitBackend(device='statevector', shots=2048) +print(backend.backend.options.method) ``` ### Advanced Configuration ```python -# Custom backend configuration -backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - shots=1000, - optimization_level=2, # 0-3, higher = more optimization - seed_simulator=42, # For reproducible results - max_parallel_threads=4, - memory=True, # Enable memory snapshots - noise_model=None # Custom noise model -) +# Custom configuration +backend = sqx.QiskitBackend(device='aer_simulator', shots=1000) -# Access underlying Qiskit backend -qiskit_backend = backend.backend -print(f"Backend configuration: {qiskit_backend.configuration()}") +# Access the underlying Qiskit backend (an AerSimulator) to change its options +backend.backend.set_options(seed_simulator=42, max_parallel_threads=4) +print(backend.backend.options.seed_simulator) ``` +`QiskitBackend` takes `device`, `provider` and `shots`. Options such as an optimisation level, noise model or memory are set on the Qiskit objects (`backend.backend`, `qiskit.transpile`) as shown below. + ## Working with Circuits ### Circuit Creation ```python +import numpy as np + + def demonstrate_qiskit_circuits(): - """Show various Qiskit circuit features.""" - + """Backend circuits are qiskit.QuantumCircuit objects, so native methods work.""" backend = sqx.get_backend('qiskit') - - # Create 4-qubit circuit circuit = backend.create_circuit(4) - - # Single qubit gates - circuit.h(0) # Hadamard - circuit.x(1) # Pauli-X - circuit.y(2) # Pauli-Y - circuit.z(3) # Pauli-Z - - # Rotation gates - import numpy as np - circuit.rx(np.pi/4, 0) # X rotation - circuit.ry(np.pi/3, 1) # Y rotation - circuit.rz(np.pi/6, 2) # Z rotation - - # Two-qubit gates - circuit.cx(0, 1) # CNOT - circuit.cz(1, 2) # Controlled-Z - circuit.swap(2, 3) # SWAP - - # Multi-controlled gates - circuit.ccx(0, 1, 2) # Toffoli (CCX) - - # Phase gates - circuit.s(0) # S gate (√Z) - circuit.t(1) # T gate (√S) - - # Measure all qubits - circuit.measure_all() - - # Execute circuit - result = backend.run(circuit, shots=1000) - print(f"Complex circuit results: {result.get_counts()}") - - # Visualize circuit (if available) - try: - print(circuit.draw()) - except: - print("Circuit visualization not available") + + circuit.h(0) # Hadamard + circuit.x(1) # Pauli-X + circuit.y(2) # Pauli-Y + circuit.z(3) # Pauli-Z + circuit.rx(np.pi / 4, 0) # rotations + circuit.ry(np.pi / 3, 1) + circuit.rz(np.pi / 6, 2) + circuit.cx(0, 1) # CNOT + circuit.cz(1, 2) # controlled-Z + circuit.swap(2, 3) # SWAP + circuit.ccx(0, 1, 2) # Toffoli + circuit.s(0) # S + circuit.t(1) # T + + # The same gates through the portable API: backend.add_gate(circuit, 'H', 0), ... + circuit = backend.add_measurement(circuit) + result = backend.execute_circuit(circuit, shots=1000) + print(f"Counts (qubit 0 is the rightmost bit): {result['counts']}") + print(circuit.draw()) + demonstrate_qiskit_circuits() ``` @@ -167,67 +138,44 @@ demonstrate_qiskit_circuits() ### Parameterized Circuits ```python -def qiskit_parameterized_circuits(): - """Demonstrate parameterized quantum circuits.""" - +import numpy as np + + +def qiskit_parameterized_circuits(seed=0): + """Hardware-efficient ansatz and a parameter sensitivity check.""" backend = sqx.get_backend('qiskit') - - # Create parameterized circuit for VQE - def create_ansatz(params, n_qubits=4, layers=2): + n_qubits, layers = 4, 2 + + def create_ansatz(params): circuit = backend.create_circuit(n_qubits) - - param_idx = 0 - - # Initial layer - for i in range(n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - - # Entangling layers - for layer in range(layers): - # CNOT ladder - for i in range(n_qubits - 1): - circuit.cx(i, i + 1) - - # Parameterized rotations - for i in range(n_qubits): - circuit.ry(params[param_idx], i) - param_idx += 1 - circuit.rz(params[param_idx], i) - param_idx += 1 - + idx = 0 + for q in range(n_qubits): + circuit.ry(params[idx], q) + idx += 1 + for _ in range(layers): + for q in range(n_qubits - 1): + circuit.cx(q, q + 1) + for q in range(n_qubits): + circuit.ry(params[idx], q) + circuit.rz(params[idx + 1], q) + idx += 2 return circuit - - # Generate random parameters - n_params = 4 + 2 * 2 * 4 # Initial + layers * 2 * qubits - params = np.random.random(n_params) * 2 * np.pi - - # Create and run ansatz - ansatz = create_ansatz(params) - ansatz.measure_all() - - result = backend.run(ansatz, shots=1000) - print(f"Parameterized circuit results: {result.get_counts()}") - - # Parameter sensitivity analysis - print("\nParameter Sensitivity Analysis:") - base_result = result.get_counts() - base_prob_00 = base_result.get('0000', 0) / 1000 - - # Vary first parameter + + n_params = n_qubits + 2 * layers * n_qubits + params = np.random.default_rng(seed).random(n_params) * 2 * np.pi + + # Exact probabilities from the statevector (qubit 0 is the leftmost bit here) + def p_zero(p): + return abs(backend.statevector_big_endian(create_ansatz(p))[0]) ** 2 + + base = p_zero(params) + print(f"P(0000) = {base:.4f}") for delta in [-0.1, -0.05, 0.05, 0.1]: - test_params = params.copy() - test_params[0] += delta - - test_circuit = create_ansatz(test_params) - test_circuit.measure_all() - - test_result = backend.run(test_circuit, shots=1000) - test_counts = test_result.get_counts() - test_prob_00 = test_counts.get('0000', 0) / 1000 - - print(f" Δθ = {delta:+.2f}: P(0000) = {test_prob_00:.3f} " - f"(change: {test_prob_00 - base_prob_00:+.3f})") + shifted = params.copy() + shifted[0] += delta + print(f" dtheta = {delta:+.2f}: P(0000) = {p_zero(shifted):.4f} " + f"(change: {p_zero(shifted) - base:+.4f})") + qiskit_parameterized_circuits() ``` @@ -236,168 +184,63 @@ qiskit_parameterized_circuits() ### Real Hardware Execution +!!! note "Requires credentials" + Needs an IBM Quantum account; checked against the 0.3.0 `QiskitBackend` constructor, not run. + + ```python def run_on_ibm_hardware(): - """Execute circuits on real IBM quantum hardware.""" - - # Note: Requires IBM Quantum account setup - try: - from qiskit_ibm_runtime import QiskitRuntimeService - - # Initialize service - service = QiskitRuntimeService(channel="ibm_quantum") - - # List available backends - available_backends = service.backends() - print("Available IBM Quantum backends:") - for backend in available_backends: - status = backend.status() - print(f" {backend.name}: {status.pending_jobs} jobs pending, " - f"operational: {status.operational}") - - # Select least busy backend - from qiskit_ibm_runtime.utils import least_busy - backend_name = least_busy(available_backends).name - - print(f"\nUsing backend: {backend_name}") - - # Create SuperQuantX backend for IBM hardware - sqx_backend = sqx.QiskitBackend( - backend_name=backend_name, - shots=1024, - optimization_level=3 # Max optimization for hardware - ) - - # Create simple Bell state - circuit = sqx_backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - print("Submitting job to IBM Quantum...") - result = sqx_backend.run(circuit, shots=1024) - - counts = result.get_counts() - print(f"Hardware results: {counts}") - - # Analyze fidelity - prob_00 = counts.get('00', 0) / 1024 - prob_11 = counts.get('11', 0) / 1024 - bell_fidelity = prob_00 + prob_11 - - print(f"Bell state fidelity: {bell_fidelity:.3f}") - - # Compare with ideal - if bell_fidelity > 0.8: - print("✅ Good Bell state fidelity") - elif bell_fidelity > 0.6: - print("⚠️ Moderate Bell state fidelity") - else: - print("❌ Low Bell state fidelity") - - except ImportError: - print("IBM Quantum access requires: pip install qiskit-ibm-runtime") - except Exception as e: - print(f"IBM Quantum access error: {e}") - print("Make sure to set up IBM Quantum credentials") + """Run a Bell state on the least busy IBM device.""" + from qiskit_ibm_runtime import QiskitRuntimeService + + service = QiskitRuntimeService() + device = service.least_busy(operational=True, simulator=False).name + print(f"Using backend: {device}") + + # provider= takes the same keyword arguments as QiskitRuntimeService + hw = sqx.QiskitBackend(device=device, shots=1024) + circuit = hw.create_circuit(2) + hw.add_gate(circuit, 'H', 0) + hw.add_gate(circuit, 'CNOT', [0, 1]) + result = hw.execute_circuit(circuit) # transpiled and run with SamplerV2 + + counts = result['counts'] + print(f"Job {result['job_id']}: {counts}") + print(f"Bell fidelity: {(counts.get('00', 0) + counts.get('11', 0)) / 1024:.3f}") + -# Uncomment to run with proper IBM Quantum setup # run_on_ibm_hardware() ``` ### Device Calibration Data -```python -def analyze_device_properties(): - """Analyze IBM quantum device properties and calibration data.""" - - try: - from qiskit_ibm_runtime import QiskitRuntimeService - - service = QiskitRuntimeService(channel="ibm_quantum") - backend = service.get_backend('ibm_osaka') # 127-qubit processor - - # Get backend properties - properties = backend.properties() - configuration = backend.configuration() - - print(f"Backend: {backend.name}") - print(f"Number of qubits: {configuration.n_qubits}") - print(f"Coupling map: {len(configuration.coupling_map)} connections") - - # Analyze qubit properties - if properties: - print("\nQubit Error Rates:") - for i in range(min(10, configuration.n_qubits)): # First 10 qubits - # T1 and T2 times - t1 = properties.t1(i) - t2 = properties.t2(i) - - # Readout error - readout_error = properties.readout_error(i) - - # Gate error (single qubit) - try: - sx_error = properties.gate_error('sx', i) - print(f" Qubit {i}: T1={t1:.1f}μs, T2={t2:.1f}μs, " - f"Readout={readout_error:.4f}, SX={sx_error:.4f}") - except: - print(f" Qubit {i}: T1={t1:.1f}μs, T2={t2:.1f}μs, " - f"Readout={readout_error:.4f}") - - # Two-qubit gate errors - print("\nTwo-Qubit Gate Errors:") - coupling_map = configuration.coupling_map - for i, (q1, q2) in enumerate(coupling_map[:10]): # First 10 pairs - try: - cx_error = properties.gate_error('cx', [q1, q2]) - print(f" CX({q1},{q2}): {cx_error:.4f}") - except: - continue - - # Create noise model for simulation - from qiskit_aer.noise import NoiseModel - noise_model = NoiseModel.from_backend(backend) - - print(f"\nNoise model created with {len(noise_model.noise_instructions)} " - f"noise instructions") - - # Use noise model in simulation - sqx_backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - noise_model=noise_model, - shots=1000 - ) - - # Test with Bell state - circuit = sqx_backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - print("\nTesting with device noise model:") - noisy_result = sqx_backend.run(circuit, shots=1000) - noisy_counts = noisy_result.get_counts() - - print(f"Noisy simulation: {noisy_counts}") - - # Calculate noise impact - prob_00 = noisy_counts.get('00', 0) / 1000 - prob_11 = noisy_counts.get('11', 0) / 1000 - prob_01 = noisy_counts.get('01', 0) / 1000 - prob_10 = noisy_counts.get('10', 0) / 1000 - - fidelity = prob_00 + prob_11 - error_rate = prob_01 + prob_10 - - print(f"Bell state fidelity with noise: {fidelity:.3f}") - print(f"Error rate: {error_rate:.3f}") - - except Exception as e: - print(f"Device analysis requires IBM Quantum access: {e}") +!!! note "Requires credentials" + Needs an IBM Quantum account; checked against the `qiskit-ibm-runtime` API, not run. -# Uncomment to run with IBM Quantum access -# analyze_device_properties() + +```python +def analyze_device_properties(device='ibm_brisbane'): + """Read calibration data and build a matching noisy simulator.""" + from qiskit_aer import AerSimulator + from qiskit_ibm_runtime import QiskitRuntimeService + + ibm_backend = QiskitRuntimeService().backend(device) + target = ibm_backend.target + print(f"Backend: {ibm_backend.name}, {ibm_backend.num_qubits} qubits") + + for q in range(5): + props = target.qubit_properties[q] + readout = target['measure'][(q,)].error + print(f" Qubit {q}: T1={props.t1 * 1e6:.1f}us, T2={props.t2 * 1e6:.1f}us, readout={readout:.4f}") + + # Noisy local simulation that mimics the device + sim = sqx.QiskitBackend() + sim.backend = AerSimulator.from_backend(ibm_backend) + circuit = sim.create_circuit(2) + circuit.h(0) + circuit.cx(0, 1) + counts = sim.execute_circuit(circuit, shots=1000)['counts'] + print(f"Bell fidelity with device noise: {(counts.get('00', 0) + counts.get('11', 0)) / 1000:.3f}") ``` ## Advanced Features @@ -405,144 +248,75 @@ def analyze_device_properties(): ### Transpilation and Optimization ```python +import numpy as np +from qiskit import transpile + + def demonstrate_transpilation(): - """Show Qiskit circuit transpilation and optimization.""" - + """Show Qiskit transpilation at each optimisation level.""" backend = sqx.get_backend('qiskit') - - # Create complex circuit that needs optimization circuit = backend.create_circuit(5) - - # Add many gates that can be optimized for i in range(5): circuit.h(i) - - for i in range(4): - circuit.cx(i, i + 1) - - # Add more layers for _ in range(3): - for i in range(5): - circuit.rz(np.pi/4, i) for i in range(4): circuit.cx(i, i + 1) - - circuit.measure_all() - - print("Original circuit stats:") - print(f" Gates: {len(circuit._circuit.data) if hasattr(circuit, '_circuit') else 'N/A'}") - - # Test different optimization levels - optimization_levels = [0, 1, 2, 3] - - for opt_level in optimization_levels: - opt_backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - optimization_level=opt_level, - shots=1000 - ) - - # Execute with optimization - result = opt_backend.run(circuit, shots=1000) - counts = result.get_counts() - - print(f"\nOptimization level {opt_level}:") - print(f" Result distribution: {len(counts)} unique outcomes") - print(f" Most probable: {max(counts.keys(), key=counts.get)} " - f"({max(counts.values())/1000:.3f})") + for i in range(5): + circuit.rz(np.pi / 4, i) + circuit.measure_all(add_bits=False) + print(f"Original: {circuit.size()} gates, depth {circuit.depth()}") + + # backend.backend is the underlying AerSimulator + for level in range(4): + compiled = transpile(circuit, backend.backend, optimization_level=level) + counts = backend.execute_circuit(compiled, shots=1000)['counts'] + print(f"Level {level}: {compiled.size()} gates, depth {compiled.depth()}, " + f"{len(counts)} outcomes") + demonstrate_transpilation() ``` +`execute_circuit` itself transpiles with Qiskit's default settings; there is no `optimization_level` argument on `QiskitBackend` in 0.3.0. + ### Custom Noise Models ```python def create_custom_noise_models(): - """Create and use custom noise models.""" - - try: - from qiskit_aer.noise import (NoiseModel, depolarizing_error, - thermal_relaxation_error, ReadoutError) - - # Create custom noise model - noise_model = NoiseModel() - - # Single-qubit gate errors - single_qubit_error = depolarizing_error(0.001, 1) # 0.1% error rate - noise_model.add_all_qubit_quantum_error(single_qubit_error, ['u1', 'u2', 'u3']) - - # Two-qubit gate errors - two_qubit_error = depolarizing_error(0.01, 2) # 1% error rate - noise_model.add_all_qubit_quantum_error(two_qubit_error, ['cx']) - - # Thermal relaxation - t1 = 50000 # T1 time (ns) - t2 = 70000 # T2 time (ns) - - for qubit in range(5): # Apply to 5 qubits - thermal_error = thermal_relaxation_error(t1, t2, 35) # 35ns gate time - noise_model.add_quantum_error(thermal_error, ['u1', 'u2', 'u3'], [qubit]) - - # Readout errors - readout_error = ReadoutError([[0.95, 0.05], [0.1, 0.9]]) # Asymmetric readout - noise_model.add_all_qubit_readout_error(readout_error) - - print("Custom noise model created:") - print(f" Quantum errors: {len(noise_model.noise_instructions)}") - print(f" Readout errors: {len(noise_model._default_readout_errors)}") - - # Use custom noise model - backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - noise_model=noise_model, - shots=2000 + """Build a Qiskit Aer noise model and compare clean and noisy results.""" + from qiskit_aer import AerSimulator + from qiskit_aer.noise import ( + NoiseModel, + ReadoutError, + depolarizing_error, + thermal_relaxation_error, + ) + + noise_model = NoiseModel() + noise_model.add_all_qubit_quantum_error(depolarizing_error(0.001, 1), ['h', 'x']) + noise_model.add_all_qubit_quantum_error(depolarizing_error(0.01, 2), ['cx']) + for qubit in range(3): # T1 = 50 us, T2 = 70 us, 35 ns gates + noise_model.add_quantum_error( + thermal_relaxation_error(50_000, 70_000, 35), ['id'], [qubit] ) - - # Test various circuits - test_circuits = { - 'Single H': lambda: backend.create_circuit(1).h(0).measure_all(), - 'Bell State': lambda: backend.create_circuit(2).h(0).cx(0,1).measure_all(), - 'GHZ State': lambda: backend.create_circuit(3).h(0).cx(0,1).cx(1,2).measure_all() - } - - print("\nNoise impact analysis:") - - for name, circuit_func in test_circuits.items(): - # Noiseless simulation - clean_backend = sqx.QiskitBackend(backend_name='qasm_simulator', shots=2000) - clean_circuit = circuit_func() - clean_result = clean_backend.run(clean_circuit, shots=2000) - clean_counts = clean_result.get_counts() - - # Noisy simulation - noisy_circuit = circuit_func() - noisy_result = backend.run(noisy_circuit, shots=2000) - noisy_counts = noisy_result.get_counts() - - # Compare fidelities - if name == 'Single H': - # Expected: 50-50 distribution - clean_fidelity = min(clean_counts.get('0', 0), clean_counts.get('1', 0)) / 1000 - noisy_fidelity = min(noisy_counts.get('0', 0), noisy_counts.get('1', 0)) / 1000 - else: - # Expected: only |00..0⟩ and |11..1⟩ - all_zeros = '0' * (2 if 'Bell' in name else 3) - all_ones = '1' * (2 if 'Bell' in name else 3) - - clean_fidelity = (clean_counts.get(all_zeros, 0) + - clean_counts.get(all_ones, 0)) / 2000 - noisy_fidelity = (noisy_counts.get(all_zeros, 0) + - noisy_counts.get(all_ones, 0)) / 2000 - - fidelity_loss = clean_fidelity - noisy_fidelity - - print(f" {name}:") - print(f" Clean fidelity: {clean_fidelity:.3f}") - print(f" Noisy fidelity: {noisy_fidelity:.3f}") - print(f" Fidelity loss: {fidelity_loss:.3f}") - - except ImportError: - print("Noise modeling requires: pip install qiskit-aer") + noise_model.add_all_qubit_readout_error(ReadoutError([[0.95, 0.05], [0.1, 0.9]])) + print("Noisy instructions:", noise_model.noise_instructions) + + clean = sqx.QiskitBackend(shots=2000) + noisy = sqx.QiskitBackend(shots=2000) + noisy.backend = AerSimulator(noise_model=noise_model) # swap in the noisy simulator + + for n in (2, 3): # Bell and GHZ states + fidelities = [] + for b in (clean, noisy): + circuit = b.create_circuit(n) + b.add_gate(circuit, 'H', 0) + for q in range(n - 1): + b.add_gate(circuit, 'CNOT', [q, q + 1]) + counts = b.execute_circuit(circuit)['counts'] + fidelities.append((counts.get('0' * n, 0) + counts.get('1' * n, 0)) / 2000) + print(f" {n}-qubit GHZ: clean {fidelities[0]:.3f}, noisy {fidelities[1]:.3f}") + create_custom_noise_models() ``` @@ -551,263 +325,101 @@ create_custom_noise_models() ```python def demonstrate_error_mitigation(): - """Show error mitigation techniques with Qiskit.""" - - try: - from qiskit_aer.noise import NoiseModel, depolarizing_error - - # Create noisy backend - noise_model = NoiseModel() - error = depolarizing_error(0.02, 1) # 2% single-qubit error - noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) - - noisy_backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - noise_model=noise_model, - shots=2000 - ) - - # Test circuit: |+⟩ state - def create_plus_state(): - circuit = noisy_backend.create_circuit(1) - circuit.h(0) - circuit.measure_all() - return circuit - - # 1. Zero-noise extrapolation - print("Error Mitigation: Zero-Noise Extrapolation") - - noise_factors = [1, 2, 3] # Amplify noise by these factors - expectation_values = [] - - for factor in noise_factors: - # Amplify noise by repeating gates - circuit = noisy_backend.create_circuit(1) - - # Apply H gate 'factor' times (odd repetitions = H, even = I) - for _ in range(factor): - circuit.h(0) - - # If even number of H gates, apply one more to get |+⟩ - if factor % 2 == 0: - circuit.h(0) - - circuit.measure_all() - - result = noisy_backend.run(circuit, shots=2000) - counts = result.get_counts() - - # Expectation value of |+⟩ state - prob_0 = counts.get('0', 0) / 2000 - expectation = 2 * prob_0 - 1 # Convert to [-1, 1] - expectation_values.append(expectation) - - print(f" Noise factor {factor}: = {expectation:.3f}") - - # Extrapolate to zero noise - # Fit linear model and extrapolate to factor=0 - import numpy as np - coeffs = np.polyfit(noise_factors, expectation_values, 1) - zero_noise_value = coeffs[1] # y-intercept - - print(f" Extrapolated zero-noise: = {zero_noise_value:.3f}") - print(f" Theoretical value: = 0.000") - print(f" Error correction: {abs(zero_noise_value):.3f}") - - # 2. Readout error mitigation - print(f"\nError Mitigation: Readout Correction") - - # Calibrate readout errors - def calibrate_readout(): - # Measure |0⟩ state - circuit_0 = noisy_backend.create_circuit(1) - circuit_0.measure_all() - result_0 = noisy_backend.run(circuit_0, shots=1000) - counts_0 = result_0.get_counts() - - # Measure |1⟩ state - circuit_1 = noisy_backend.create_circuit(1) - circuit_1.x(0) # Prepare |1⟩ - circuit_1.measure_all() - result_1 = noisy_backend.run(circuit_1, shots=1000) - counts_1 = result_1.get_counts() - - # Build calibration matrix - p00 = counts_0.get('0', 0) / 1000 # P(measure 0 | prepared 0) - p01 = counts_0.get('1', 0) / 1000 # P(measure 1 | prepared 0) - p10 = counts_1.get('0', 0) / 1000 # P(measure 0 | prepared 1) - p11 = counts_1.get('1', 0) / 1000 # P(measure 1 | prepared 1) - - calibration_matrix = np.array([[p00, p10], [p01, p11]]) - return calibration_matrix - - cal_matrix = calibrate_readout() - print(f" Calibration matrix:") - print(f" [[{cal_matrix[0,0]:.3f}, {cal_matrix[0,1]:.3f}],") - print(f" [{cal_matrix[1,0]:.3f}, {cal_matrix[1,1]:.3f}]]") - - # Test readout correction - test_circuit = create_plus_state() - raw_result = noisy_backend.run(test_circuit, shots=1000) - raw_counts = raw_result.get_counts() - - # Apply correction - raw_probs = np.array([ - raw_counts.get('0', 0) / 1000, - raw_counts.get('1', 0) / 1000 - ]) - - corrected_probs = np.linalg.inv(cal_matrix) @ raw_probs - - print(f" Raw probabilities: [P(0)={raw_probs[0]:.3f}, P(1)={raw_probs[1]:.3f}]") - print(f" Corrected probs: [P(0)={corrected_probs[0]:.3f}, P(1)={corrected_probs[1]:.3f}]") - print(f" Theoretical: [P(0)=0.500, P(1)=0.500]") - - # Calculate improvement - raw_error = abs(raw_probs[0] - 0.5) + abs(raw_probs[1] - 0.5) - corrected_error = abs(corrected_probs[0] - 0.5) + abs(corrected_probs[1] - 0.5) - improvement = (raw_error - corrected_error) / raw_error * 100 - - print(f" Error reduction: {improvement:.1f}%") - - except ImportError: - print("Error mitigation requires advanced Qiskit components") + """Zero-noise extrapolation and readout correction on a noisy Aer simulator.""" + from qiskit_aer import AerSimulator + from qiskit_aer.noise import NoiseModel, ReadoutError, depolarizing_error + + noise_model = NoiseModel() + noise_model.add_all_qubit_quantum_error(depolarizing_error(0.02, 1), ['x']) + noise_model.add_all_qubit_readout_error(ReadoutError([[0.97, 0.03], [0.06, 0.94]])) + noisy = sqx.QiskitBackend(shots=4000) + noisy.backend = AerSimulator(noise_model=noise_model) + + # 1. Zero-noise extrapolation: X^(2k+1) = X, but noise grows with k + print("Zero-noise extrapolation (ideal of |1> is -1):") + factors, values = [1, 3, 5], [] + for factor in factors: + circuit = noisy.create_circuit(1) + for _ in range(factor): + circuit.x(0) + circuit.barrier() # stop the transpiler from cancelling X pairs + circuit.measure_all(add_bits=False) + counts = noisy.execute_circuit(circuit)['counts'] + z = (counts.get('0', 0) - counts.get('1', 0)) / 4000 + values.append(z) + print(f" noise factor {factor}: = {z:.3f}") + zero_noise = np.polyfit(factors, values, 1)[1] + print(f" extrapolated: = {zero_noise:.3f}") + + # 2. Readout correction from a calibration matrix + def measure(prep_one): + circuit = noisy.create_circuit(1) + if prep_one: + circuit.x(0) + circuit.measure_all(add_bits=False) + counts = noisy.execute_circuit(circuit)['counts'] + return np.array([counts.get('0', 0), counts.get('1', 0)]) / 4000 + + cal = np.column_stack([measure(False), measure(True)]) # columns: prepared 0, prepared 1 + raw = measure(True) + corrected = np.linalg.solve(cal, raw) + print(f"Readout correction: raw P(1)={raw[1]:.3f}, corrected P(1)={corrected[1]:.3f}") + demonstrate_error_mitigation() ``` +SuperQuantX also has helpers for this in `superquantx.noise` (`ZeroNoiseExtrapolation`) and `superquantx.measurements.ResultAnalyzer`; note that `ResultAnalyzer.readout_error_mitigation` is a placeholder in 0.3.0 and returns the counts unchanged. + ## Performance Optimization ### Execution Time Analysis ```python -def qiskit_performance_analysis(): - """Analyze Qiskit backend performance characteristics.""" - - import time - - # Test different simulators - simulators = [ - ('qasm_simulator', 'Basic QASM simulator'), - ('statevector_simulator', 'Statevector simulator'), - ] - - # Circuit complexity levels - complexities = [ - (2, 1, "Simple 2-qubit, 1 layer"), - (4, 2, "Medium 4-qubit, 2 layers"), - (6, 3, "Complex 6-qubit, 3 layers"), - ] - - results = {} - - print("Qiskit Performance Analysis") - print("=" * 30) - - for sim_name, sim_desc in simulators: - print(f"\nTesting {sim_name} ({sim_desc}):") - results[sim_name] = {} - - try: - for n_qubits, n_layers, desc in complexities: - # Create test circuit - backend = sqx.QiskitBackend( - backend_name=sim_name, - shots=1000, - optimization_level=2 - ) - - circuit = backend.create_circuit(n_qubits) - - # Build parameterized circuit - params = np.random.random(n_qubits * n_layers * 2) * 2 * np.pi - param_idx = 0 - - for layer in range(n_layers): - # Rotation layer - for qubit in range(n_qubits): - circuit.ry(params[param_idx], qubit) - param_idx += 1 - circuit.rz(params[param_idx], qubit) - param_idx += 1 - - # Entangling layer - for qubit in range(n_qubits - 1): - circuit.cx(qubit, qubit + 1) - - circuit.measure_all() - - # Time execution - start_time = time.time() - result = backend.run(circuit, shots=1000) - execution_time = time.time() - start_time - - results[sim_name][(n_qubits, n_layers)] = { - 'time': execution_time, - 'counts': len(result.get_counts()) - } - - print(f" {desc}: {execution_time:.3f}s " - f"({len(result.get_counts())} unique outcomes)") - - except Exception as e: - print(f" Error with {sim_name}: {e}") - - # Shot count vs accuracy analysis - print(f"\nShot Count vs Accuracy Analysis:") - backend = sqx.QiskitBackend(backend_name='qasm_simulator') - - # Bell state circuit - circuit = backend.create_circuit(2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - shot_counts = [100, 500, 1000, 2000, 5000] - theoretical_prob = 0.5 # For Bell state |00⟩ probability - - for shots in shot_counts: - start_time = time.time() - result = backend.run(circuit, shots=shots) - exec_time = time.time() - start_time - - counts = result.get_counts() - prob_00 = counts.get('00', 0) / shots - error = abs(prob_00 - theoretical_prob) - - print(f" {shots:4d} shots: P(00)={prob_00:.3f}, " - f"Error={error:.3f}, Time={exec_time:.3f}s") - - # Optimization level impact - print(f"\nOptimization Level Impact:") - - # Complex circuit for optimization testing - test_backend = sqx.QiskitBackend(backend_name='qasm_simulator') - complex_circuit = test_backend.create_circuit(4) - - # Create circuit that can be optimized - for i in range(4): - complex_circuit.h(i) - complex_circuit.x(i) # These X gates after H can be optimized - complex_circuit.h(i) # H-X-H = Z-H can be optimized - - for i in range(3): - complex_circuit.cx(i, i + 1) - - complex_circuit.measure_all() - - for opt_level in range(4): - opt_backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - optimization_level=opt_level, - shots=1000 - ) - - start_time = time.time() - result = opt_backend.run(complex_circuit, shots=1000) - exec_time = time.time() - start_time - - print(f" Opt level {opt_level}: {exec_time:.3f}s") +import time + +import numpy as np +from qiskit import transpile + + +def qiskit_performance_analysis(seed=0): + """Execution time by circuit size, and shot count against accuracy.""" + rng = np.random.default_rng(seed) + backend = sqx.QiskitBackend(device='aer_simulator') + + for n_qubits, n_layers in [(2, 1), (4, 2), (6, 3)]: + circuit = backend.create_circuit(n_qubits) + for _ in range(n_layers): + for q in range(n_qubits): + circuit.ry(rng.uniform(0, 2 * np.pi), q) + circuit.rz(rng.uniform(0, 2 * np.pi), q) + for q in range(n_qubits - 1): + circuit.cx(q, q + 1) + start = time.time() + counts = backend.execute_circuit(circuit, shots=1000)['counts'] + print(f" {n_qubits} qubits, {n_layers} layers: {time.time() - start:.3f}s, " + f"{len(counts)} unique outcomes") + + # Shot count against sampling error for a Bell state + bell = backend.create_circuit(2) + bell.h(0) + bell.cx(0, 1) + for shots in [100, 1000, 10000]: + p00 = backend.execute_circuit(bell, shots=shots)['counts'].get('00', 0) / shots + print(f" {shots:5d} shots: P(00)={p00:.3f}, error={abs(p00 - 0.5):.3f}") + + # Transpiler optimisation levels on a circuit with removable gates + redundant = backend.create_circuit(4) + for q in range(4): + redundant.h(q) + redundant.x(q) + redundant.h(q) # H X H = Z + for q in range(3): + redundant.cx(q, q + 1) + for level in range(4): + out = transpile(redundant, backend.backend, optimization_level=level) + print(f" Opt level {level}: {out.size()} gates, depth {out.depth()}") + qiskit_performance_analysis() ``` @@ -818,99 +430,23 @@ qiskit_performance_analysis() ```python def qiskit_quantum_ml_example(): - """Comprehensive QML example using Qiskit backend.""" - + """Quantum SVM on the Qiskit backend.""" from sklearn.datasets import make_classification + from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler - from sklearn.metrics import accuracy_score - - print("Quantum Machine Learning with Qiskit") - print("=" * 38) - - # Generate dataset - X, y = make_classification( - n_samples=100, - n_features=4, - n_classes=2, - n_redundant=0, - random_state=42 - ) - - # Preprocess data - scaler = StandardScaler() - X_scaled = scaler.fit_transform(X) - - X_train, X_test, y_train, y_test = train_test_split( - X_scaled, y, test_size=0.3, random_state=42 - ) - - print(f"Dataset: {len(X)} samples, {X.shape[1]} features, 2 classes") + + X, y = make_classification(n_samples=60, n_features=4, n_redundant=0, random_state=42) + X = StandardScaler().fit_transform(X) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) print(f"Training: {len(X_train)}, Testing: {len(X_test)}") - - # Create Quantum SVM using Qiskit backend - qsvm = sqx.QuantumSVM( - backend='qiskit', - feature_map='ZFeatureMap', - num_features=4, - shots=1024 - ) - - # Train quantum SVM - print("\nTraining Quantum SVM with Qiskit backend...") - qsvm.fit(X_train, y_train) - - # Make predictions - train_pred = qsvm.predict(X_train) - test_pred = qsvm.predict(X_test) - - train_acc = accuracy_score(y_train, train_pred) - test_acc = accuracy_score(y_test, test_pred) - - print(f"Training Accuracy: {train_acc:.3f}") - print(f"Test Accuracy: {test_acc:.3f}") - - # Compare with different Qiskit simulators - simulators = ['qasm_simulator', 'statevector_simulator'] - - print(f"\nComparing Qiskit simulators:") - for sim in simulators: - try: - sim_qsvm = sqx.QuantumSVM( - backend=sqx.QiskitBackend(backend_name=sim), - feature_map='ZFeatureMap', - num_features=4 - ) - - sim_qsvm.fit(X_train, y_train) - sim_pred = sim_qsvm.predict(X_test) - sim_acc = accuracy_score(y_test, sim_pred) - - print(f" {sim}: {sim_acc:.3f}") - - except Exception as e: - print(f" {sim}: Error - {e}") - - # Feature map comparison - print(f"\nFeature map comparison:") - feature_maps = ['ZFeatureMap', 'ZZFeatureMap', 'PauliFeatureMap'] - - for fm in feature_maps: - try: - fm_qsvm = sqx.QuantumSVM( - backend='qiskit', - feature_map=fm, - num_features=4 - ) - - fm_qsvm.fit(X_train, y_train) - fm_pred = fm_qsvm.predict(X_test) - fm_acc = accuracy_score(y_test, fm_pred) - - print(f" {fm}: {fm_acc:.3f}") - - except Exception as e: - print(f" {fm}: Error - {e}") + + # Train on the Qiskit backend with each feature map + for fm in ['ZFeatureMap', 'ZZFeatureMap', 'PauliFeatureMap']: + fm_qsvm = sqx.QuantumSVM(backend=sqx.QiskitBackend(), feature_map=fm, feature_map_reps=1) + fm_acc = accuracy_score(y_test, fm_qsvm.fit(X_train, y_train).predict(X_test)) + print(f" {fm}: {fm_acc:.3f}") + qiskit_quantum_ml_example() ``` @@ -921,58 +457,56 @@ qiskit_quantum_ml_example() #### 1. IBM Quantum Authentication +!!! note "Requires credentials" + Needs an IBM Quantum token; not run. Current `qiskit-ibm-runtime` accepts `channel="ibm_quantum_platform"` or `"ibm_cloud"`; the old `"ibm_quantum"` channel is rejected. + + ```python -# Fix authentication issues from qiskit_ibm_runtime import QiskitRuntimeService -# Check saved accounts -saved_accounts = QiskitRuntimeService.saved_accounts() -print("Saved accounts:", saved_accounts) +print("Saved accounts:", QiskitRuntimeService.saved_accounts()) -# Re-save credentials if needed QiskitRuntimeService.save_account( - channel="ibm_quantum", + channel="ibm_quantum_platform", token="YOUR_TOKEN", - overwrite=True + overwrite=True, ) ``` #### 2. Backend Availability +!!! note "Requires credentials" + Needs an IBM Quantum account; not run. + + ```python -# Check backend status -def check_backend_status(): - try: - service = QiskitRuntimeService() - backends = service.backends() - - for backend in backends: - status = backend.status() - print(f"{backend.name}: " - f"operational={status.operational}, " - f"pending_jobs={status.pending_jobs}") - except Exception as e: - print(f"Cannot check backends: {e}") +from qiskit_ibm_runtime import QiskitRuntimeService -check_backend_status() +for ibm_backend in QiskitRuntimeService().backends(): + status = ibm_backend.status() + print(f"{ibm_backend.name}: operational={status.operational}, " + f"pending_jobs={status.pending_jobs}") ``` #### 3. Memory Issues ```python -# Optimize for large circuits -backend = sqx.QiskitBackend( - backend_name='qasm_simulator', - max_parallel_threads=1, # Reduce memory usage - shots=1000, - optimization_level=3 # More optimization -) +# Large circuits: the matrix-product-state method needs far less memory +# than a full statevector for weakly entangled circuits +backend = sqx.QiskitBackend(device='matrix_product_state', shots=1000) + +wide = backend.create_circuit(40) +backend.add_gate(wide, 'H', 0) +for q in range(39): + backend.add_gate(wide, 'CNOT', [q, q + 1]) +counts = backend.execute_circuit(wide)['counts'] +print(sorted(counts)) # only all-zeros and all-ones ``` ### Performance Tips 1. **Use appropriate simulators**: `statevector_simulator` for small circuits, `qasm_simulator` for general use -2. **Optimize circuits**: Use `optimization_level=3` for hardware execution +2. **Optimize circuits**: transpile with `qiskit.transpile(circuit, backend.backend, optimization_level=3)` before hardware execution 3. **Manage shots**: Balance accuracy vs execution time 4. **Batch jobs**: Submit multiple circuits together when possible 5. **Monitor queue**: Check IBM Quantum queue status before submission @@ -983,55 +517,52 @@ backend = sqx.QiskitBackend( ```python # qiskit_helpers.py +import time + + class QiskitHelpers: @staticmethod - def create_efficient_backend(n_qubits, use_hardware=False): - if use_hardware: - return sqx.QiskitBackend( - backend_name='least_busy', - optimization_level=3, - shots=1024 - ) - else: - simulator = 'statevector_simulator' if n_qubits <= 10 else 'qasm_simulator' - return sqx.QiskitBackend( - backend_name=simulator, - optimization_level=2, - shots=1000 - ) - + def create_efficient_backend(n_qubits, ibm_device=None, provider=None): + if ibm_device: # requires credentials + return sqx.QiskitBackend(device=ibm_device, provider=provider, shots=1024) + method = 'statevector' if n_qubits <= 20 else 'matrix_product_state' + return sqx.QiskitBackend(device=method, shots=1000) + @staticmethod def submit_with_retry(backend, circuit, max_retries=3): for attempt in range(max_retries): try: - return backend.run(circuit) - except Exception as e: + return backend.execute_circuit(circuit) + except Exception: if attempt == max_retries - 1: - raise e + raise print(f"Attempt {attempt + 1} failed, retrying...") - time.sleep(2 ** attempt) # Exponential backoff + time.sleep(2 ** attempt) # exponential backoff + + +helper_backend = QiskitHelpers.create_efficient_backend(2) +bell = helper_backend.create_circuit(2) +bell.h(0) +bell.cx(0, 1) +print(QiskitHelpers.submit_with_retry(helper_backend, bell)['counts']) ``` ### Error Handling ```python -def robust_qiskit_execution(circuit, backend_name='qasm_simulator'): - """Execute circuit with comprehensive error handling.""" - +def robust_qiskit_execution(circuit, device='ibm_brisbane', fallback='aer_simulator'): + """Try a device and fall back to the local Aer simulator on failure.""" try: - backend = sqx.QiskitBackend(backend_name=backend_name) - result = backend.run(circuit, shots=1000) - return result - + return sqx.QiskitBackend(device=device).execute_circuit(circuit, shots=1000) except Exception as e: - print(f"Execution failed with {backend_name}: {e}") - - # Fallback to basic simulator - if backend_name != 'qasm_simulator': - print("Falling back to qasm_simulator...") - return robust_qiskit_execution(circuit, 'qasm_simulator') - else: - raise e + print(f"Execution failed with {device}: {e.__class__.__name__}") + if device == fallback: + raise + print(f"Falling back to {fallback}...") + return robust_qiskit_execution(circuit, fallback, fallback) + + +print(robust_qiskit_execution(bell)['counts']) ``` ## Resources @@ -1051,7 +582,7 @@ def robust_qiskit_execution(circuit, backend_name='qasm_simulator'): *The Qiskit backend runs on Qiskit Aer and is tested on the simulator. IBM Quantum hardware access goes through qiskit-ibm-runtime with your own credentials and is untested.* !!! tip "Optimization" - For best performance on IBM hardware, use `optimization_level=3` and minimize circuit depth. Consider using Qiskit Runtime for reduced latency. + For best performance on IBM hardware, transpile with `optimization_level=3` and minimize circuit depth. Consider using Qiskit Runtime for reduced latency. !!! warning "Queue Times" Real IBM quantum hardware may have significant queue times. Check device status and consider using simulators for development. diff --git a/docs/backends/simulator.md b/docs/backends/simulator.md index fb2999d..d0e43d3 100644 --- a/docs/backends/simulator.md +++ b/docs/backends/simulator.md @@ -1,32 +1,23 @@ # 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. +The Python simulator is a pure-Python statevector backend that ships with +SuperQuantX. It needs no extra dependencies and is the default choice for +tests, tutorials and local experiments. ## Overview -The Simulator backend in SuperQuantX offers: +- Pure Python, no Qiskit / PennyLane / Cirq required +- Direct statevector access +- Fluent gate methods on the circuit object (`circuit.h(0)`, `circuit.cx(0, 1)`) + **and** the portable `backend.add_gate` API +- Feature maps, kernels and variational Ansätze shared with the other backends -- **Pure Python Implementation**: No external quantum computing dependencies -- **Educational Value**: Clear, readable quantum simulation code -- **Rapid Development**: Fast prototyping without backend setup -- **Statevector Access**: Direct access to quantum state amplitudes -- **Feature Maps**: Built-in quantum machine learning encoding circuits -- **Variational Ansätze**: Common parameterized circuit templates -- **Gradient Support**: Numerical differentiation for optimization - -!!! note "Performance Considerations" - This backend is optimized for clarity and simplicity rather than performance. For larger quantum circuits, consider using specialized quantum simulators. +It favours clarity over speed. For larger circuits prefer PennyLane Lightning, +Qiskit Aer or Cirq. ## Installation -The Simulator backend is included with SuperQuantX and requires no additional dependencies: - ```bash -# Install SuperQuantX (simulator included) uv add "superquantx==0.3.0" ``` @@ -35,921 +26,162 @@ uv add "superquantx==0.3.0" ```python import superquantx as sqx -# Initialize simulator backend -backend = sqx.get_backend('simulator') -print(f"Simulator backend loaded: {backend.is_available()}") -print(f"Max qubits: {backend.max_qubits}") +backend = sqx.get_backend("simulator") +print(backend.is_available()) +print(backend.max_qubits) +print(backend.get_backend_info()["backend_name"]) ``` ## Quick Start -### Basic Quantum Circuit +### Portable API ```python import superquantx as sqx -import numpy as np -# Initialize simulator backend -backend = sqx.get_backend('simulator', max_qubits=5, shots=1024) +backend = sqx.get_backend("simulator", max_qubits=5, shots=1024) -# Create a simple Bell state circuit circuit = backend.create_circuit(2) +circuit = backend.add_gate(circuit, "H", 0) +circuit = backend.add_gate(circuit, "CX", [0, 1]) +circuit = backend.add_measurement(circuit) -# Add quantum gates -circuit = backend.add_gate(circuit, 'H', 0) # Hadamard on qubit 0 -circuit = backend.add_gate(circuit, 'CX', [0, 1]) # CNOT gate - -# Execute the circuit result = backend.execute_circuit(circuit, shots=1000) -print("Bell state results:", result['counts']) - -# Expected output: roughly equal probabilities for '00' and '11' -``` - -### Parameterized Circuit - -```python -# Create circuit with rotation gates -circuit = backend.create_circuit(3) - -# Add parameterized gates -circuit = backend.add_gate(circuit, 'RY', 0, [np.pi/4]) # π/4 rotation -circuit = backend.add_gate(circuit, 'RX', 1, [np.pi/3]) # π/3 rotation -circuit = backend.add_gate(circuit, 'RZ', 2, [np.pi/2]) # π/2 rotation - -# Add entangling gates -circuit = backend.add_gate(circuit, 'CX', [0, 1]) -circuit = backend.add_gate(circuit, 'CX', [1, 2]) - -# Get statevector -statevector = backend.get_statevector(circuit) -print(f"Statevector shape: {statevector.shape}") -print(f"Statevector norm: {np.linalg.norm(statevector):.6f}") +print(result["counts"]) ``` -## Configuration - -### Backend Initialization - -```python -# Basic configuration -backend = sqx.SimulatorBackend( - device='simulator', - max_qubits=10, # Maximum qubits to simulate - shots=1024 # Default measurement shots -) - -# High-precision simulation -backend_precise = sqx.SimulatorBackend( - max_qubits=8, - shots=10000 # More shots for better statistics -) +### Fluent Simulator API -# Development/testing configuration -backend_dev = sqx.SimulatorBackend( - max_qubits=4, - shots=100 # Fast execution for testing -) -``` - -### Simulator Capabilities +On the simulator only, the circuit object is a `QuantumState` with gate +methods and `backend.run` returns a `QuantumResult`: ```python -# Check simulator capabilities -capabilities = backend.capabilities - -print("Simulator capabilities:") -for capability, supported in capabilities.items(): - print(f" {capability}: {supported}") - -# Output includes: -# supports_gradient: True -# supports_parameter_shift: True -# supports_finite_diff: True -# supports_backprop: False (not implemented) -# supports_hardware: False -# supports_noise_models: False -``` - -## Gate Operations - -### Single-Qubit Gates - -```python -circuit = backend.create_circuit(3) - -# Pauli gates -circuit = backend.add_gate(circuit, 'X', 0) # Pauli-X (NOT) -circuit = backend.add_gate(circuit, 'Y', 1) # Pauli-Y -circuit = backend.add_gate(circuit, 'Z', 2) # Pauli-Z - -# Hadamard gate -circuit = backend.add_gate(circuit, 'H', 0) - -# Phase gates -circuit = backend.add_gate(circuit, 'S', 1) # S gate (√Z) -circuit = backend.add_gate(circuit, 'T', 2) # T gate (⁴√Z) +import superquantx as sqx -# Rotation gates -circuit = backend.add_gate(circuit, 'RX', 0, [np.pi/2]) # X-rotation -circuit = backend.add_gate(circuit, 'RY', 1, [np.pi/3]) # Y-rotation -circuit = backend.add_gate(circuit, 'RZ', 2, [np.pi/4]) # Z-rotation +backend = sqx.get_backend("simulator") +circuit = backend.create_circuit(2) +circuit.h(0) +circuit.cx(0, 1) +circuit.measure_all() -# Available single-qubit gates -available_gates = backend.gates.keys() -print("Available gates:", list(available_gates)) +result = backend.run(circuit, shots=1000) +print(result.get_counts()) ``` -### Two-Qubit Gates - -```python -circuit = backend.create_circuit(4) +Other backends do not implement these fluent methods. Prefer `add_gate` / +`execute_circuit` when you want portable examples. -# CNOT gate (Controlled-X) -circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) -circuit = backend.add_gate(circuit, 'CX', [0, 1]) # Same as CNOT - -# Controlled-Z gate -circuit = backend.add_gate(circuit, 'CZ', [1, 2]) - -# SWAP gate -circuit = backend.add_gate(circuit, 'SWAP', [2, 3]) - -# Execute and measure -result = backend.execute_circuit(circuit) -print("Two-qubit circuit results:", result['counts']) -``` - -### Multi-Qubit Gates +### Parameterized Circuit and Statevector ```python -# Toffoli gate (CCX - simplified implementation) -circuit = backend.create_circuit(4) -circuit = backend.add_gate(circuit, 'H', 0) -circuit = backend.add_gate(circuit, 'H', 1) -circuit = backend.add_gate(circuit, 'CCX', [0, 1, 2]) # Control qubits 0,1, target 2 - -# Note: Toffoli implementation is simplified in the current backend -print("Toffoli circuit executed (simplified implementation)") -``` - -## Advanced Features - -### Statevector Analysis +import numpy as np +import superquantx as sqx -```python -def analyze_quantum_state(backend, circuit): - """Analyze quantum state properties.""" - - # Get statevector - statevector = backend.get_statevector(circuit) - n_qubits = backend._get_n_qubits(circuit) - - # Calculate probabilities - probabilities = np.abs(statevector)**2 - - # Find dominant basis states - dominant_indices = np.where(probabilities > 0.01)[0] - - print(f"Quantum State Analysis ({n_qubits} qubits):") - print(f"Statevector dimension: {len(statevector)}") - print(f"Normalization: {np.linalg.norm(statevector):.6f}") - print(f"Entropy: {-np.sum(probabilities * np.log2(probabilities + 1e-16)):.4f}") - - print("\nDominant basis states:") - for idx in dominant_indices: - basis_state = format(idx, f'0{n_qubits}b') - amplitude = statevector[idx] - probability = probabilities[idx] - print(f"|{basis_state}⟩: amplitude = {amplitude:.4f}, probability = {probability:.4f}") - - return { - 'statevector': statevector, - 'probabilities': probabilities, - 'entropy': -np.sum(probabilities * np.log2(probabilities + 1e-16)) - } - -# Example: Analyze GHZ state +backend = sqx.get_backend("simulator") circuit = backend.create_circuit(3) -circuit = backend.add_gate(circuit, 'H', 0) -circuit = backend.add_gate(circuit, 'CX', [0, 1]) -circuit = backend.add_gate(circuit, 'CX', [1, 2]) - -analysis = analyze_quantum_state(backend, circuit) -``` - -### Quantum Feature Maps - -```python -def demonstrate_feature_maps(): - """Demonstrate quantum feature maps for machine learning.""" - - # Generate sample data - X = np.random.random((5, 3)) # 5 samples, 3 features - - # Create ZZ feature map - zz_map = backend.create_feature_map( - n_features=3, - feature_map='ZZFeatureMap', - reps=2 - ) - - # Apply feature map to first data point - encoded_circuit = zz_map(X[0]) - statevector = backend.get_statevector(encoded_circuit) - - print("ZZ Feature Map Encoding:") - print(f"Input data: {X[0]}") - print(f"Encoded statevector norm: {np.linalg.norm(statevector):.6f}") - - # Pauli feature map - pauli_map = backend.create_feature_map( - n_features=3, - feature_map='PauliFeatureMap', - reps=1 - ) - - pauli_circuit = pauli_map(X[0]) - pauli_statevector = backend.get_statevector(pauli_circuit) - - print(f"Pauli feature map statevector norm: {np.linalg.norm(pauli_statevector):.6f}") - -demonstrate_feature_maps() -``` - -### Quantum Kernel Computation +backend.add_gate(circuit, "RY", 0, [np.pi / 4]) +backend.add_gate(circuit, "RX", 1, [np.pi / 3]) +backend.add_gate(circuit, "RZ", 2, [np.pi / 2]) +backend.add_gate(circuit, "CX", [0, 1]) +backend.add_gate(circuit, "CX", [1, 2]) -```python -def compute_quantum_kernel_example(): - """Compute quantum kernel matrix.""" - - # Sample training data - X_train = np.array([ - [0.1, 0.2], - [0.4, 0.8], - [0.7, 0.3], - [0.9, 0.6] - ]) - - # Sample test data - X_test = np.array([ - [0.2, 0.3], - [0.5, 0.7] - ]) - - # Compute kernel matrix - kernel_matrix = backend.compute_kernel_matrix( - X_train, X_test, - feature_map='ZZFeatureMap', - shots=1000 - ) - - print("Quantum Kernel Matrix:") - print(kernel_matrix) - print(f"Matrix shape: {kernel_matrix.shape}") - - return kernel_matrix - -kernel_matrix = compute_quantum_kernel_example() -``` - -### Variational Ansätze - -```python -def demonstrate_ansatz_circuits(): - """Demonstrate different ansatz circuits for VQE/QAOA.""" - - n_qubits = 4 - - # Real Amplitudes ansatz - params_ra = np.random.random(8) # 2 layers × 4 qubits - ra_ansatz = backend.create_ansatz('RealAmplitudes', n_qubits, params_ra) - ra_circuit = ra_ansatz() - - print("Real Amplitudes Ansatz:") - print(f"Parameters: {params_ra}") - print(f"Circuit qubits: {backend._get_n_qubits(ra_circuit)}") - - # EfficientSU2 ansatz - params_su2 = np.random.random(12) # 1 layer × 4 qubits × 3 params - su2_ansatz = backend.create_ansatz('EfficientSU2', n_qubits, params_su2) - su2_circuit = su2_ansatz() - - print("\nEfficientSU2 Ansatz:") - print(f"Parameters: {params_su2}") - print(f"Circuit qubits: {backend._get_n_qubits(su2_circuit)}") - - # Compare statevectors - ra_state = backend.get_statevector(ra_circuit) - su2_state = backend.get_statevector(su2_circuit) - - print(f"\nRA statevector entropy: {-np.sum(np.abs(ra_state)**2 * np.log2(np.abs(ra_state)**2 + 1e-16)):.4f}") - print(f"SU2 statevector entropy: {-np.sum(np.abs(su2_state)**2 * np.log2(np.abs(su2_state)**2 + 1e-16)):.4f}") - -demonstrate_ansatz_circuits() +statevector = backend.get_statevector(circuit) +print(statevector.shape, float(np.linalg.norm(statevector))) ``` -### Expectation Value Calculations +## Configuration ```python -def hamiltonian_expectation_example(): - """Calculate expectation values with different Hamiltonians.""" - - # Create test circuit (Bell state) - circuit = backend.create_circuit(2) - circuit = backend.add_gate(circuit, 'H', 0) - circuit = backend.add_gate(circuit, 'CX', [0, 1]) - - # Simple Hamiltonian: σ_z ⊗ I - H_z = np.array([ - [1, 0, 0, 0], - [0, -1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, -1] - ]) - - expectation_z = backend.compute_expectation(circuit, H_z) - print(f"⟨ψ|σ_z ⊗ I|ψ⟩ = {expectation_z:.6f}") - - # Hamiltonian: σ_x ⊗ σ_x - H_xx = np.array([ - [0, 0, 0, 1], - [0, 0, 1, 0], - [0, 1, 0, 0], - [1, 0, 0, 0] - ]) - - expectation_xx = backend.compute_expectation(circuit, H_xx) - print(f"⟨ψ|σ_x ⊗ σ_x|ψ⟩ = {expectation_xx:.6f}") - - # For Bell state |00⟩ + |11⟩, expect: - # ⟨σ_z ⊗ I⟩ = 0 (equal superposition) - # ⟨σ_x ⊗ σ_x⟩ = 1 (maximally correlated) - - return expectation_z, expectation_xx - -exp_z, exp_xx = hamiltonian_expectation_example() -``` - -## Quantum Machine Learning Examples - -### VQE Implementation +import superquantx as sqx -```python -def simple_vqe_h2(): - """Simple VQE implementation for H2 molecule.""" - - # H2 Hamiltonian (simplified) - # H = -1.0523 I + 0.3979 Z_0 - 0.3979 Z_1 - 0.0113 Z_0*Z_1 + 0.1809 X_0*X_1 - - def h2_energy(params): - """Calculate H2 energy for given parameters.""" - # Create ansatz circuit - ansatz = backend.create_ansatz('RealAmplitudes', 2, params) - circuit = ansatz() - - # Compute expectation values for each Pauli term - statevector = backend.get_statevector(circuit) - - # Identity term - energy = -1.0523 - - # Z_0 term (σ_z ⊗ I) - H_z0 = np.diag([1, -1, 1, -1]) - energy += 0.3979 * backend.compute_expectation(circuit, H_z0) - - # Z_1 term (I ⊗ σ_z) - H_z1 = np.diag([1, 1, -1, -1]) - energy -= 0.3979 * backend.compute_expectation(circuit, H_z1) - - # Z_0*Z_1 term - H_zz = np.diag([1, -1, -1, 1]) - energy -= 0.0113 * backend.compute_expectation(circuit, H_zz) - - # X_0*X_1 term - H_xx = np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) - energy += 0.1809 * backend.compute_expectation(circuit, H_xx) - - return energy - - # Optimize parameters - from scipy.optimize import minimize - - initial_params = np.random.random(4) * 2 * np.pi - result = minimize(h2_energy, initial_params, method='COBYLA') - - print("VQE H2 Results:") - print(f"Optimal energy: {result.fun:.6f} Ha") - print(f"Optimal parameters: {result.x}") - print(f"Expected ground state: ≈ -1.137 Ha") - - return result - -# Run VQE example -vqe_result = simple_vqe_h2() +backend = sqx.SimulatorBackend(max_qubits=10, shots=1024) +print(backend.capabilities) ``` -### QAOA Implementation +## Feature Maps and Kernels -```python -def simple_qaoa_maxcut(): - """Simple QAOA for Max-Cut problem.""" - - # Define graph edges (triangle + additional edge) - edges = [(0, 1), (1, 2), (2, 0), (0, 3)] - n_nodes = 4 - - def qaoa_circuit(gamma, beta, p_layers=1): - """Create QAOA circuit.""" - circuit = backend.create_circuit(n_nodes) - - # Initial superposition - for i in range(n_nodes): - circuit = backend.add_gate(circuit, 'H', i) - - # QAOA layers - for layer in range(p_layers): - # Cost Hamiltonian (ZZ interactions) - for i, j in edges: - circuit = backend.add_gate(circuit, 'CZ', [i, j]) - circuit = backend.add_gate(circuit, 'RZ', j, [2 * gamma[layer]]) - - # Mixer Hamiltonian (X rotations) - for i in range(n_nodes): - circuit = backend.add_gate(circuit, 'RX', i, [2 * beta[layer]]) - - return circuit - - def qaoa_cost(params): - """QAOA cost function.""" - p_layers = len(params) // 2 - gamma = params[:p_layers] - beta = params[p_layers:] - - circuit = qaoa_circuit(gamma, beta, p_layers) - result = backend.execute_circuit(circuit, shots=1000) - - # Calculate cut value expectation - total_cut = 0 - total_counts = sum(result['counts'].values()) - - for bitstring, count in result['counts'].items(): - # Count edges crossing the cut - cut_value = 0 - for i, j in edges: - if bitstring[i] != bitstring[j]: - cut_value += 1 - - total_cut += (count / total_counts) * cut_value - - return -total_cut # Minimize negative cut (maximize cut) - - # Optimize QAOA - from scipy.optimize import minimize - - p_layers = 2 - initial_params = np.random.random(2 * p_layers) * np.pi - result = minimize(qaoa_cost, initial_params, method='COBYLA') - - print("QAOA Max-Cut Results:") - print(f"Optimal cut value: {-result.fun:.4f}") - print(f"Optimal parameters: {result.x}") - print(f"Maximum possible cut: {len(edges)} edges") - - return result - -# Run QAOA example -qaoa_result = simple_qaoa_maxcut() -``` - -### Quantum Neural Network +`create_feature_map` returns a `FeatureMapSpec`. Build a circuit from it with +`build_feature_map_circuit`; do not call the spec like a function. ```python -def simple_qnn_classifier(): - """Simple quantum neural network for binary classification.""" - - # Generate synthetic 2D classification data - np.random.seed(42) - n_samples = 20 - X = np.random.random((n_samples, 2)) * 2 - 1 # [-1, 1] range - y = (X[:, 0] + X[:, 1] > 0).astype(int) # Simple linear separation - - def qnn_circuit(x, params): - """Quantum neural network circuit.""" - # Data encoding - feature_map = backend.create_feature_map(2, 'ZZFeatureMap', reps=1) - circuit = feature_map(x) - - # Variational layers - ansatz = backend.create_ansatz('EfficientSU2', 2, params) - variational_circuit = ansatz() - - # Combine encoding and variational parts (simplified) - # In practice, you'd need to compose the circuits properly - return circuit - - def qnn_predict(X_batch, params): - """Make predictions with QNN.""" - predictions = [] - - for x in X_batch: - circuit = qnn_circuit(x, params) - - # Measure expectation value of Z_0 for classification - statevector = backend.get_statevector(circuit) - - # Simple measurement probability - prob_0 = np.abs(statevector[0])**2 + np.abs(statevector[2])**2 - prediction = 1 if prob_0 > 0.5 else 0 - predictions.append(prediction) - - return np.array(predictions) - - def qnn_loss(params): - """QNN training loss.""" - predictions = qnn_predict(X, params) - - # Binary cross-entropy loss (simplified) - loss = np.mean((predictions - y)**2) - return loss - - # Train QNN - initial_params = np.random.random(6) * 2 * np.pi # 6 parameters - - print("Training simple QNN...") - print(f"Initial accuracy: {np.mean(qnn_predict(X, initial_params) == y):.4f}") - - # Note: For real training, you'd use proper gradient descent - # This is a simplified demonstration - - return initial_params - -# Run QNN example -qnn_params = simple_qnn_classifier() -``` - -## Performance and Limitations - -### Performance Characteristics +import numpy as np +import superquantx as sqx -```python -def performance_analysis(): - """Analyze simulator performance.""" - import time - - qubit_counts = [2, 4, 6, 8] - execution_times = [] - - print("Performance Analysis:") - print("Qubits | Time (ms) | State Dimension") - print("-------|-----------|----------------") - - for n_qubits in qubit_counts: - if n_qubits <= backend.max_qubits: - # Create test circuit - start_time = time.time() - - circuit = backend.create_circuit(n_qubits) - - # Add gates - for i in range(n_qubits): - circuit = backend.add_gate(circuit, 'H', i) - - for i in range(n_qubits - 1): - circuit = backend.add_gate(circuit, 'CX', [i, i + 1]) - - # Execute - result = backend.execute_circuit(circuit, shots=100) - - end_time = time.time() - execution_time = (end_time - start_time) * 1000 - - execution_times.append(execution_time) - state_dim = 2**n_qubits - - print(f" {n_qubits} | {execution_time:.2f} | {state_dim}") - - print(f"\nSimulator limits:") - print(f"Max qubits: {backend.max_qubits}") - print(f"Max state dimension: {2**backend.max_qubits:,}") - -performance_analysis() -``` +backend = sqx.get_backend("simulator") +X = np.array([[0.1, 0.2, 0.3], [0.4, 0.8, 0.2], [0.7, 0.3, 0.9]]) -### Memory Usage Estimation +spec = backend.create_feature_map(n_features=3, feature_map="ZZFeatureMap", reps=2) +encoded = backend.build_feature_map_circuit(X[0], spec) +sv = backend.get_statevector(encoded) +print(spec, float(np.linalg.norm(sv))) -```python -def memory_usage_analysis(): - """Estimate memory usage for different qubit counts.""" - - print("Memory Usage Estimates:") - print("Qubits | State Vector | Memory (MB)") - print("-------|--------------|------------") - - for n_qubits in range(1, 16): - state_dim = 2**n_qubits - # Complex128: 16 bytes per complex number - memory_bytes = state_dim * 16 - memory_mb = memory_bytes / (1024**2) - - if memory_mb < 1000: # Only show reasonable sizes - print(f" {n_qubits:2d} | {state_dim:8,} | {memory_mb:8.2f}") - else: - print(f" {n_qubits:2d} | {state_dim:8,} | {memory_mb:8.0f}") - - if n_qubits >= 20: # Stop at very large sizes - break - -memory_usage_analysis() +K = backend.compute_kernel_matrix(X, X, feature_map="ZZFeatureMap", shots=200) +print(K.shape) ``` -## Error Handling and Debugging +Supported maps: `ZZFeatureMap`, `ZFeatureMap`, `PauliFeatureMap`, `AngleEncoding`. -### Comprehensive Error Handling - -```python -def robust_simulation_example(): - """Demonstrate robust simulation with error handling.""" - - import logging - - # Setup logging for debugging - logging.basicConfig(level=logging.INFO) - logger = logging.getLogger(__name__) - - def safe_circuit_execution(backend, circuit_builder, max_retries=3): - """Execute circuit with error handling.""" - - for attempt in range(max_retries): - try: - # Build circuit - circuit = circuit_builder() - - # Validate circuit - n_qubits = backend._get_n_qubits(circuit) - if n_qubits > backend.max_qubits: - raise ValueError(f"Circuit has {n_qubits} qubits, max is {backend.max_qubits}") - - # Execute circuit - result = backend.execute_circuit(circuit) - - # Validate result - if 'counts' not in result: - raise RuntimeError("Invalid execution result") - - logger.info(f"Circuit execution successful on attempt {attempt + 1}") - return result - - except Exception as e: - logger.warning(f"Attempt {attempt + 1} failed: {e}") - - if attempt == max_retries - 1: - logger.error("All retry attempts failed") - return None - - return None - - # Example circuit builder that might fail - def problematic_circuit(): - circuit = backend.create_circuit(3) - - # Add gates that might cause issues - circuit = backend.add_gate(circuit, 'H', 0) - circuit = backend.add_gate(circuit, 'UNKNOWN_GATE', 1) # Will cause warning - circuit = backend.add_gate(circuit, 'RX', 2, [np.pi/4]) - - return circuit - - # Test robust execution - result = safe_circuit_execution(backend, problematic_circuit) - - if result: - print("Robust execution successful:") - print(f"Results: {result['counts']}") - else: - print("Robust execution failed after all retries") - -robust_simulation_example() -``` +## Variational Ansätze -### Circuit Validation +`create_ansatz` returns a circuit, not a factory. ```python -def validate_circuit_construction(): - """Validate circuit construction steps.""" - - def validate_gate_application(backend, gate, qubits, params=None): - """Validate individual gate application.""" - - validation = { - 'valid': True, - 'warnings': [], - 'errors': [] - } - - # Check qubit indices - if isinstance(qubits, int): - qubits = [qubits] - - max_qubit = max(qubits) if qubits else -1 - if max_qubit >= backend.max_qubits: - validation['errors'].append(f"Qubit index {max_qubit} exceeds max {backend.max_qubits-1}") - validation['valid'] = False - - # Check gate existence - if gate.upper() not in backend.gates and not gate.upper().startswith('R'): - validation['warnings'].append(f"Gate '{gate}' may not be recognized") - - # Check parameter requirements - rotation_gates = ['RX', 'RY', 'RZ'] - if gate.upper() in rotation_gates: - if not params or len(params) == 0: - validation['errors'].append(f"Rotation gate '{gate}' requires angle parameter") - validation['valid'] = False - - return validation - - # Test various gate validations - test_cases = [ - ('H', [0], None), - ('RX', [1], [np.pi/2]), - ('RY', [2], []), # Missing parameter - should warn - ('CX', [0, 1], None), - ('UNKNOWN', [0], None), # Unknown gate - ('H', [15], None), # Invalid qubit index - ] - - print("Gate Validation Results:") - for gate, qubits, params in test_cases: - validation = validate_gate_application(backend, gate, qubits, params) - - status = "✓" if validation['valid'] else "✗" - print(f"{status} {gate} on {qubits} with params {params}") - - for warning in validation['warnings']: - print(f" ⚠ {warning}") - for error in validation['errors']: - print(f" ✗ {error}") - -validate_circuit_construction() -``` - -## Best Practices - -### Simulation Guidelines +import numpy as np +import superquantx as sqx -1. **Qubit Limits**: Keep circuits under 12 qubits for reasonable performance -2. **Gate Decomposition**: Use basic gates (H, X, Y, Z, CX) when possible -3. **Statevector Access**: Use statevector operations for debugging -4. **Parameter Optimization**: Use numerical gradients for parameter optimization +backend = sqx.get_backend("simulator") +n_qubits, reps = 4, 1 +n_params = backend.ansatz_param_count("RealAmplitudes", n_qubits, reps) +params = np.random.default_rng(0).random(n_params) -### Code Organization +ansatz = backend.create_ansatz("RealAmplitudes", n_qubits, params, reps=reps) +backend.add_measurement(ansatz) +print(backend.execute_circuit(ansatz, shots=500)["counts"]) -```python -# Example: Well-structured quantum algorithm -class QuantumAlgorithmSimulator: - """Template for quantum algorithm implementation.""" - - def __init__(self, backend, n_qubits): - self.backend = backend - self.n_qubits = n_qubits - self.circuit = None - - def initialize_circuit(self): - """Initialize quantum circuit.""" - self.circuit = self.backend.create_circuit(self.n_qubits) - return self.circuit - - def add_initialization(self): - """Add state initialization.""" - for i in range(self.n_qubits): - self.circuit = self.backend.add_gate(self.circuit, 'H', i) - - def add_algorithm_gates(self, parameters): - """Add algorithm-specific gates.""" - # Override in subclasses - pass - - def execute(self, parameters=None, shots=1000): - """Execute the quantum algorithm.""" - self.initialize_circuit() - self.add_initialization() - - if parameters: - self.add_algorithm_gates(parameters) - - return self.backend.execute_circuit(self.circuit, shots=shots) - - def get_statevector(self): - """Get current statevector.""" - if self.circuit is None: - raise ValueError("Circuit not initialized") - return self.backend.get_statevector(self.circuit) - -# Example usage -algorithm = QuantumAlgorithmSimulator(backend, n_qubits=3) -result = algorithm.execute(shots=1000) -print("Algorithm result:", result['counts']) +su2_n = backend.ansatz_param_count("EfficientSU2", n_qubits, reps) +su2 = backend.create_ansatz( + "EfficientSU2", n_qubits, np.zeros(su2_n), reps=reps +) +print(type(su2).__name__) ``` -## Troubleshooting +## Expectation Values -### Common Issues - -**Circuit Size Too Large** ```python -# Check qubit limits -if n_qubits > backend.max_qubits: - print(f"Reducing circuit size from {n_qubits} to {backend.max_qubits} qubits") - n_qubits = backend.max_qubits -``` +import numpy as np +import superquantx as sqx -**Unknown Gate Error** -```python -# Check available gates -available_gates = list(backend.gates.keys()) -print("Available gates:", available_gates) +backend = sqx.get_backend("simulator") +circuit = backend.create_circuit(2) +backend.add_gate(circuit, "H", 0) +backend.add_gate(circuit, "CX", [0, 1]) -# Use alternative gates -if 'CNOT' not in available_gates and 'CX' in available_gates: - circuit = backend.add_gate(circuit, 'CX', [0, 1]) # Use CX instead of CNOT +# Pauli dict: qubit 0 is the leftmost character of the label +zz = backend.compute_expectation(circuit, {"ZZ": 1.0}) +print(zz) ``` -**Memory Issues** -```python -# Reduce circuit size or use shot-based simulation -if n_qubits > 10: - print("Large circuit detected - consider using shot-based approaches") - shots = 10000 # More shots for better statistics with smaller circuits -``` +## Quantum ML on the Simulator -**Numerical Precision** ```python -# Check statevector normalization -statevector = backend.get_statevector(circuit) -norm = np.linalg.norm(statevector) -if abs(norm - 1.0) > 1e-10: - print(f"Warning: Statevector norm = {norm:.12f} (should be 1.0)") -``` +import numpy as np +from sklearn.datasets import make_moons +from sklearn.model_selection import train_test_split +import superquantx as sqx -### Performance Optimization +X, y = make_moons(n_samples=40, noise=0.1, random_state=0) +X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.25, random_state=0 +) -**Optimize for Small Circuits** -```python -# Use statevector operations for analysis -def efficient_small_circuit_analysis(circuit): - """Efficient analysis for small circuits.""" - - # Direct statevector computation - statevector = backend.get_statevector(circuit) - - # Calculate all probabilities at once - probabilities = np.abs(statevector)**2 - - # Find most likely outcomes - top_indices = np.argsort(probabilities)[-5:] # Top 5 - - n_qubits = backend._get_n_qubits(circuit) - results = {} - - for idx in top_indices: - bitstring = format(idx, f'0{n_qubits}b') - results[bitstring] = float(probabilities[idx]) - - return results - -# Use for small circuits instead of shot-based simulation -small_circuit = backend.create_circuit(3) -small_circuit = backend.add_gate(small_circuit, 'H', 0) -small_circuit = backend.add_gate(small_circuit, 'CX', [0, 1]) - -efficient_results = efficient_small_circuit_analysis(small_circuit) -print("Efficient analysis:", efficient_results) +qsvm = sqx.QuantumSVM(backend="simulator", feature_map="ZFeatureMap") +qsvm.fit(X_train, y_train) +print(float(np.mean(qsvm.predict(X_test) == y_test))) ``` -## API Reference - -The Simulator backend provides these key methods: - -- `create_circuit(n_qubits)`: Create quantum circuit -- `add_gate(circuit, gate, qubits, params)`: Add quantum gate -- `execute_circuit(circuit, shots)`: Execute circuit with measurements -- `get_statevector(circuit)`: Get quantum statevector -- `create_feature_map(n_features, type, reps)`: Create quantum feature map -- `create_ansatz(type, n_qubits, params)`: Create parameterized ansatz -- `compute_expectation(circuit, hamiltonian)`: Calculate expectation values -- `compute_kernel_matrix(X1, X2, feature_map)`: Compute quantum kernel matrix - -### Gate Library - -Available quantum gates: -- Single-qubit: `I`, `X`, `Y`, `Z`, `H`, `S`, `T` -- Rotations: `RX`, `RY`, `RZ` (require angle parameter) -- Two-qubit: `CNOT`, `CX`, `CZ`, `SWAP` -- Multi-qubit: `CCX` (Toffoli, simplified implementation) - -For complete API documentation, see the [API Reference](../api/backends.md#simulator-backend) section. - ---- +## Tips -*The Python Simulator backend is ideal for learning quantum computing concepts, prototyping algorithms, and testing quantum code without external dependencies.* \ No newline at end of file +- Use the fluent API for teaching; use `add_gate` for portable docs and tests. +- `backend.run(...).get_counts()` is simulator-only. Everywhere else read + `result["counts"]` from `execute_circuit`. +- Cap `max_qubits` when you want to fail fast on oversized circuits. diff --git a/docs/backends/tket.md b/docs/backends/tket.md index 653b441..de6635c 100644 --- a/docs/backends/tket.md +++ b/docs/backends/tket.md @@ -1,9 +1,5 @@ # 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 @@ -100,26 +96,26 @@ print(f"Optimized circuit: {optimized_circuit.n_gates} gates") ### Backend Initialization Options ```python -# Local simulator (default) +# Local simulator (default, needs pytket-qiskit) backend = sqx.TKETBackend(device='aer_simulator', shots=1024) -# Quantinuum H1-1E hardware -backend = sqx.TKETBackend( - device='H1-1E', - api_key='your-quantinuum-api-key', - shots=100 # Reduced shots for hardware -) +``` -# Quantinuum H1-2E (larger system) -backend = sqx.TKETBackend( - device='H1-2E', - machine='H1-2E', - api_key='your-api-key', - shots=1000 -) +The `cirq_simulator` device needs `pytket-cirq`, which is not part of the `tket` extra (`pip install pytket-cirq`): -# TKET-Cirq integration -backend = sqx.TKETBackend(device='cirq_simulator') + +```python +cirq_backend = sqx.TKETBackend(device='cirq_simulator') +``` + +Quantinuum devices (requires credentials and `pytket-quantinuum`, not run here): + + +```python +backend = sqx.TKETBackend(device='H1-1E', shots=100) + +# 'machine' overrides the device name sent to Quantinuum +backend = sqx.TKETBackend(device='H1-2E', machine='H1-2E', shots=1000) ``` ### Environment Configuration @@ -139,27 +135,14 @@ export TKET_CACHE_DIR="~/.tket_cache" TKET provides native access to Quantinuum's trapped-ion quantum computers: -```python -# H1-1E: 20-qubit ion trap system -backend_h1_1e = sqx.TKETBackend( - device='H1-1E', - api_key='your-api-key', - shots=100 -) - -# H1-2E: 56-qubit ion trap system -backend_h1_2e = sqx.TKETBackend( - device='H1-2E', - api_key='your-api-key', - shots=100 -) +!!! note "Requires credentials" + These need `pytket-quantinuum` and a Quantinuum account; checked against the 0.3.0 constructor, not run. The device name is passed to `QuantinuumBackend(device_name=...)`. `api_key` is stored on the backend, but sign-in is handled by pytket-quantinuum's own login. -# H2-1: 32-qubit second-generation system -backend_h2_1 = sqx.TKETBackend( - device='H2-1', - api_key='your-api-key', - shots=100 -) + +```python +backend_h1_1e = sqx.TKETBackend(device='H1-1E', shots=100) +backend_h1_2e = sqx.TKETBackend(device='H1-2E', shots=100) +backend_h2_1 = sqx.TKETBackend(device='H2-1', shots=100) ``` ### Hardware-Specific Compilation @@ -231,139 +214,156 @@ def _results_converged(counts1, counts2, threshold=0.01): ### Parameterized Circuits ```python -# Create parameterized circuit for variational algorithms -circuit, param_names = backend.create_parameterized_circuit( - n_qubits=4, - n_params=6 -) +# Variational circuits: rebuild the circuit with numeric angles for each +# parameter vector (there is no symbolic parameter binding in 0.3.0) +import numpy as np + + +def build_ansatz(backend, theta): + circuit = backend.create_circuit(2) + for i in range(2): + circuit = backend.add_gate(circuit, 'ry', i, [theta[i]]) + circuit = backend.add_gate(circuit, 'cx', [0, 1]) + for i in range(2): + circuit = backend.add_gate(circuit, 'ry', i, [theta[i + 2]]) + return circuit -print("Parameters:", param_names) -# Output: ['theta_0', 'theta_1', 'theta_2', 'theta_3', 'theta_4', 'theta_5'] -# Build parameterized ansatz -for i in range(4): - circuit = backend.add_gate(circuit, 'ry', i, params=[param_names[i]]) - -for i in range(3): - circuit = backend.add_gate(circuit, 'cx', [i, i+1]) - -for i in range(4): - circuit = backend.add_gate(circuit, 'ry', i, params=[param_names[i+4] if i+4 < len(param_names) else 0]) +param_values = np.array([0.5, 1.2, -0.3, 0.8]) +bound_circuit = build_ansatz(backend, param_values) -# Bind specific parameter values -param_values = { - 'theta_0': 0.5, 'theta_1': 1.2, 'theta_2': -0.3, - 'theta_3': 0.8, 'theta_4': 1.1, 'theta_5': -0.7 -} +# Or use the built-in ansatz library +print(backend.ansatz_param_count('RealAmplitudes', 2, reps=1)) # 4 +ansatz = backend.create_ansatz('RealAmplitudes', 2, param_values, reps=1) -bound_circuit = backend.bind_parameters(circuit, param_values) -result = backend.execute_circuit(bound_circuit) +measured = backend.add_measurement(bound_circuit.copy()) +print(backend.execute_circuit(measured, shots=1000)['counts']) ``` ### Custom Compiler Passes ```python from pytket.passes import ( - SequencePass, DecomposeBoxes, CliffordSimp, - RemoveRedundancies, OptimisePhaseGadgets, - PauliSimp, FullPeepholeOptimise + CliffordSimp, + DecomposeBoxes, + FullPeepholeOptimise, + PauliSimp, + RemoveRedundancies, ) +from pytket.circuit import OpType + def create_custom_optimization_pass(): - """Create custom optimization sequence.""" - return SequencePass([ - DecomposeBoxes(), # Decompose any box structures - CliffordSimp(), # Simplify Clifford gates - PauliSimp(), # Simplify Pauli gadgets - OptimisePhaseGadgets(), # Optimize phase gates - CliffordSimp(), # Second Clifford pass - FullPeepholeOptimise(), # Peephole optimizations - RemoveRedundancies(), # Remove redundant gates - ]) - -# Apply custom optimization + """A custom pass sequence, applied in stages. + + Each pass has gate-set preconditions (PauliSimp, for example, does not + accept the TK1 gates CliffordSimp produces), so order matters. + """ + return [ + DecomposeBoxes(), # expand any boxes + PauliSimp(), # resynthesise via Pauli gadgets + CliffordSimp(), # simplify Clifford subcircuits + FullPeepholeOptimise(), # local peephole rewrites + RemoveRedundancies(), # drop gates that cancel + ] + + circuit = backend.create_circuit(5) -# ... add gates ... +for i in range(5): + circuit = backend.add_gate(circuit, 'h', i) +# Two rounds of ZZ rotations; TKET merges them +for angle in (0.3, 0.2): + for i in range(4): + circuit = backend.add_gate(circuit, 'cx', [i, i + 1]) + circuit = backend.add_gate(circuit, 'rz', i + 1, [angle]) + circuit = backend.add_gate(circuit, 'cx', [i, i + 1]) -custom_pass = create_custom_optimization_pass() optimized_circuit = circuit.copy() -custom_pass.apply(optimized_circuit) +for compiler_pass in create_custom_optimization_pass(): + compiler_pass.apply(optimized_circuit) -print(f"Gates: {circuit.n_gates} → {optimized_circuit.n_gates}") +print(f"Gates: {circuit.n_gates} -> {optimized_circuit.n_gates}") +print(f"CX: {circuit.n_gates_of_type(OpType.CX)} -> {optimized_circuit.n_gates_of_type(OpType.CX)}") ``` ### Expectation Value Calculations ```python -# Calculate expectation values for observables -def calculate_energy_expectation(backend, ansatz_circuit, hamiltonian_terms): - """Calculate energy expectation value for VQE.""" - - total_energy = 0.0 - - for pauli_string, coeff in hamiltonian_terms.items(): - # Create measurement circuit for this Pauli string - meas_circuit = ansatz_circuit.copy() - - # Add basis rotations for X and Y measurements - for qubit, pauli in enumerate(pauli_string): - if pauli == 'X': - meas_circuit = backend.add_gate(meas_circuit, 'h', qubit) - elif pauli == 'Y': - meas_circuit = backend.add_gate(meas_circuit, 'rx', qubit, [-np.pi/2]) - - # Measure expectation value - expectation = backend.expectation_value(meas_circuit, 'Z') - total_energy += coeff * expectation - - return total_energy +import numpy as np -# Example: H2 molecule Hamiltonian +# H2 Hamiltonian (STO-3G, 0.74 Angstrom), qubit 0 is the leftmost label h2_hamiltonian = { 'II': -1.0523732, + 'ZI': 0.39793742, 'IZ': -0.39793742, - 'ZI': -0.39793742, 'ZZ': -0.01128010, - 'XX': 0.18093119 + 'XX': 0.18093119, } -# Calculate energy for parameterized circuit -energy = calculate_energy_expectation(backend, bound_circuit, h2_hamiltonian) -print(f"Ground state energy estimate: {energy:.6f}") +# Exact from the TKET statevector (dicts, Hamiltonian objects or matrices) +energy = backend.compute_expectation(bound_circuit, h2_hamiltonian) +print(f"Energy of this ansatz state: {energy:.6f}") + + +def shot_based_energy(backend, ansatz, hamiltonian, shots=4000): + """The same quantity from measurements: rotate into each Pauli basis and count.""" + total = 0.0 + for pauli, coeff in hamiltonian.items(): + if set(pauli) == {'I'}: + total += coeff + continue + circuit = ansatz.copy() + for qubit, p in enumerate(pauli): + if p == 'X': + circuit = backend.add_gate(circuit, 'h', qubit) + elif p == 'Y': + circuit = backend.add_gate(circuit, 'rx', qubit, [np.pi / 2]) + circuit = backend.add_measurement(circuit) + counts = backend.counts_big_endian(backend.execute_circuit(circuit, shots=shots)['counts']) + parity = sum( + c * (-1) ** sum(int(bits[q]) for q, p in enumerate(pauli) if p != 'I') + for bits, c in counts.items() + ) + total += coeff * parity / shots + return total + + +print(f"Shot-based estimate: {shot_based_energy(backend, bound_circuit, h2_hamiltonian):.6f}") ``` ### Mid-Circuit Measurements ```python -# Circuit with mid-circuit measurements and classical control -def create_adaptive_circuit(backend, n_qubits=3): - """Create circuit with adaptive measurements.""" - from pytket.circuit import if_not_bit - - circuit = backend.create_circuit(n_qubits) - circuit.add_c_register("mid_meas", 1) - circuit.add_c_register("final_meas", n_qubits) - - # Initial superposition +from pytket.circuit import Bit, Circuit + + +def create_adaptive_circuit(n_qubits=3): + """Mid-circuit measurement with a classically controlled correction. + + Classical control is written with pytket directly; the backend + executes any pytket Circuit. + """ + circuit = Circuit(n_qubits) + mid = Bit("mid", 0) + circuit.add_bit(mid) + circuit.add_c_register("final", n_qubits) + for i in range(n_qubits): - circuit = backend.add_gate(circuit, 'h', i) - - # Mid-circuit measurement of first qubit - circuit.Measure(circuit.qubits[0], circuit.bits[0]) - - # Conditional operations based on measurement - with circuit.if_not_bit(circuit.bits[0]): - circuit = backend.add_gate(circuit, 'x', 1) - circuit = backend.add_gate(circuit, 'x', 2) - - # Final measurements + circuit.H(i) + circuit.Measure(circuit.qubits[0], mid) + + # Flip qubits 1 and 2 only when the mid-circuit result was 0 + circuit.X(1, condition_bits=[mid], condition_value=0) + circuit.X(2, condition_bits=[mid], condition_value=0) + for i in range(n_qubits): - circuit.Measure(circuit.qubits[i], circuit.bits[i+1]) - + circuit.Measure(circuit.qubits[i], Bit("final", i)) return circuit -adaptive_circuit = create_adaptive_circuit(backend) -result = backend.execute_circuit(adaptive_circuit) + +adaptive_circuit = create_adaptive_circuit() +result = backend.execute_circuit(adaptive_circuit, shots=500) +print(result['counts']) ``` ## Performance Optimization @@ -371,34 +371,31 @@ result = backend.execute_circuit(adaptive_circuit) ### Compilation Strategies ```python -# Different optimization levels +from pytket.circuit import OpType + + def compare_optimization_levels(backend, circuit): - """Compare different TKET optimization levels.""" - + """Compare the TKET optimisation levels used by optimize_circuit (0 to 3).""" results = {} - for level in range(4): optimized = backend.optimize_circuit(circuit, optimization_level=level) - results[f"level_{level}"] = { 'gates': optimized.n_gates, 'depth': optimized.depth(), - 'cx_count': optimized.n_gates_of_type(OpType.CX) if hasattr(optimized, 'n_gates_of_type') else 'N/A' + 'cx_count': optimized.n_gates_of_type(OpType.CX), } - return results -# Test circuit + test_circuit = backend.create_circuit(6) for i in range(6): test_circuit = backend.add_gate(test_circuit, 'h', i) for i in range(5): - test_circuit = backend.add_gate(test_circuit, 'cx', [i, i+1]) + test_circuit = backend.add_gate(test_circuit, 'cx', [i, i + 1]) for i in range(6): test_circuit = backend.add_gate(test_circuit, 'rz', i, [0.5]) -optimization_comparison = compare_optimization_levels(backend, test_circuit) -for level, metrics in optimization_comparison.items(): +for level, metrics in compare_optimization_levels(backend, test_circuit).items(): print(f"{level}: {metrics}") ``` @@ -586,148 +583,87 @@ def validate_tket_circuit(circuit, backend): ### VQE with TKET Optimization ```python -def tket_optimized_vqe(): - """Complete VQE implementation with TKET optimization.""" - - # Initialize backend +import numpy as np +from scipy.optimize import minimize + + +def tket_optimized_vqe(seed=0): + """VQE where every ansatz circuit is optimised by TKET before evaluation.""" backend = sqx.get_backend('tket', device='aer_simulator') - - # Define H2 Hamiltonian - hamiltonian = { - 'II': -1.0523732, - 'IZ': -0.39793742, - 'ZI': -0.39793742, - 'ZZ': -0.01128010, - 'XX': 0.18093119 - } - + def create_ansatz(params): - """Create UCCSD-inspired ansatz.""" - circuit, param_names = backend.create_parameterized_circuit(2, len(params)) - - # Initial state preparation - circuit = backend.add_gate(circuit, 'x', 0) # |01⟩ initial state - - # Parameterized gates + circuit = backend.create_circuit(2) + circuit = backend.add_gate(circuit, 'x', 0) # |10> reference state circuit = backend.add_gate(circuit, 'ry', 0, [params[0]]) circuit = backend.add_gate(circuit, 'ry', 1, [params[1]]) circuit = backend.add_gate(circuit, 'cx', [0, 1]) circuit = backend.add_gate(circuit, 'ry', 0, [params[2]]) circuit = backend.add_gate(circuit, 'ry', 1, [params[3]]) - return circuit - + def energy_function(params): - """Calculate energy for given parameters.""" - circuit = create_ansatz(params) - - # Optimize circuit with TKET - optimized_circuit = backend.optimize_circuit(circuit, optimization_level=2) - - return calculate_energy_expectation(backend, optimized_circuit, hamiltonian) - - # Optimize parameters - from scipy.optimize import minimize - - initial_params = np.random.random(4) * 2 * np.pi - result = minimize(energy_function, initial_params, method='COBYLA') - - print(f"Optimized energy: {result.fun:.6f}") - print(f"Optimal parameters: {result.x}") - + optimized = backend.optimize_circuit(create_ansatz(params), optimization_level=2) + return backend.compute_expectation(optimized, h2_hamiltonian) + + rng = np.random.default_rng(seed) + result = minimize(energy_function, rng.random(4) * 2 * np.pi, method='COBYLA') + exact = sqx.Hamiltonian.from_dict(h2_hamiltonian).ground_state_energy() + + print(f"Optimized energy: {result.fun:.6f} (exact {exact:.6f})") return result -# Run VQE + vqe_result = tket_optimized_vqe() ``` ### QAOA with Hardware Backend ```python -def tket_qaoa_max_cut(graph_edges, p_layers=3, use_hardware=False): - """QAOA for Max-Cut problem using TKET.""" - +import numpy as np +from scipy.optimize import minimize + + +def tket_qaoa_max_cut(graph_edges, p_layers=2, seed=0): + """QAOA for Max-Cut, with TKET optimisation before every execution.""" n_nodes = max(max(edge) for edge in graph_edges) + 1 - - # Choose backend - if use_hardware: - backend = sqx.TKETBackend( - device='H1-1E', - api_key=os.getenv('QUANTINUUM_API_KEY'), - shots=1000 - ) - else: - backend = sqx.TKETBackend(device='aer_simulator') - + backend = sqx.TKETBackend(device='aer_simulator', shots=1000) + # For hardware use sqx.TKETBackend(device='H1-1E') (requires credentials) + def create_qaoa_circuit(gamma, beta): - """Create QAOA circuit.""" - circuit, _ = backend.create_parameterized_circuit(n_nodes, 0) - - # Initial superposition + circuit = backend.create_circuit(n_nodes) for i in range(n_nodes): circuit = backend.add_gate(circuit, 'h', i) - - # QAOA layers for layer in range(p_layers): - # Problem Hamiltonian (ZZ terms) - for i, j in graph_edges: + for i, j in graph_edges: # problem layer (ZZ terms) circuit = backend.add_gate(circuit, 'cx', [i, j]) circuit = backend.add_gate(circuit, 'rz', j, [2 * gamma[layer]]) circuit = backend.add_gate(circuit, 'cx', [i, j]) - - # Mixer Hamiltonian (X rotations) - for i in range(n_nodes): + for i in range(n_nodes): # mixer layer circuit = backend.add_gate(circuit, 'rx', i, [2 * beta[layer]]) - return circuit - + def cost_function(params): - """QAOA cost function.""" - gamma = params[:p_layers] - beta = params[p_layers:] - - circuit = create_qaoa_circuit(gamma, beta) - - # Optimize with TKET - if use_hardware: - optimized = backend.optimize_circuit(circuit, optimization_level=3) - else: - optimized = backend.optimize_circuit(circuit, optimization_level=2) - - # Add measurements - measured_circuit = optimized.copy() - measured_circuit = backend.add_measurement(measured_circuit, list(range(n_nodes))) - - # Execute - result = backend.execute_circuit(measured_circuit) - - # Calculate expectation value - expectation = 0.0 - total_shots = sum(result['counts'].values()) - - for bitstring, count in result['counts'].items(): - # Calculate cost for this bitstring - cost = 0 - for i, j in graph_edges: - if bitstring[i] != bitstring[j]: - cost += 1 - - expectation += (count / total_shots) * cost - - return -expectation # Maximize cut (minimize negative) - - # Optimize QAOA parameters - initial_params = np.random.uniform(0, 2*np.pi, 2*p_layers) - result = minimize(cost_function, initial_params, method='COBYLA') - - print(f"Optimal QAOA cost: {-result.fun:.4f}") - print(f"Optimal parameters: {result.x}") - + circuit = create_qaoa_circuit(params[:p_layers], params[p_layers:]) + optimized = backend.optimize_circuit(circuit, optimization_level=2) + optimized = backend.add_measurement(optimized, list(range(n_nodes))) + counts = backend.counts_big_endian(backend.execute_circuit(optimized)['counts']) + + total = sum(counts.values()) + expectation = sum( + count / total * sum(bits[i] != bits[j] for i, j in graph_edges) + for bits, count in counts.items() + ) + return -expectation # maximise the cut + + rng = np.random.default_rng(seed) + result = minimize(cost_function, rng.uniform(0, np.pi, 2 * p_layers), + method='COBYLA', options={'maxiter': 60}) + print(f"Expected cut: {-result.fun:.3f} (best possible: 3)") return result -# Example: small graph + edges = [(0, 1), (1, 2), (2, 0), (0, 3)] -qaoa_result = tket_qaoa_max_cut(edges, p_layers=2) +qaoa_result = tket_qaoa_max_cut(edges) ``` ## Best Practices @@ -765,14 +701,18 @@ pip install pytket[all] ``` **Quantinuum API Authentication Failed** +!!! note "Requires credentials" + Needs `pytket-quantinuum` and a Quantinuum account. Checked against the 0.3.0 constructor, not run. + + ```python -# Check API key configuration -import os -print("API Key:", os.getenv('QUANTINUUM_API_KEY')) +# Is the Quantinuum extension installed? +import importlib.util +print("pytket-quantinuum:", importlib.util.find_spec("pytket.extensions.quantinuum") is not None) -# Test connection -backend = sqx.TKETBackend(device='H1-1E', api_key='your-key') -info = backend.get_backend_info() +# Then try the device; authentication is handled by pytket-quantinuum +backend = sqx.TKETBackend(device='H1-1E') +print(backend.get_backend_info()) ``` **Circuit Compilation Failed** @@ -913,7 +853,7 @@ The TKET backend provides these key methods: - `get_backend_info()`: Backend information - `get_circuit_info()`: Circuit capabilities -For complete API documentation, see the [API Reference](../api/backends.md#tket-backend) section. +For complete API documentation, see the [API Reference](../api/backends.md) section. --- diff --git a/docs/design/qmes-feature-map-auto.md b/docs/design/qmes-feature-map-auto.md index 47ab060..9ed9100 100644 --- a/docs/design/qmes-feature-map-auto.md +++ b/docs/design/qmes-feature-map-auto.md @@ -113,7 +113,7 @@ Closest-name mapping is approximate: from sklearn.datasets import make_classification from superquantx.algorithms import QuantumSVM -X, y = make_classification(n_samples=40, n_features=4, n_informative=3, random_state=0) +X, y = make_classification(n_samples=40, n_features=4, n_informative=3, n_redundant=0, n_repeated=0, random_state=0) qsvm = QuantumSVM(backend="simulator", feature_map="auto", shots=100) qsvm.fit(X, y) print(qsvm.selected_feature_map_) @@ -126,7 +126,13 @@ Optional Qmes path: pip install git+https://github.com/tungduy1704/Qmes ``` +!!! note "Optional Qmes dependency" + Needs the Qmes package from GitHub; not run in the docs checker. + + ```python +from superquantx.algorithms import QuantumSVM + qsvm = QuantumSVM( backend="simulator", feature_map="auto", diff --git a/docs/development/architecture.md b/docs/development/architecture.md index b538d9f..b754b46 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -1,9 +1,5 @@ # 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 @@ -56,8 +52,10 @@ SuperQuantX follows a modular, layered architecture designed for quantum computi ### Backend System ```python -# Backend abstraction allows seamless switching -backend = sqx.get_backend('pennylane') # or 'qiskit', 'cirq', etc. +import superquantx as sqx + +# Backend abstraction: swap the name, keep the code +backend = sqx.get_backend('pennylane') # or 'simulator', 'qiskit', 'cirq', 'braket', 'tket' algorithm = sqx.QuantumSVM(backend=backend) ``` @@ -70,27 +68,36 @@ algorithm = sqx.QuantumSVM(backend=backend) ### Circuit Management ```python -# Unified circuit construction -circuit = sqx.QuantumCircuit(n_qubits=4) +# Backend-independent circuit description (draw, compose, serialise) +circuit = sqx.QuantumCircuit(4) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() + +# Executable circuit on a specific backend, built with the shared gate names +backend = sqx.get_backend('simulator') +native = backend.create_circuit(4) +backend.add_gate(native, 'H', 0) +backend.add_gate(native, 'CNOT', [0, 1]) +backend.add_measurement(native) +print(backend.execute_circuit(native, shots=100)['counts']) ``` **Components:** -- `QuantumCircuit`: Main circuit representation -- `QuantumGate`: Individual gate operations -- `Parameter`: Symbolic parameters for variational algorithms -- `Measurement`: Quantum measurement operations +- `QuantumCircuit`: backend-independent circuit description +- `QuantumGate`: individual gate operations +- Backend circuits: created by `backend.create_circuit(n)` and executed by `backend.execute_circuit` +- `MeasurementResult`: counts with analysis helpers ### Algorithm Framework ```python # High-level algorithm interface qsvm = sqx.QuantumSVM( + backend='simulator', feature_map='ZZFeatureMap', - ansatz='RealAmplitudes', - optimizer='SPSA' + feature_map_reps=2, + C=1.0, ) ``` @@ -107,21 +114,32 @@ qsvm = sqx.QuantumSVM( Each backend implements the `QuantumBackend` interface: ```python -class QuantumBackend(ABC): +from abc import ABC, abstractmethod + + +class BaseBackend(ABC): + """Abridged from superquantx/backends/base_backend.py.""" + + @abstractmethod + def _initialize_backend(self) -> None: ... + + @abstractmethod + def create_circuit(self, n_qubits: int): ... + + @abstractmethod + def add_gate(self, circuit, gate: str, qubits, params=None): ... + @abstractmethod - def create_circuit(self, n_qubits: int) -> QuantumCircuit: - """Create quantum circuit""" - pass - + def add_measurement(self, circuit, qubits=None): ... + @abstractmethod - def execute(self, circuit: QuantumCircuit, shots: int) -> Result: - """Execute quantum circuit""" - pass - + def execute_circuit(self, circuit, shots=None) -> dict: ... + @abstractmethod - def compile_circuit(self, circuit: QuantumCircuit) -> CompiledCircuit: - """Compile circuit for execution""" - pass + def get_statevector(self, circuit): ... + + @abstractmethod + def _get_n_qubits(self, circuit) -> int: ... ``` ### Gate System @@ -129,19 +147,12 @@ class QuantumBackend(ABC): Gates are represented using a flexible matrix-based system: ```python -class GateMatrix: - # Pauli gates - 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) - - @staticmethod - def rx(theta: float) -> np.ndarray: - """Rotation around X-axis""" - return np.array([ - [np.cos(theta/2), -1j*np.sin(theta/2)], - [-1j*np.sin(theta/2), np.cos(theta/2)] - ]) +import numpy as np +from superquantx.gates import GateMatrix + +# Fixed gates are class attributes, rotations are static methods +print(GateMatrix.X) +print(np.round(GateMatrix.rx(np.pi / 2), 3)) ``` ### Measurement System @@ -149,15 +160,12 @@ class GateMatrix: Measurements are handled through a unified interface: ```python -class MeasurementResult: - counts: Dict[str, int] - shots: int - memory: Optional[List[str]] - metadata: Dict[str, Any] - - def probabilities(self) -> Dict[str, float]: - """Convert counts to probabilities""" - return {k: v/self.shots for k, v in self.counts.items()} +from superquantx.measurements import MeasurementResult + +# Pydantic model: counts, shots, optional memory and metadata +result = MeasurementResult(counts={'00': 480, '11': 520}, shots=1000) +print(result.probabilities) +print(result.most_frequent) ``` ## 🔬 Algorithm Architecture @@ -231,43 +239,64 @@ Raw Results → Measurement Analysis → Error Mitigation → Final Results ### Adding New Backends -1. **Implement Backend Interface** +1. **Implement Backend Interface** (all seven abstract methods of `BaseBackend`) ```python - class NewBackend(QuantumBackend): - def create_circuit(self, n_qubits): - # Backend-specific implementation - pass + from superquantx.backends.base_backend import BaseBackend + + class NewBackend(BaseBackend): + def _initialize_backend(self): ... + def create_circuit(self, n_qubits): ... + def add_gate(self, circuit, gate, qubits, params=None): ... + def add_measurement(self, circuit, qubits=None): ... + def execute_circuit(self, circuit, shots=None): ... + def get_statevector(self, circuit): ... + def _get_n_qubits(self, circuit): ... ``` 2. **Register Backend** ```python - BACKEND_REGISTRY['new_backend'] = NewBackend + from superquantx.backends import BACKEND_REGISTRY, SimulatorBackend, get_backend + + class MySimulator(SimulatorBackend): # a real subclass, so this example runs + pass + + BACKEND_REGISTRY['my_simulator'] = MySimulator + print(type(get_backend('my_simulator')).__name__) ``` 3. **Add Tests** ```python def test_new_backend(): - backend = get_backend('new_backend') - # Test backend functionality + backend = get_backend('my_simulator') + circuit = backend.create_circuit(1) + backend.add_gate(circuit, 'X', 0) + backend.add_measurement(circuit) + assert backend.execute_circuit(circuit, shots=10)['counts'] == {'1': 10} + + test_new_backend() ``` ### Adding New Algorithms 1. **Inherit from Base Class** ```python - class NewQuantumAlgorithm(QuantumAlgorithm): - def __init__(self, backend): - super().__init__(backend) - - def run(self, data): - # Algorithm implementation - pass + from superquantx.algorithms import BaseQuantumAlgorithm + + class NewQuantumAlgorithm(BaseQuantumAlgorithm): + def fit(self, X, y=None, **kwargs): + # Train here; self.backend is already a backend object + self.is_fitted = True + return self + + def predict(self, X, **kwargs): + return [0] * len(X) + + print(NewQuantumAlgorithm(backend='simulator').fit([[0.1]]).predict([[0.1], [0.2]])) ``` 2. **Implement Required Methods** - - `run()`: Main algorithm execution - - `fit()`: Training (if applicable) - - `predict()`: Prediction (if applicable) + - `fit()`: training or optimisation + - `predict()`: prediction or the final answer ## 🔍 Performance Considerations @@ -276,17 +305,17 @@ Raw Results → Measurement Analysis → Error Mitigation → Final Results ```python class CircuitOptimizer: def optimize(self, circuit): - """Multi-pass circuit optimization""" - # 1. Gate fusion - circuit = self._fuse_single_qubit_gates(circuit) - - # 2. Two-qubit gate reduction - circuit = self._reduce_cnot_gates(circuit) - - # 3. Layout optimization - circuit = self._optimize_layout(circuit) - - return circuit + """Multi-pass circuit optimization""" + # 1. Gate fusion + circuit = self._fuse_single_qubit_gates(circuit) + + # 2. Two-qubit gate reduction + circuit = self._reduce_cnot_gates(circuit) + + # 3. Layout optimization + circuit = self._optimize_layout(circuit) + + return circuit ``` ### Parallel Execution @@ -294,14 +323,14 @@ class CircuitOptimizer: ```python class ParallelExecutor: def execute_batch(self, circuits, shots): - """Execute multiple circuits in parallel""" - with ThreadPoolExecutor(max_workers=self.num_workers) as executor: - futures = [ - executor.submit(self._execute_single, circuit, shots) - for circuit in circuits - ] - results = [future.result() for future in futures] - return results + """Execute multiple circuits in parallel""" + with ThreadPoolExecutor(max_workers=self.num_workers) as executor: + futures = [ + executor.submit(self._execute_single, circuit, shots) + for circuit in circuits + ] + results = [future.result() for future in futures] + return results ``` ### Memory Management @@ -341,31 +370,39 @@ tests/ ```python import logging -from superquantx.logging import get_logger -logger = get_logger(__name__) +from superquantx.logging_config import configure_logging -def quantum_function(): +configure_logging(level='INFO') +logger = logging.getLogger(__name__) # SuperQuantX modules use standard logging + +def quantum_function(backend, circuit): logger.info("Starting quantum computation") try: - result = backend.execute(circuit) + result = backend.execute_circuit(circuit, shots=100) logger.debug(f"Result: {result}") return result except Exception as e: logger.error(f"Quantum execution failed: {e}") raise + +quantum_function(backend, native) ``` ### Performance Profiling ```python -from superquantx.profiler import profile_quantum +import cProfile +import pstats + +import numpy as np -@profile_quantum -def benchmark_algorithm(): - """Automatically profile quantum algorithm execution""" - # Algorithm implementation - pass +# There is no built-in profiler; the standard library works well +profiler = cProfile.Profile() +profiler.enable() +sqx.QuantumSVM(backend='simulator').fit(np.random.default_rng(0).normal(size=(20, 2)), np.array([0, 1] * 10)) +profiler.disable() +pstats.Stats(profiler).sort_stats('cumulative').print_stats(5) ``` ## 🔮 Future Architecture diff --git a/docs/development/contributing.md b/docs/development/contributing.md index 42ba609..7a825fd 100644 --- a/docs/development/contributing.md +++ b/docs/development/contributing.md @@ -237,22 +237,18 @@ src/superquantx/ ### Testing Best Practices ```python +import numpy as np +from superquantx import QuantumSVM, get_backend + def test_quantum_algorithm(): - """Test quantum algorithm with known expected result.""" - # Setup - backend = get_backend('simulator') - algorithm = QuantumSVM(backend=backend) - - # Test data with known classification - X_test = np.array([[0, 0], [1, 1]]) - y_test = np.array([0, 1]) - - # Execute - result = algorithm.fit_predict(X_test, y_test) - - # Verify - assert result.accuracy > 0.9 - assert len(result.predictions) == len(y_test) + """Train a tiny QuantumSVM and check the prediction shape.""" + backend = get_backend("simulator") + model = QuantumSVM(backend=backend, feature_map="ZFeatureMap") + X = np.array([[0.0, 0.0], [1.0, 1.0], [0.1, 0.2], [0.9, 0.8]]) + y = np.array([0, 1, 0, 1]) + model.fit(X, y) + preds = model.predict(X) + assert preds.shape == y.shape ``` ## 📚 Documentation Standards diff --git a/docs/development/standards.md b/docs/development/standards.md index f081dfd..0bf2273 100644 --- a/docs/development/standards.md +++ b/docs/development/standards.md @@ -1,9 +1,5 @@ # 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 @@ -34,6 +30,9 @@ Follow [PEP 8](https://pep8.org/) with the following specifics: # Indentation: 4 spaces (no tabs) # Quotes: Double quotes for strings, single for internal +import numpy as np + + class QuantumAlgorithm: """ Base class for quantum algorithms. @@ -96,10 +95,12 @@ class BackendNotFoundError(Exception): #### Constants ```python +import numpy as np + # UPPER_SNAKE_CASE for constants DEFAULT_SHOTS = 1024 MAX_QUBITS = 32 -SUPPORTED_BACKENDS = ["simulator", "pennylane", "qiskit", "cirq"] +SUPPORTED_BACKENDS = ["simulator", "pennylane", "qiskit", "cirq", "braket", "tket", "ocean"] # Module-level constants PI = np.pi @@ -127,9 +128,11 @@ class QuantumAlgorithm: Use comprehensive type hints: ```python -from typing import List, Dict, Optional, Union, Callable, Tuple, Any +from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np +from superquantx.backends.base_backend import BaseBackend + # Basic types def process_data(data: List[float]) -> Dict[str, float]: """Process numerical data.""" @@ -147,7 +150,7 @@ def quantum_operation( def get_backend( name: str, config: Optional[Dict[str, Any]] = None -) -> Union[QuantumBackend, None]: +) -> Union[BaseBackend, None]: """Get quantum backend by name.""" pass @@ -331,144 +334,108 @@ Note: ### Test Structure ```python -import pytest import numpy as np -from unittest.mock import Mock, patch +import pytest +from unittest.mock import patch + from superquantx.algorithms import QuantumSVM +from superquantx.backends import SimulatorBackend + class TestQuantumSVM: - """Test suite for Quantum Support Vector Machine.""" - + """Test suite for the quantum support vector machine.""" + @pytest.fixture def sample_data(self): - """Provide sample dataset for testing.""" - np.random.seed(42) - X = np.random.randn(20, 2) + """Small, linearly separable dataset.""" + rng = np.random.default_rng(42) + X = rng.normal(size=(20, 2)) y = (X[:, 0] + X[:, 1] > 0).astype(int) return X, y - + @pytest.fixture def qsvm(self): - """Provide QSVM instance for testing.""" return QuantumSVM(backend="simulator") - - def test_initialization(self): - """Test QSVM initialization with default parameters.""" - qsvm = QuantumSVM() - - assert qsvm.backend == "simulator" + + def test_initialization(self, qsvm): + """Defaults: simulator backend object, C=1.0, not fitted.""" + assert isinstance(qsvm.backend, SimulatorBackend) assert qsvm.C == 1.0 - assert not qsvm._is_trained - + assert not qsvm.is_fitted + def test_fit_with_valid_data(self, qsvm, sample_data): - """Test fitting QSVM with valid training data.""" X, y = sample_data - result = qsvm.fit(X, y) - - # Should return self for method chaining - assert result is qsvm - assert qsvm._is_trained - assert hasattr(qsvm, 'kernel_matrix_') - + + assert result is qsvm # method chaining + assert qsvm.is_fitted + assert qsvm.kernel_matrix_.shape == (len(X), len(X)) + def test_fit_with_invalid_data(self, qsvm): - """Test fitting QSVM with invalid data raises ValueError.""" X = np.array([[1, 2], [3, 4]]) - y = np.array([0, 1, 2]) # Wrong length - - with pytest.raises(ValueError, match="X and y must have same length"): + y = np.array([0, 1, 2]) # wrong length + + with pytest.raises(ValueError, match="same number of samples"): qsvm.fit(X, y) - + @pytest.mark.parametrize("backend", ["simulator", "pennylane"]) def test_different_backends(self, backend, sample_data): - """Test QSVM works with different backends.""" X, y = sample_data - try: qsvm = QuantumSVM(backend=backend) - qsvm.fit(X, y) - predictions = qsvm.predict(X) - - assert len(predictions) == len(y) - assert all(pred in [0, 1] for pred in predictions) except ImportError: - pytest.skip(f"Backend {backend} not available") - + pytest.skip(f"Backend {backend} not installed") + predictions = qsvm.fit(X, y).predict(X) + + assert len(predictions) == len(y) + assert set(predictions) <= {0, 1} + def test_predict_before_fit_raises_error(self, qsvm, sample_data): - """Test that predict raises error before fit is called.""" X, _ = sample_data - - with pytest.raises(RuntimeError, match="must be trained first"): + with pytest.raises(ValueError, match="must be fitted"): qsvm.predict(X) - - @patch('superquantx.backends.get_backend') - def test_backend_integration(self, mock_get_backend, qsvm, sample_data): - """Test backend integration with mocking.""" + + def test_backend_is_used(self, qsvm, sample_data): + """Spy on the backend to check the kernel goes through it.""" X, y = sample_data - - # Mock backend behavior - mock_backend = Mock() - mock_backend.execute.return_value = Mock(counts={'00': 50, '11': 50}) - mock_get_backend.return_value = mock_backend - - qsvm.fit(X, y) - - # Verify backend was called - mock_get_backend.assert_called_once() - mock_backend.execute.assert_called() + with patch.object(qsvm.backend, "compute_kernel_matrix", + wraps=qsvm.backend.compute_kernel_matrix) as spy: + qsvm.fit(X, y) + spy.assert_called() ``` ### Property-Based Testing ```python -from hypothesis import given, strategies as st +import numpy as np import hypothesis.extra.numpy as npst +from hypothesis import given, strategies as st + +from superquantx.gates import GateMatrix + class TestQuantumGates: """Property-based tests for quantum gates.""" - - @given(theta=st.floats(min_value=0, max_value=2*np.pi)) + + @given(theta=st.floats(min_value=0, max_value=2 * np.pi)) def test_rotation_gates_unitary(self, theta): - """Test that rotation gates are always unitary.""" - gates = [ - GateMatrix.rx(theta), - GateMatrix.ry(theta), - GateMatrix.rz(theta) - ] - - for gate in gates: - # Unitary condition: U†U = I - identity = np.eye(2, dtype=complex) - result = gate.conj().T @ gate - assert np.allclose(result, identity, atol=1e-10) - + """Rotation gates are always unitary.""" + for gate in [GateMatrix.rx(theta), GateMatrix.ry(theta), GateMatrix.rz(theta)]: + assert np.allclose(gate.conj().T @ gate, np.eye(2), atol=1e-10) + @given( state=npst.arrays( dtype=complex, shape=(2,), - elements=st.complex_numbers( - min_magnitude=0, - max_magnitude=1, - allow_infinity=False, - allow_nan=False - ) + elements=st.complex_numbers(max_magnitude=1, allow_infinity=False, allow_nan=False), ) ) def test_pauli_gates_preserve_norm(self, state): - """Test that Pauli gates preserve state norm.""" - # Normalize input state - if np.linalg.norm(state) > 0: + """Pauli gates preserve the norm of a state.""" + if np.linalg.norm(state) > 1e-6: state = state / np.linalg.norm(state) - - pauli_gates = [GateMatrix.X, GateMatrix.Y, GateMatrix.Z] - - for gate in pauli_gates: - result_state = gate @ state - assert np.allclose( - np.linalg.norm(result_state), - 1.0, - atol=1e-10 - ) + for gate in [GateMatrix.X, GateMatrix.Y, GateMatrix.Z]: + assert np.isclose(np.linalg.norm(gate @ state), 1.0, atol=1e-10) ``` ## 🔧 Code Quality Tools @@ -701,38 +668,43 @@ def sanitize_backend_name(name: str) -> str: ### Error Handling ```python -class SuperQuantXError(Exception): - """Base exception for SuperQuantX.""" - pass +# The hierarchy in superquantx/exceptions.py (abridged) +from superquantx.exceptions import ( + AlgorithmError, + BackendError, + QuantumCircuitError, + SuperQuantXError, +) +import logging -class BackendError(SuperQuantXError): - """Error related to quantum backend operations.""" - pass +import superquantx as sqx -class CircuitError(SuperQuantXError): - """Error in quantum circuit construction or execution.""" - pass +logger = logging.getLogger(__name__) -class AlgorithmError(SuperQuantXError): - """Error in quantum algorithm execution.""" - pass # Good error handling -def execute_quantum_circuit(circuit: QuantumCircuit) -> MeasurementResult: - """Execute quantum circuit with proper error handling.""" +def execute_quantum_circuit(backend_name: str, n_qubits: int) -> dict: + """Run a GHZ circuit, turning backend failures into AlgorithmError.""" try: - validate_circuit(circuit) - backend = get_backend() - result = backend.execute(circuit) - return process_result(result) - + backend = sqx.get_backend(backend_name) + circuit = backend.create_circuit(n_qubits) + backend.add_gate(circuit, 'H', 0) + for q in range(n_qubits - 1): + backend.add_gate(circuit, 'CNOT', [q, q + 1]) + backend.add_measurement(circuit) + return backend.execute_circuit(circuit, shots=100) + except BackendError as e: logger.error(f"Backend execution failed: {e}") raise AlgorithmError(f"Circuit execution failed: {e}") from e - + except Exception as e: logger.error(f"Unexpected error in circuit execution: {e}") raise AlgorithmError("Unexpected error during execution") from e + + +print(execute_quantum_circuit('simulator', 3)['counts']) +assert issubclass(AlgorithmError, SuperQuantXError) ``` ## 📊 Logging Standards diff --git a/docs/development/testing.md b/docs/development/testing.md index 278b003..8fab85b 100644 --- a/docs/development/testing.md +++ b/docs/development/testing.md @@ -1,9 +1,5 @@ # 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 @@ -138,110 +134,87 @@ class TestQuantumGates: ### Testing Quantum Circuits ```python +import numpy as np from superquantx.circuits import QuantumCircuit -from superquantx.measurements import MeasurementResult + class TestQuantumCircuits: + """Tests for the backend-independent circuit description.""" + def test_circuit_creation(self): - """Test basic circuit creation""" - circuit = QuantumCircuit(n_qubits=3, n_classical=3) - + circuit = QuantumCircuit(3, 3) + assert circuit.num_qubits == 3 assert circuit.num_classical_bits == 3 - assert len(circuit.data) == 0 - + assert len(circuit.gates) == 0 + def test_gate_application(self): - """Test applying gates to circuit""" circuit = QuantumCircuit(2) - - # Apply gates circuit.h(0) circuit.cx(0, 1) - - assert len(circuit.data) == 2 - assert circuit.data[0].name == 'h' - assert circuit.data[1].name == 'cx' - + + assert [g.name for g in circuit.gates] == ['H', 'CNOT'] + assert circuit.gates[1].qubits == [0, 1] + def test_bell_state_circuit(self): - """Test Bell state preparation circuit""" circuit = QuantumCircuit(2, 2) - - # Create Bell state |Φ+⟩ = (|00⟩ + |11⟩)/√2 circuit.h(0) circuit.cx(0, 1) circuit.measure_all() - - # Verify circuit structure - assert circuit.depth() == 2 # H gate, then CX gate - assert circuit.count_ops()['h'] == 1 - assert circuit.count_ops()['cx'] == 1 - assert circuit.count_ops()['measure'] == 2 - - def test_parameterized_circuit(self): - """Test circuits with parameters""" - from superquantx.circuits import Parameter - - theta = Parameter('theta') + + assert len(circuit.gates) == 2 + assert circuit.measurements == [(0, 0), (1, 1)] + + def test_rotation_parameters(self): + # There is no symbolic Parameter class; rotations take numbers circuit = QuantumCircuit(1) - circuit.ry(theta, 0) - - # Bind parameter - bound_circuit = circuit.bind_parameters({theta: np.pi/2}) - - assert len(bound_circuit.parameters) == 0 - assert bound_circuit.data[0].params[0] == np.pi/2 + circuit.ry(np.pi / 2, 0) + + assert circuit.gates[0].parameters == [np.pi / 2] + + def test_json_round_trip(self): + circuit = QuantumCircuit(2) + circuit.h(0) + circuit.cx(0, 1) + + assert QuantumCircuit.from_json(circuit.to_json()).gates == circuit.gates ``` ### Testing Algorithms ```python -from superquantx.algorithms import QuantumSVM from sklearn.datasets import make_classification +from superquantx.algorithms import QuantumSVM +from superquantx.backends import SimulatorBackend + class TestQuantumAlgorithms: def test_qsvm_initialization(self): - """Test QSVM initialization""" - backend = 'simulator' - qsvm = QuantumSVM(backend=backend) - - assert qsvm.backend == backend - assert qsvm.feature_map is not None - assert qsvm.quantum_kernel is not None - + qsvm = QuantumSVM(backend='simulator', feature_map='ZZFeatureMap') + + assert isinstance(qsvm.backend, SimulatorBackend) # names resolve to backend objects + assert qsvm.feature_map == 'ZZFeatureMap' + assert not qsvm.is_fitted + def test_qsvm_small_dataset(self): - """Test QSVM on small synthetic dataset""" - # Create simple 2D dataset X, y = make_classification( - n_samples=20, n_features=2, n_redundant=0, - n_informative=2, n_clusters_per_class=1, random_state=42 + n_samples=20, n_features=2, n_redundant=0, + n_informative=2, n_clusters_per_class=1, random_state=42, ) - qsvm = QuantumSVM(backend='simulator') - - # Fit and predict - qsvm.fit(X, y) - predictions = qsvm.predict(X) - - # Basic validations + predictions = qsvm.fit(X, y).predict(X) + assert len(predictions) == len(y) - assert all(pred in [0, 1] for pred in predictions) - - # Should achieve reasonable accuracy on training data - accuracy = np.mean(predictions == y) - assert accuracy > 0.7 # At least 70% accuracy - + assert set(predictions) <= {0, 1} + assert np.mean(predictions == y) >= 0.6 # training accuracy floor + @pytest.mark.parametrize("backend", ["simulator", "pennylane"]) def test_qsvm_backend_consistency(self, backend): - """Test QSVM consistency across backends""" X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([0, 1, 1, 0]) # XOR pattern - - qsvm = QuantumSVM(backend=backend) - - # Should not crash and produce valid output - qsvm.fit(X, y) - predictions = qsvm.predict(X) - + + predictions = QuantumSVM(backend=backend).fit(X, y).predict(X) + assert len(predictions) == len(y) assert all(isinstance(pred, (int, np.integer)) for pred in predictions) ``` @@ -254,72 +227,46 @@ class TestQuantumAlgorithms: import pytest from superquantx import get_backend + +def bell_counts(backend_name, shots=1000): + backend = get_backend(backend_name) + circuit = backend.create_circuit(2) + backend.add_gate(circuit, 'H', 0) + backend.add_gate(circuit, 'CNOT', [0, 1]) + backend.add_measurement(circuit) + return backend.execute_circuit(circuit, shots=shots)['counts'] + + class TestBackendIntegration: - @pytest.mark.parametrize("backend_name", [ - "simulator", "pennylane", "qiskit", "cirq" - ]) + @pytest.mark.parametrize("backend_name", ["simulator", "pennylane", "qiskit", "cirq"]) def test_backend_availability(self, backend_name): - """Test that backends can be loaded""" try: backend = get_backend(backend_name) - assert backend is not None except ImportError: pytest.skip(f"Backend {backend_name} not available") - + assert backend is not None + def test_cross_backend_consistency(self): - """Test that same circuit produces similar results across backends""" - circuit = QuantumCircuit(2, 2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - backends = ["simulator"] # Add more as available + """The same Bell circuit gives similar distributions on every backend.""" results = {} - - for backend_name in backends: + for backend_name in ["simulator", "qiskit", "cirq", "pennylane"]: try: - backend = get_backend(backend_name) - result = backend.execute(circuit, shots=1000) - results[backend_name] = result + results[backend_name] = bell_counts(backend_name) except ImportError: continue - - # Compare probability distributions - if len(results) > 1: - backend_names = list(results.keys()) - ref_probs = results[backend_names[0]].probabilities - - for backend_name in backend_names[1:]: - probs = results[backend_name].probabilities - - # Check that probability distributions are similar - for outcome in ref_probs: - if outcome in probs: - diff = abs(ref_probs[outcome] - probs[outcome]) - assert diff < 0.1 # Within 10% - + + reference = results.pop('simulator') + for counts in results.values(): + for outcome in ('00', '11'): + diff = abs(reference.get(outcome, 0) - counts.get(outcome, 0)) / 1000 + assert diff < 0.1 # within 10% + def test_bell_state_measurement(self): - """Test Bell state measurement across backends""" - circuit = QuantumCircuit(2, 2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - backend = get_backend('simulator') - result = backend.execute(circuit, shots=1000) - - # Bell state should only produce |00⟩ and |11⟩ - valid_outcomes = {'00', '11'} - for outcome in result.counts: - assert outcome in valid_outcomes - - # Should be roughly 50/50 distribution - if '00' in result.counts and '11' in result.counts: - prob_00 = result.counts['00'] / 1000 - prob_11 = result.counts['11'] / 1000 - - assert 0.3 < prob_00 < 0.7 # Rough statistical test - assert 0.3 < prob_11 < 0.7 + counts = bell_counts('simulator') + + assert set(counts) <= {'00', '11'} # only correlated outcomes + assert 0.3 < counts.get('00', 0) / 1000 < 0.7 + assert 0.3 < counts.get('11', 0) / 1000 < 0.7 ``` ### End-to-End Workflow Tests @@ -327,58 +274,45 @@ class TestBackendIntegration: ```python class TestWorkflows: def test_complete_qml_workflow(self): - """Test complete quantum machine learning workflow""" + """Data preparation, training, prediction and evaluation.""" from sklearn.datasets import make_blobs - from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score - - # 1. Data preparation + from sklearn.model_selection import train_test_split + X, y = make_blobs(n_samples=40, centers=2, random_state=42) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42 ) - - # 2. Model training - qsvm = QuantumSVM(backend='simulator') - qsvm.fit(X_train, y_train) - - # 3. Prediction - y_pred = qsvm.predict(X_test) - - # 4. Evaluation - accuracy = accuracy_score(y_test, y_pred) - - # Should achieve reasonable performance - assert accuracy > 0.6 + + qsvm = QuantumSVM(backend='simulator', feature_map='ZFeatureMap') + y_pred = qsvm.fit(X_train, y_train).predict(X_test) + + assert accuracy_score(y_test, y_pred) > 0.7 assert len(y_pred) == len(y_test) - - def test_noise_modeling_workflow(self): - """Test noise modeling and error mitigation workflow""" - from superquantx.noise import NoiseModel, DepolarizingChannel - from superquantx.measurements import ResultAnalyzer - - # 1. Create noisy backend - noise_model = NoiseModel() - noise_channel = DepolarizingChannel(probability=0.01) - noise_model.add_gate_noise('h', noise_channel) - - # 2. Create test circuit - circuit = QuantumCircuit(2, 2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() - - # 3. Execute with and without noise - clean_backend = get_backend('simulator') - noisy_backend = get_backend('simulator', noise_model=noise_model) - - clean_result = clean_backend.execute(circuit, shots=1000) - noisy_result = noisy_backend.execute(circuit, shots=1000) - - # 4. Compare results - comparison = ResultAnalyzer.compare_results(clean_result, noisy_result) - - # Noise should create some difference + + def test_readout_noise_workflow(self): + """Compare ideal counts with counts after simulated readout noise.""" + from superquantx.measurements import MeasurementResult, ResultAnalyzer + + backend = get_backend('simulator') + circuit = backend.create_circuit(2) + backend.add_gate(circuit, 'H', 0) + backend.add_gate(circuit, 'CNOT', [0, 1]) + backend.add_measurement(circuit) + clean = backend.execute_circuit(circuit, shots=1000)['counts'] + + # Flip each measured bit with probability 5% (classical readout noise) + rng = np.random.default_rng(0) + noisy = {} + for bits, count in clean.items(): + for _ in range(count): + out = ''.join(b if rng.random() > 0.05 else str(1 - int(b)) for b in bits) + noisy[out] = noisy.get(out, 0) + 1 + + comparison = ResultAnalyzer.compare_results( + MeasurementResult(counts=clean, shots=1000), + MeasurementResult(counts=noisy, shots=1000), + ) assert comparison['total_variation_distance'] > 0 ``` @@ -388,117 +322,93 @@ class TestWorkflows: ```python import time + import pytest -from superquantx.benchmarks import QuantumBenchmark +from superquantx import get_backend + class TestPerformance: @pytest.mark.performance - def test_circuit_compilation_performance(self): - """Benchmark circuit compilation speed""" - circuit = QuantumCircuit(10) - - # Add many gates + def test_circuit_execution_performance(self): + """A 10-qubit, 190-gate circuit should run quickly on the simulator.""" + backend = get_backend('simulator') + circuit = backend.create_circuit(10) for i in range(100): - circuit.h(i % 10) + backend.add_gate(circuit, 'H', i % 10) if i % 10 < 9: - circuit.cx(i % 10, (i % 10) + 1) - - backend = get_backend('simulator') - - # Measure compilation time + backend.add_gate(circuit, 'CNOT', [i % 10, i % 10 + 1]) + backend.add_measurement(circuit) + start_time = time.time() - compiled_circuit = backend.compile_circuit(circuit) - compilation_time = time.time() - start_time - - # Should compile reasonably quickly - assert compilation_time < 5.0 # Less than 5 seconds - assert compiled_circuit is not None - + result = backend.execute_circuit(circuit, shots=1000) + assert time.time() - start_time < 5.0 + assert sum(result['counts'].values()) == 1000 + @pytest.mark.performance def test_algorithm_scaling(self): - """Test algorithm performance scaling""" + """QSVM training time should not explode with dataset size.""" from sklearn.datasets import make_classification - - sizes = [10, 20, 40] + times = [] - - for size in sizes: - X, y = make_classification(n_samples=size, n_features=2, random_state=42) - - qsvm = QuantumSVM(backend='simulator') - + for size in [10, 20, 40]: + X, y = make_classification( + n_samples=size, n_features=2, n_redundant=0, n_informative=2, random_state=42 + ) start_time = time.time() - qsvm.fit(X, y) - training_time = time.time() - start_time - - times.append(training_time) - - # Training time shouldn't increase exponentially - assert times[-1] < times[0] * 10 # No more than 10x increase - + QuantumSVM(backend='simulator').fit(X, y) + times.append(time.time() - start_time) + + assert times[-1] < max(times[0], 0.05) * 50 # kernel cost is O(n^2), with headroom + @pytest.mark.performance def test_memory_usage(self): - """Test memory usage during execution""" - import psutil + """Executing a 12-qubit circuit should not use much memory.""" + psutil = pytest.importorskip("psutil") import os - + process = psutil.Process(os.getpid()) initial_memory = process.memory_info().rss - - # Create and execute large circuit - circuit = QuantumCircuit(12) + + backend = get_backend('simulator', max_qubits=12) + circuit = backend.create_circuit(12) for i in range(12): - circuit.h(i) - circuit.measure_all() - - backend = get_backend('simulator') - result = backend.execute(circuit, shots=1000) - - final_memory = process.memory_info().rss - memory_increase = final_memory - initial_memory - - # Memory increase should be reasonable (less than 100MB) - assert memory_increase < 100 * 1024 * 1024 + backend.add_gate(circuit, 'H', i) + backend.add_measurement(circuit) + backend.execute_circuit(circuit, shots=1000) + + assert process.memory_info().rss - initial_memory < 100 * 1024 * 1024 ``` ### Regression Testing ```python class TestRegression: - def test_known_algorithm_results(self): - """Test that algorithms produce known results on standard datasets""" - # Store expected results for regression testing - expected_results = { - 'iris_qsvm_accuracy': 0.95, - 'bell_state_fidelity': 0.99, - 'vqe_h2_energy': -1.137 - } - - # Test each known result - for test_name, expected_value in expected_results.items(): - if test_name == 'iris_qsvm_accuracy': - actual_value = self._test_iris_qsvm() - assert abs(actual_value - expected_value) < 0.05 - - def _test_iris_qsvm(self): - """Helper method for QSVM on Iris dataset""" + """Pin results recorded on SuperQuantX 0.3.0 so changes are noticed.""" + + def test_iris_qsvm_accuracy(self): from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split - - # Use subset of Iris dataset (2 classes, 2 features) + iris = load_iris() - X = iris.data[:100, :2] # First 2 features, first 2 classes - y = iris.target[:100] - + X, y = iris.data[:100, :2], iris.target[:100] # 2 classes, 2 features X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42 ) - - qsvm = QuantumSVM(backend='simulator') - qsvm.fit(X_train, y_train) - predictions = qsvm.predict(X_test) - - return np.mean(predictions == y_test) + qsvm = QuantumSVM(backend='simulator', feature_map='ZFeatureMap', feature_map_reps=1) + accuracy = np.mean(qsvm.fit(X_train, y_train).predict(X_test) == y_test) + + assert abs(accuracy - 0.77) < 0.05 # baseline recorded on 0.3.0 + + def test_vqe_h2_energy(self): + from superquantx import VQE, Hamiltonian + + h2 = Hamiltonian.from_dict({ + 'II': -1.0523732, 'ZI': 0.39793742, 'IZ': -0.39793742, + 'ZZ': -0.01128010, 'XX': 0.18093119, + }) + energy = VQE(hamiltonian=h2, backend='simulator', optimizer='COBYLA', seed=0).find_ground_state() + + assert abs(energy - (-1.857275)) < 1e-3 # exact: h2.ground_state_energy() ``` ## 🛠️ Test Utilities @@ -529,30 +439,38 @@ def ghz_state(n_qubits): ```python # tests/fixtures/test_circuits.py -from superquantx.circuits import QuantumCircuit +import numpy as np +from superquantx import get_backend + -def bell_circuit(): - """Create Bell state preparation circuit""" - circuit = QuantumCircuit(2, 2) - circuit.h(0) - circuit.cx(0, 1) - circuit.measure_all() +def bell_circuit(backend): + """Bell state preparation on a backend circuit.""" + circuit = backend.create_circuit(2) + backend.add_gate(circuit, 'H', 0) + backend.add_gate(circuit, 'CNOT', [0, 1]) + backend.add_measurement(circuit) return circuit -def qft_circuit(n_qubits): - """Create Quantum Fourier Transform circuit""" - circuit = QuantumCircuit(n_qubits) - + +def qft_circuit(backend, n_qubits): + """Quantum Fourier Transform built from H, controlled-RZ and SWAP. + + CRZ(theta) equals the controlled-phase gate up to a phase on the control, + which is enough for tests that compare measurement statistics. + """ + circuit = backend.create_circuit(n_qubits) for i in range(n_qubits): - circuit.h(i) + backend.add_gate(circuit, 'H', i) for j in range(i + 1, n_qubits): - circuit.cp(np.pi / 2**(j - i), j, i) - - # Reverse qubit order + backend.add_gate(circuit, 'CRZ', [j, i], [np.pi / 2 ** (j - i)]) for i in range(n_qubits // 2): - circuit.swap(i, n_qubits - 1 - i) - + backend.add_gate(circuit, 'SWAP', [i, n_qubits - 1 - i]) return circuit + + +sim = get_backend('simulator') +print(sim.execute_circuit(bell_circuit(sim), shots=100)['counts']) +print(qft_circuit(sim, 3) is not None) ``` ## 📊 Test Reporting diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index c1a2966..5280614 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -1,9 +1,5 @@ # 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 @@ -257,6 +253,10 @@ PENNYLANE_DEVICE=lightning.qubit Load it in your Python script: +!!! note "Optional dependency" + Needs an extra package that is not part of SuperQuantX 0.3.0; not run. + + ```python import os from dotenv import load_dotenv @@ -387,6 +387,10 @@ print(f"Max qubits: {sqx.get_config('max_qubits')}") ### Secure Key Management +!!! note "Optional dependency" + Needs an extra package that is not part of SuperQuantX 0.3.0; not run. + + ```python import superquantx as sqx from keyring import get_password diff --git a/docs/getting-started/first-program.md b/docs/getting-started/first-program.md index a51a1b1..a95ef6b 100644 --- a/docs/getting-started/first-program.md +++ b/docs/getting-started/first-program.md @@ -1,9 +1,5 @@ # 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 diff --git a/docs/mcp.md b/docs/mcp.md index cae99d5..4c296b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -203,13 +203,25 @@ Use SuperQuantX 0.3.0 or newer; 0.2.0 does not include the MCP server. `examples/mcp_client_demo.py` launches the server over stdio with the official SDK client and calls every tool: +!!! note "Requires a running MCP client session" + Illustrates the official MCP Python client; skipped in the docs checker because it launches a subprocess server. + + ```python -from mcp import Client, StdioServerParameters +import asyncio +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client params = StdioServerParameters(command="python", args=["-m", "superquantx.mcp"]) -async with Client(params) as client: - result = await client.call_tool("bell_state_demo", {"shots": 1000}) - print(result.structured_content) + +async def main(): + async with stdio_client(params) as (read, write): + async with ClientSession(read, write) as client: + await client.initialize() + result = await client.call_tool("bell_state_demo", {"shots": 1000}) + print(result) + +asyncio.run(main()) ``` ## How it relates to the IBM Qiskit MCP servers diff --git a/docs/tutorials/basic-quantum.md b/docs/tutorials/basic-quantum.md index 1d46dbf..327ab13 100644 --- a/docs/tutorials/basic-quantum.md +++ b/docs/tutorials/basic-quantum.md @@ -1,9 +1,5 @@ # 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 diff --git a/docs/tutorials/quantum-ml.md b/docs/tutorials/quantum-ml.md index 4ddf731..5b5265e 100644 --- a/docs/tutorials/quantum-ml.md +++ b/docs/tutorials/quantum-ml.md @@ -1,9 +1,5 @@ # 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 @@ -1014,10 +1010,11 @@ def complete_qml_pipeline(): backend='simulator', feature_map='ZZFeatureMap' ), - 'VQC': sqx.VariationalQuantumClassifier( - n_qubits=4, - n_layers=2, - backend='simulator' + 'QuantumNN': sqx.QuantumNN( + backend='simulator', + n_layers=2, + max_epochs=20, + seed=0, ) } @@ -1026,11 +1023,7 @@ def complete_qml_pipeline(): try: # Train - if 'VQC' in name: - model.compile(optimizer='adam', learning_rate=0.1) - model.fit(X_train, y_train, epochs=20, verbose=0) - else: - model.fit(X_train, y_train) + model.fit(X_train, y_train) # Predict y_pred = model.predict(X_test) diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index b5ac4a6..3e17c59 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -1,1011 +1,399 @@ # 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 quantum algorithms for machine learning and optimisation, each with a classical check. This guide shows how to use them, how to build textbook algorithms from gates, and how to write your own algorithm class. +Every example on this page runs on SuperQuantX 0.3.0 with the built-in `'simulator'` backend, except the annealing example, which needs the `ocean` extra (`uv add "superquantx[ocean]==0.3.0"`). -SuperQuantX provides quantum algorithms for machine learning and optimisation, each with a classical check. This guide covers how to use, customize, and combine these algorithms in your research. +## 🎯 What ships in 0.3.0 -## 🎯 Algorithm Categories +| Category | Classes and functions | +|---|---| +| Machine learning | `QuantumSVM`, `QuantumNN`, `QuantumKMeans`, `QuantumPCA` (`HybridClassifier` has a known issue, see below) | +| Optimisation | `VQE`, `QAOA`, `create_vqe_for_molecule`, `OceanBackend.solve_qubo` / `solve_ising` / `solve_max_cut` | +| Physics | `Hamiltonian`, `PauliString` (exact ground state, time evolution, expectation values) | +| Evaluation | `compare_to_classical`, `benchmark_algorithm` | +| Agents | see the [Agents API](../api/agents.md) | -SuperQuantX organizes quantum algorithms into several categories: +!!! note "Not available as library classes" + There are no `QuantumFourierTransform`, `QuantumPhaseEstimation`, `QuantumTeleportation`, `GroversAlgorithm`, `QuantumWalk`, `QuantumGAN`, `VariationalQuantumClassifier`, `VariationalQuantumSimulator`, `BB84Protocol`, `ShorsAlgorithm`, `MaxCutProblem` or `QuantumAnnealer` classes in 0.3.0. The section below builds several textbook algorithms directly from gates instead. -- **🔬 Fundamental Algorithms**: Basic quantum computing building blocks -- **🧠 Quantum Machine Learning**: ML algorithms leveraging quantum computation -- **⚡ Optimization Algorithms**: Quantum approaches to optimization problems -- **🔍 Search Algorithms**: Quantum search and database query methods -- **🔐 Cryptographic Algorithms**: Quantum cryptography and security -- **🧮 Simulation Algorithms**: Quantum system simulation methods +## 🔬 Textbook algorithms built from gates -## 🔬 Fundamental Quantum Algorithms +The simulator circuit has gate methods (`h`, `x`, `y`, `z`, `rx`, `ry`, `rz`, `cx`, `cz`) and `apply_gate(matrix, qubits)` for any other unitary. `backend.statevector_big_endian(circuit)` returns the state with qubit 0 as the most significant bit. ### Quantum Fourier Transform (QFT) -The QFT is fundamental to many quantum algorithms: - ```python -import superquantx as sqx import numpy as np +import superquantx as sqx -# Create QFT algorithm -qft = sqx.QuantumFourierTransform(n_qubits=4, backend='pennylane') +backend = sqx.get_backend('simulator') -# Apply to a quantum state -backend = sqx.get_backend('pennylane') -circuit = backend.create_circuit(4) -# Prepare initial state (can be any superposition) -circuit.h(0) -circuit.h(1) +def cphase(theta): + """Controlled phase gate as a 4x4 matrix.""" + return np.diag([1, 1, 1, np.exp(1j * theta)]) + + +SWAP = np.eye(4)[[0, 2, 1, 3]] + + +def qft(circuit, n): + for j in range(n): + circuit.h(j) + for k in range(j + 1, n): + circuit.apply_gate(cphase(np.pi / 2 ** (k - j)), [k, j]) + for j in range(n // 2): + circuit.apply_gate(SWAP, [j, n - 1 - j]) + return circuit -# Apply QFT -qft_circuit = qft.create_circuit() -combined_circuit = circuit + qft_circuit -# Execute -result = backend.run(combined_circuit, shots=1000) -print(f"QFT result: {result.get_counts()}") +n = 3 +circuit = backend.create_circuit(n) +circuit.x(2) # prepare |001> = basis state 1 +qft(circuit, n) -# Visualize the frequency domain -qft.plot_frequency_spectrum(result) +state = backend.statevector_big_endian(circuit) +expected = np.exp(2j * np.pi * 1 * np.arange(2 ** n) / 2 ** n) / np.sqrt(2 ** n) +print("QFT output phases (units of 2pi):", np.round(np.angle(state) / (2 * np.pi) % 1, 3)) +print("Matches the DFT of |1>:", np.allclose(state, expected)) ``` ### Quantum Phase Estimation (QPE) -Estimate eigenvalues of unitary operators: +Estimate the phase of the T gate, whose eigenvalue on |1> is exp(2 pi i / 8). Three counting qubits recover the phase 1/8 exactly. This reuses `cphase` and `SWAP` from the QFT example. ```python -# Create a unitary operator (e.g., rotation) -import numpy as np +def inverse_qft(circuit, qubits): + n = len(qubits) + for j in range(n // 2): + circuit.apply_gate(SWAP, [qubits[j], qubits[n - 1 - j]]) + for j in reversed(range(n)): + for k in reversed(range(j + 1, n)): + circuit.apply_gate(cphase(-np.pi / 2 ** (k - j)), [qubits[k], qubits[j]]) + circuit.h(qubits[j]) -def create_rotation_unitary(theta): - """Create a rotation unitary matrix.""" - return np.array([ - [np.cos(theta/2), -1j*np.sin(theta/2)], - [-1j*np.sin(theta/2), np.cos(theta/2)] - ]) - -# Phase estimation algorithm -theta = np.pi/4 # True phase -unitary = create_rotation_unitary(theta) - -qpe = sqx.QuantumPhaseEstimation( - unitary_operator=unitary, - precision_qubits=4, # Number of qubits for precision - backend='qiskit' -) -estimated_phase = qpe.estimate() -print(f"True phase: {theta:.6f}") -print(f"Estimated phase: {estimated_phase:.6f}") -print(f"Error: {abs(theta - estimated_phase):.6f}") +phase = 1 / 8 # T gate +counting = [0, 1, 2] +target = 3 + +circuit = backend.create_circuit(4) +circuit.x(target) # eigenstate |1> +for q in counting: + circuit.h(q) +for i, q in enumerate(counting): + power = 2 ** (len(counting) - 1 - i) # qubit 0 is the most significant bit + circuit.apply_gate(cphase(2 * np.pi * phase * power), [q, target]) +inverse_qft(circuit, counting) + +probs = np.abs(backend.statevector_big_endian(circuit)) ** 2 +best = format(int(np.argmax(probs)), '04b') +estimate = int(best[:3], 2) / 2 ** 3 +print(f"Most likely outcome {best}, estimated phase {estimate} (true {phase})") ``` -### Quantum Teleportation +### Quantum teleportation -Demonstrate quantum information transfer: +This version uses the deferred-measurement form: the classically controlled corrections become controlled gates, so the whole protocol is one unitary circuit and fidelity can be checked from the statevector. ```python -# Quantum teleportation protocol -teleportation = sqx.QuantumTeleportation(backend='simulator') +theta, phi = 1.1, 0.4 -# Prepare arbitrary quantum state to teleport -state_to_teleport = [0.6, 0.8j] # α|0⟩ + β|1⟩ +# The state to teleport, prepared on its own for reference +ref = backend.create_circuit(1) +ref.ry(theta, 0) +ref.rz(phi, 0) +psi = backend.statevector_big_endian(ref) -# Perform teleportation -teleported_state = teleportation.teleport_state(state_to_teleport) +circuit = backend.create_circuit(3) +circuit.ry(theta, 0) +circuit.rz(phi, 0) # qubit 0 holds |psi> +circuit.h(1) +circuit.cx(1, 2) # Bell pair on qubits 1 and 2 +circuit.cx(0, 1) +circuit.h(0) # Bell measurement basis +circuit.cx(1, 2) # X correction +circuit.cz(0, 2) # Z correction + +state = backend.statevector_big_endian(circuit).reshape(2, 2, 2) +rho_bob = np.einsum('abi,abj->ij', state, state.conj()) # trace out qubits 0 and 1 +fidelity = np.real(psi.conj() @ rho_bob @ psi) +print(f"Teleportation fidelity: {fidelity:.6f}") +``` -print(f"Original state: {state_to_teleport}") -print(f"Teleported state: {teleported_state}") +### Grover's search -# Verify fidelity -fidelity = teleportation.calculate_fidelity(state_to_teleport, teleported_state) -print(f"Teleportation fidelity: {fidelity:.6f}") +Two-qubit Grover search for the marked item |11>. One iteration finds it with certainty. + +```python +circuit = backend.create_circuit(2) +circuit.h(0); circuit.h(1) # uniform superposition +circuit.cz(0, 1) # oracle: flip the phase of |11> +circuit.h(0); circuit.h(1) # diffusion operator +circuit.x(0); circuit.x(1) +circuit.cz(0, 1) +circuit.x(0); circuit.x(1) +circuit.h(0); circuit.h(1) +circuit.measure_all() + +counts = backend.run(circuit, shots=1000).get_counts() +print("Grover counts:", counts) ``` ## 🧠 Quantum Machine Learning ### Quantum Support Vector Machine (QSVM) -Quantum-enhanced classification: +`QuantumSVM` computes a quantum kernel and trains a classical SVM on it. Supported feature maps are `'ZZFeatureMap'`, `'ZFeatureMap'`, `'PauliFeatureMap'` and `'AngleEncoding'`; `feature_map_reps` sets the depth. ```python from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split +from sklearn.svm import SVC +import superquantx as sqx -# Create dataset -X, y = make_classification( - n_samples=200, - n_features=4, - n_classes=2, - n_redundant=0, - random_state=42 -) +X, y = make_classification(n_samples=80, n_features=4, n_classes=2, n_redundant=0, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - -# Quantum SVM with different feature maps -feature_maps = ['ZFeatureMap', 'ZZFeatureMap', 'PauliFeatureMap'] -results = {} - -for feature_map in feature_maps: - qsvm = sqx.QuantumSVM( - backend='pennylane', - feature_map=feature_map, - num_features=4, - depth=2 - ) - - # Train the model +for feature_map in ['ZFeatureMap', 'ZZFeatureMap', 'PauliFeatureMap']: + qsvm = sqx.QuantumSVM(backend='simulator', feature_map=feature_map, feature_map_reps=2) qsvm.fit(X_train, y_train) - - # Evaluate - accuracy = qsvm.score(X_test, y_test) - results[feature_map] = accuracy - - print(f"QSVM with {feature_map}: {accuracy:.3f}") - -# Compare with classical SVM -from sklearn.svm import SVC -classical_svm = SVC(kernel='rbf') -classical_svm.fit(X_train, y_train) -classical_accuracy = classical_svm.score(X_test, y_test) + print(f"QSVM with {feature_map}: {qsvm.score(X_test, y_test):.3f}") -print(f"Classical SVM: {classical_accuracy:.3f}") +classical = SVC(kernel='rbf').fit(X_train, y_train) +print(f"Classical RBF SVM: {classical.score(X_test, y_test):.3f}") ``` -### Variational Quantum Classifier (VQC) - -Trainable quantum classifier: - -```python -# Variational Quantum Classifier -vqc = sqx.VariationalQuantumClassifier( - n_qubits=4, - n_layers=3, - backend='pennylane', - optimizer='adam' -) - -# Configure training -vqc.compile( - optimizer='adam', - learning_rate=0.01, - loss='binary_crossentropy' -) - -# Train the classifier -history = vqc.fit( - X_train, y_train, - epochs=100, - validation_data=(X_test, y_test), - verbose=1 -) - -# Plot training history -vqc.plot_training_history(history) - -# Make predictions -predictions = vqc.predict(X_test) -probabilities = vqc.predict_proba(X_test) - -print(f"VQC Accuracy: {vqc.score(X_test, y_test):.3f}") -``` +A single train/test split is noisy. For a fair comparison use `compare_to_classical` (see [Benchmarking](benchmarking.md)), which tunes the classical baselines and reports a p-value. ### Quantum Neural Network (QNN) -Deep quantum neural networks: +`QuantumNN` is a trainable variational circuit with angle encoding. It covers the "variational quantum classifier" use case. ```python -# Build quantum neural network -qnn = sqx.QuantumNeuralNetwork( - architecture=[ - sqx.layers.QuantumConv2D(filters=4, kernel_size=2), - sqx.layers.QuantumPooling2D(pool_size=2), - sqx.layers.QuantumDense(units=16, activation='relu'), - sqx.layers.QuantumDense(units=2, activation='softmax') - ], - backend='pennylane' +qnn = sqx.QuantumNN( + backend='simulator', + n_layers=2, + encoding='angle', + entanglement='linear', + learning_rate=0.05, + max_epochs=20, + task_type='classification', + seed=0, ) - -# Compile model -qnn.compile( - optimizer='adam', - loss='sparse_categorical_crossentropy', - metrics=['accuracy'] -) - -# Train on quantum data -qnn.fit(X_train, y_train, epochs=50, batch_size=32) - -# Evaluate -test_loss, test_accuracy = qnn.evaluate(X_test, y_test) -print(f"QNN Test Accuracy: {test_accuracy:.3f}") +qnn.fit(X_train, y_train) +print(f"QNN test accuracy: {qnn.score(X_test, y_test):.3f}") +history = qnn.get_training_history() +print("Training history keys:", list(history)) ``` -### Quantum Generative Adversarial Network (QGAN) +### Hybrid classifier -Generate quantum data: +!!! bug "Known issue in 0.3.0" + `HybridClassifier` is exported but does not work reliably in 0.3.0: the default `'ensemble'` mode and the `'voting'` and `'stacking'` modes raise a NumPy shape error in `fit`, and `'sequential'` trains but gives poor accuracy. Until this is fixed, compare quantum and classical models with `compare_to_classical` (below) instead. -```python -# Quantum GAN for data generation -qgan = sqx.QuantumGAN( - generator_layers=3, - discriminator_layers=2, - latent_dim=4, - backend='pennylane' -) - -# Train QGAN -qgan.fit( - X_train, - epochs=100, - batch_size=16 -) - -# Generate new samples -generated_samples = qgan.generate(n_samples=100) - -# Visualize real vs generated data -qgan.plot_data_comparison(X_train, generated_samples) -``` +!!! note "Not available in 0.3.0" + Quantum GANs and Keras-style layer APIs (`sqx.layers`, `model.compile`) are not implemented. ## ⚡ Optimization Algorithms ### Variational Quantum Eigensolver (VQE) -Find ground state energies: - ```python -# Define Hamiltonian (e.g., H2 molecule) -def create_h2_hamiltonian(bond_distance=0.74): - """Create H2 molecule Hamiltonian.""" - # Simplified H2 Hamiltonian coefficients - coeffs = [ - -1.0523732, # Identity - 0.39793742, # Z0 - -0.39793742, # Z1 - -0.01128010, # Z0Z1 - 0.18093119 # X0X1 - ] - - paulis = [ - sqx.PauliString('II'), - sqx.PauliString('ZI'), - sqx.PauliString('IZ'), - sqx.PauliString('ZZ'), - sqx.PauliString('XX') - ] - - return sqx.Hamiltonian(coeffs, paulis) - -# Create VQE algorithm -h2_hamiltonian = create_h2_hamiltonian() - -vqe = sqx.VQE( - hamiltonian=h2_hamiltonian, - ansatz='UCCSD', # Unitary Coupled Cluster - optimizer='COBYLA', - backend='pennylane' -) +import superquantx as sqx -# Find ground state -ground_energy = vqe.find_ground_state() -ground_state = vqe.get_ground_state_vector() +# Two-qubit reduced H2 Hamiltonian (STO-3G, 0.74 Angstrom) +h2 = sqx.Hamiltonian.from_dict({ + 'II': -1.0523732, + 'ZI': 0.39793742, + 'IZ': -0.39793742, + 'ZZ': -0.01128010, + 'XX': 0.18093119, +}) -print(f"Ground state energy: {ground_energy:.6f} Ha") +vqe = sqx.VQE(hamiltonian=h2, ansatz='RealAmplitudes', optimizer='COBYLA', backend='simulator', seed=0) +ground_energy = vqe.find_ground_state() +exact_energy = h2.ground_state_energy() -# Compare with exact diagonalization -exact_energy = h2_hamiltonian.ground_state_energy() +print(f"VQE energy: {ground_energy:.6f} Ha") print(f"Exact energy: {exact_energy:.6f} Ha") -print(f"Error: {abs(ground_energy - exact_energy):.6f} Ha") -``` - -### Quantum Approximate Optimization Algorithm (QAOA) - -Solve combinatorial optimization: - -```python -# Max-Cut problem example -def create_maxcut_problem(graph_edges, weights=None): - """Create Max-Cut problem instance.""" - if weights is None: - weights = [1.0] * len(graph_edges) - - problem = sqx.MaxCutProblem(edges=graph_edges, weights=weights) - return problem - -# Define graph -edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] -maxcut_problem = create_maxcut_problem(edges) - -# QAOA solver -qaoa = sqx.QAOA( - problem=maxcut_problem, - layers=3, # p parameter - optimizer='SPSA', - backend='qiskit' -) - -# Solve optimization problem -optimal_solution = qaoa.solve() -optimal_value = qaoa.get_optimal_value() - -print(f"Optimal cut value: {optimal_value}") -print(f"Optimal solution: {optimal_solution}") - -# Visualize optimization landscape -qaoa.plot_optimization_landscape() -``` - -### Quantum Annealing - -Solve optimization via quantum annealing: - -```python -# Quantum annealing for QUBO problems -qubo_matrix = np.array([ - [-1, 2, 2], - [0, -1, 2], - [0, 0, -1] -]) - -annealer = sqx.QuantumAnnealer( - backend='ocean', # D-Wave Ocean backend - annealing_time=20, # microseconds - num_reads=1000 -) - -# Solve QUBO -solution = annealer.solve_qubo(qubo_matrix) - -print(f"Best solution: {solution.best_solution}") -print(f"Best energy: {solution.best_energy}") -print(f"Solution frequency: {solution.solution_counts}") +print(f"Error: {abs(ground_energy - exact_energy):.2e} Ha") ``` -## 🔍 Search Algorithms - -### Grover's Algorithm - -Quantum database search: - -```python -# Grover's algorithm for unstructured search -def oracle_function(x): - """Oracle that marks target items.""" - # Mark items 3 and 7 as targets - return x in [3, 7] - -grover = sqx.GroversAlgorithm( - search_space_size=16, # 2^4 items - oracle=oracle_function, - backend='cirq' -) +`create_vqe_for_molecule('H2')` builds the same problem from the bundled molecular data. A `'UCCSD'` ansatz is not available; use `'RealAmplitudes'` or a callable. -# Run search -search_results = grover.search() - -print(f"Target items found: {search_results.targets}") -print(f"Success probability: {search_results.success_probability:.3f}") -print(f"Number of iterations: {search_results.iterations}") - -# Analyze amplitude amplification -grover.plot_amplitude_evolution() -``` - -### Quantum Walk Algorithm +### Quantum Approximate Optimization Algorithm (QAOA) -Quantum random walk for graph traversal: +`QAOA.solve(adjacency)` runs weighted MaxCut and checks the answer by brute force. ```python -# Quantum walk on a graph -import networkx as nx - -# Create graph -G = nx.cycle_graph(8) # 8-node cycle graph - -quantum_walk = sqx.QuantumWalk( - graph=G, - steps=10, - backend='simulator' -) - -# Run quantum walk starting from node 0 -probability_distribution = quantum_walk.run(start_node=0) +import numpy as np -print(f"Final probability distribution: {probability_distribution}") +edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)] +adjacency = np.zeros((4, 4)) +for i, j in edges: + adjacency[i, j] = adjacency[j, i] = 1.0 -# Compare with classical random walk -classical_walk = sqx.ClassicalWalk(graph=G, steps=10) -classical_distribution = classical_walk.run(start_node=0) +qaoa = sqx.QAOA(backend='simulator', p=3, optimizer='COBYLA', seed=0) +result = qaoa.solve(adjacency) -# Plot comparison -quantum_walk.plot_distribution_comparison( - probability_distribution, - classical_distribution -) +print("Best partition:", result['bitstring']) +print("Cut value:", result['cut_value'], "of optimum", result['classical_optimum']) +print("Approximation ratio:", round(result['approximation_ratio'], 3)) ``` -## 🔐 Cryptographic Algorithms +### Quantum annealing (D-Wave Ocean) -### Quantum Key Distribution (QKD) - -Secure key exchange: +Annealing problems go through the `ocean` backend. Without D-Wave credentials it uses the local simulated annealer. ```python -# BB84 Quantum Key Distribution protocol -qkd = sqx.BB84Protocol( - key_length=128, - noise_level=0.05, # 5% channel noise - backend='simulator' -) +ocean = sqx.get_backend('ocean') -# Alice and Bob generate shared key -alice_key, bob_key, security_params = qkd.generate_shared_key() +# Minimise -x0 - x1 - x2 + 2 x0 x1 + 2 x0 x2 + 2 x1 x2 (pick exactly one variable) +Q = {(0, 0): -1, (1, 1): -1, (2, 2): -1, (0, 1): 2, (0, 2): 2, (1, 2): 2} +result = ocean.solve_qubo(Q, num_reads=100) -print(f"Alice's key: {alice_key[:20]}...") # Show first 20 bits -print(f"Bob's key: {bob_key[:20]}...") -print(f"Key agreement: {alice_key == bob_key}") -print(f"Security parameters: {security_params}") - -# Detect eavesdropping -eve_present = qkd.detect_eavesdropping() -print(f"Eavesdropping detected: {eve_present}") +best = int(np.argmin(result['energies'])) +print("Best solution:", {k: int(v) for k, v in result['samples'][best].items()}) +print("Best energy:", float(result['energies'][best])) ``` -### Shor's Algorithm +## 🧮 Simulating quantum systems -Factor large integers: +`Hamiltonian` gives exact reference values for small systems: the matrix, ground-state energy, expectation values and time evolution. ```python -# Shor's algorithm for integer factorization -def shors_algorithm(N, backend='qiskit'): - """Factor integer N using Shor's algorithm.""" - - shor = sqx.ShorsAlgorithm( - N=N, - backend=backend, - optimization_level=2 - ) - - factors = shor.factor() - return factors - -# Example: Factor 15 (should give factors 3 and 5) -N = 15 -factors = shors_algorithm(N) - -print(f"Factors of {N}: {factors}") -print(f"Verification: {factors[0] * factors[1] == N}") - -# For larger numbers (requires more qubits) -# N = 21 -# factors = shors_algorithm(N, backend='simulator') +ising = sqx.Hamiltonian.ising_model(4, J=1.0, h=0.5) +print(f"Ising ground-state energy: {ising.ground_state_energy():.6f}") + +# Time evolution of |0000> under the Ising Hamiltonian: the energy is conserved, +# but the magnetisation of qubit 0 oscillates because of the transverse field +z0 = sqx.Hamiltonian.from_dict({'ZIII': 1.0}) +psi0 = np.zeros(2 ** 4, dtype=complex) +psi0[0] = 1.0 +for t in [0.0, 0.5, 1.0, 2.0]: + psi_t = ising.time_evolution(t) @ psi0 + energy = np.real(ising.expectation_value(psi_t)) + magnetisation = np.real(z0.expectation_value(psi_t)) + print(f"t={t}: = {energy:.4f}, = {magnetisation:.4f}") + +# The same Hamiltonian solved variationally +vqe = sqx.VQE(hamiltonian=ising, backend='simulator', reps=2, seed=0) +print(f"VQE: {vqe.find_ground_state():.6f}") ``` -## 🧮 Simulation Algorithms - -### Quantum System Simulation - -Simulate quantum many-body systems: - -```python -# Simulate Ising model -def create_ising_hamiltonian(n_spins, coupling_strength=1.0, field_strength=0.5): - """Create transverse field Ising model Hamiltonian.""" - - terms = [] - coefficients = [] - - # Coupling terms: -J * Z_i * Z_{i+1} - for i in range(n_spins - 1): - pauli_string = ['I'] * n_spins - pauli_string[i] = 'Z' - pauli_string[i + 1] = 'Z' - terms.append(sqx.PauliString(''.join(pauli_string))) - coefficients.append(-coupling_strength) - - # Transverse field terms: -h * X_i - for i in range(n_spins): - pauli_string = ['I'] * n_spins - pauli_string[i] = 'X' - terms.append(sqx.PauliString(''.join(pauli_string))) - coefficients.append(-field_strength) - - return sqx.Hamiltonian(coefficients, terms) - -# Create and simulate Ising model -n_spins = 4 -ising_hamiltonian = create_ising_hamiltonian(n_spins) - -simulator = sqx.QuantumSimulator( - hamiltonian=ising_hamiltonian, - backend='pennylane' -) - -# Time evolution -initial_state = sqx.create_plus_state(n_spins) # All spins in |+⟩ -evolution_times = np.linspace(0, 2*np.pi, 50) - -evolved_states = simulator.time_evolution( - initial_state=initial_state, - times=evolution_times -) - -# Analyze dynamics -magnetization = simulator.measure_observable( - evolved_states, - observable='magnetization' -) - -simulator.plot_dynamics(evolution_times, magnetization) -``` +!!! note "Not available in 0.3.0" + Excited-state solvers, quantum walks, BB84 key distribution and Shor's algorithm are not implemented. -### Variational Quantum Simulator (VQS) +## 🔧 Custom Algorithm Development -Simulate ground states of complex systems: +Subclass `BaseQuantumAlgorithm` and implement `fit` and `predict`. The base class resolves `backend` to a backend object and stores `shots` and `seed`. ```python -# Variational quantum simulation -vqs = sqx.VariationalQuantumSimulator( - hamiltonian=ising_hamiltonian, - ansatz='hardware_efficient', - layers=6, - backend='pennylane' -) - -# Find ground state -ground_state_energy, ground_state_params = vqs.find_ground_state() - -print(f"VQS ground state energy: {ground_state_energy:.6f}") - -# Compare with exact diagonalization -exact_ground_energy = ising_hamiltonian.ground_state_energy() -print(f"Exact ground state energy: {exact_ground_energy:.6f}") -print(f"Error: {abs(ground_state_energy - exact_ground_energy):.6f}") - -# Analyze excited states -excited_states = vqs.find_excited_states(num_states=3) -print(f"Excited state energies: {excited_states}") -``` +import numpy as np +from scipy.optimize import minimize +from superquantx.algorithms import BaseQuantumAlgorithm -## 🔧 Custom Algorithm Development -### Building Custom Algorithms +class GroundStateProbability(BaseQuantumAlgorithm): + """Train RY angles so that measuring gives |00...0> as often as possible.""" -```python -from superquantx.algorithms import BaseQuantumAlgorithm + def __init__(self, n_qubits=3, backend='simulator', **kwargs): + super().__init__(backend=backend, **kwargs) + self.n_qubits = n_qubits -class MyQuantumAlgorithm(BaseQuantumAlgorithm): - """Template for custom quantum algorithms.""" - - def __init__(self, backend='simulator', **kwargs): - super().__init__(backend=backend) - self.parameters = kwargs - - def create_ansatz(self, params): - """Create the quantum circuit ansatz.""" + def circuit(self, params): circuit = self.backend.create_circuit(self.n_qubits) - - # Your custom circuit construction logic for i, param in enumerate(params): - circuit.ry(param, i % self.n_qubits) - - # Add entangling gates + circuit.ry(param, i) for i in range(self.n_qubits - 1): circuit.cx(i, i + 1) - return circuit - - def cost_function(self, params): - """Define the cost function to optimize.""" - circuit = self.create_ansatz(params) - - # Add measurement - circuit.measure_all() - - # Execute and compute cost - result = self.backend.run(circuit, shots=1000) - counts = result.get_counts() - - # Example cost: maximize |00...0⟩ state probability - ground_state_prob = counts.get('0' * self.n_qubits, 0) / 1000 - return -ground_state_prob # Minimize negative probability - - def optimize(self, initial_params=None): - """Run the optimization.""" - if initial_params is None: - initial_params = np.random.random(self.n_qubits) * 2 * np.pi - - from scipy.optimize import minimize - - result = minimize( - self.cost_function, - initial_params, - method='COBYLA' - ) - - return result.x, result.fun - -# Use custom algorithm -custom_algo = MyQuantumAlgorithm(n_qubits=4, backend='pennylane') -optimal_params, optimal_cost = custom_algo.optimize() - -print(f"Optimal parameters: {optimal_params}") -print(f"Optimal cost: {optimal_cost}") -``` -### Algorithm Composition + def cost(self, params): + probs = np.abs(self.backend.statevector_big_endian(self.circuit(params))) ** 2 + return -probs[0] -```python -# Combine multiple algorithms -class HybridQuantumAlgorithm: - """Combine quantum algorithms for complex problems.""" - - def __init__(self, backend='pennylane'): - self.backend = backend - self.vqe = sqx.VQE(backend=backend) - self.qaoa = sqx.QAOA(backend=backend) - self.grover = sqx.GroversAlgorithm(backend=backend) - - def solve_optimization_with_search(self, problem): - """Use QAOA + Grover for optimization.""" - - # First, get approximate solution with QAOA - qaoa_solution = self.qaoa.solve(problem) - - # Use QAOA solution to define search space for Grover - search_space = self.create_search_space(qaoa_solution) - - # Refine with Grover's algorithm - refined_solution = self.grover.search(search_space) - - return refined_solution - - def quantum_ml_with_simulation(self, hamiltonian, training_data): - """Combine VQE and ML for quantum system learning.""" - - # Use VQE to understand ground state - ground_energy = self.vqe.find_ground_state(hamiltonian) - - # Use ground state information in ML model - qnn = sqx.QuantumNeuralNetwork( - n_qubits=hamiltonian.n_qubits, - backend=self.backend - ) - - # Initialize with VQE solution - initial_params = self.vqe.optimal_parameters - qnn.set_initial_parameters(initial_params) - - # Train ML model - qnn.fit(training_data) - - return qnn - -# Example usage -hybrid_algo = HybridQuantumAlgorithm(backend='pennylane') -# ml_model = hybrid_algo.quantum_ml_with_simulation(my_hamiltonian, training_data) -``` + def fit(self, X=None, y=None, **kwargs): + x0 = np.random.default_rng(self.seed).uniform(0, 2 * np.pi, self.n_qubits) + res = minimize(self.cost, x0, method='COBYLA') + self.optimal_params_, self.optimal_cost_ = res.x, res.fun + self.is_fitted = True + return self -## 📊 Algorithm Performance Analysis + def predict(self, X=None, **kwargs): + circuit = self.circuit(self.optimal_params_) + circuit.measure_all() + return self.backend.run(circuit, shots=self.shots).get_counts() -### Benchmarking Framework -```python -class QuantumAlgorithmBenchmark: - """Benchmark quantum algorithms across different metrics.""" - - def __init__(self): - self.results = {} - - def benchmark_algorithm(self, algorithm_class, problem_instances, backends): - """Benchmark algorithm across problems and backends.""" - - results = [] - - for problem in problem_instances: - for backend_name in backends: - try: - # Initialize algorithm - algo = algorithm_class(backend=backend_name) - - # Measure performance - start_time = time.time() - solution = algo.solve(problem) - end_time = time.time() - - # Collect metrics - metrics = { - 'backend': backend_name, - 'problem_size': getattr(problem, 'size', 'unknown'), - 'execution_time': end_time - start_time, - 'solution_quality': self.evaluate_solution(solution, problem), - 'convergence_steps': getattr(algo, 'num_iterations', None), - 'success': True - } - - except Exception as e: - metrics = { - 'backend': backend_name, - 'problem_size': getattr(problem, 'size', 'unknown'), - 'error': str(e), - 'success': False - } - - results.append(metrics) - - return results - - def create_benchmark_report(self, results): - """Generate comprehensive benchmark report.""" - import pandas as pd - - df = pd.DataFrame(results) - - # Performance summary - successful_results = df[df['success'] == True] - - report = { - 'success_rate': len(successful_results) / len(df), - 'average_execution_time': successful_results['execution_time'].mean(), - 'best_backend': successful_results.loc[ - successful_results['solution_quality'].idxmax(), 'backend' - ], - 'fastest_backend': successful_results.loc[ - successful_results['execution_time'].idxmin(), 'backend' - ] - } - - return report, df - -# Example benchmarking -benchmark = QuantumAlgorithmBenchmark() - -# Create test problems -problems = [ - sqx.create_random_maxcut_problem(n_nodes=4), - sqx.create_random_maxcut_problem(n_nodes=6), - sqx.create_random_maxcut_problem(n_nodes=8) -] - -backends = ['simulator', 'pennylane', 'qiskit'] - -# Run benchmark -results = benchmark.benchmark_algorithm(sqx.QAOA, problems, backends) -report, results_df = benchmark.create_benchmark_report(results) - -print("📊 Benchmark Report:") -for key, value in report.items(): - print(f"{key}: {value}") +algo = GroundStateProbability(n_qubits=3, backend='simulator', seed=0).fit() +print(f"P(|000>) = {-algo.optimal_cost_:.4f}") +print("Sampled counts:", algo.predict()) ``` -## 🚀 Advanced Algorithm Usage +### Combining algorithms -### Parameter Optimization Strategies +Algorithms are plain objects, so composition is ordinary Python. Here QAOA answers a MaxCut problem and VQE checks the energy of the corresponding Ising Hamiltonian. ```python -# Advanced parameter optimization for variational algorithms -class AdvancedOptimizer: - """Advanced optimization strategies for quantum algorithms.""" - - def __init__(self, algorithm): - self.algorithm = algorithm - self.optimization_history = [] - - def adaptive_optimization(self, initial_params): - """Adaptive optimization with multiple strategies.""" - - strategies = [ - {'method': 'COBYLA', 'maxiter': 100}, - {'method': 'SPSA', 'maxiter': 200}, - {'method': 'L-BFGS-B', 'maxiter': 100} - ] - - best_result = None - best_cost = float('inf') - - for strategy in strategies: - try: - result = self.algorithm.optimize( - initial_params=initial_params, - **strategy - ) - - if result.fun < best_cost: - best_cost = result.fun - best_result = result - - self.optimization_history.append({ - 'strategy': strategy['method'], - 'cost': result.fun, - 'success': result.success, - 'iterations': result.nit - }) - - except Exception as e: - print(f"Strategy {strategy['method']} failed: {e}") - - return best_result - - def plot_optimization_comparison(self): - """Plot comparison of optimization strategies.""" - import matplotlib.pyplot as plt - - strategies = [h['strategy'] for h in self.optimization_history] - costs = [h['cost'] for h in self.optimization_history] - - plt.figure(figsize=(10, 6)) - plt.bar(strategies, costs) - plt.title('Optimization Strategy Comparison') - plt.ylabel('Final Cost') - plt.xticks(rotation=45) - plt.tight_layout() - plt.show() - -# Example usage with VQE -vqe = sqx.VQE(hamiltonian=my_hamiltonian, backend='pennylane') -optimizer = AdvancedOptimizer(vqe) - -best_params = optimizer.adaptive_optimization( - initial_params=np.random.random(vqe.num_parameters) -) -optimizer.plot_optimization_comparison() +adjacency = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]], dtype=float) +cut = sqx.QAOA(backend='simulator', p=2, seed=0).solve(adjacency) + +# MaxCut as an Ising energy: sum over edges of (Z_i Z_j - 1) / 2 +terms = {} +for i in range(3): + for j in range(i + 1, 3): + if adjacency[i, j]: + label = ''.join('Z' if q in (i, j) else 'I' for q in range(3)) + terms[label] = terms.get(label, 0) + 0.5 * adjacency[i, j] + terms['III'] = terms.get('III', 0) - 0.5 * adjacency[i, j] +H = sqx.Hamiltonian.from_dict(terms) + +print("QAOA cut:", cut['cut_value'], "| -ground energy:", -H.ground_state_energy()) ``` -### Error Mitigation +## 📊 Algorithm Performance Analysis + +Use `compare_to_classical` to compare a quantum classifier against tuned classical baselines on the same cross-validation folds. See [Benchmarking](benchmarking.md) for the full guide. ```python -# Error mitigation techniques for NISQ algorithms -class ErrorMitigatedAlgorithm: - """Wrapper to add error mitigation to quantum algorithms.""" - - def __init__(self, base_algorithm, mitigation_methods=None): - self.base_algorithm = base_algorithm - if mitigation_methods is None: - mitigation_methods = ['zero_noise_extrapolation', 'readout_correction'] - self.mitigation_methods = mitigation_methods - - def run_with_mitigation(self, circuit, shots=1000): - """Run circuit with error mitigation.""" - - results = {} - - # Raw result (no mitigation) - raw_result = self.base_algorithm.backend.run(circuit, shots=shots) - results['raw'] = raw_result.get_counts() - - # Apply mitigation methods - for method in self.mitigation_methods: - try: - if method == 'zero_noise_extrapolation': - mitigated_result = self.zero_noise_extrapolation(circuit, shots) - elif method == 'readout_correction': - mitigated_result = self.readout_correction(circuit, shots) - - results[method] = mitigated_result - - except Exception as e: - print(f"Mitigation method {method} failed: {e}") - - return results - - def zero_noise_extrapolation(self, circuit, shots): - """Zero-noise extrapolation error mitigation.""" - - noise_factors = [1, 2, 3] # Noise amplification factors - results = [] - - for factor in noise_factors: - # Amplify noise by repeating gates - noisy_circuit = self.amplify_noise(circuit, factor) - result = self.base_algorithm.backend.run(noisy_circuit, shots=shots) - results.append(result.get_counts()) - - # Extrapolate to zero noise - extrapolated_result = self.extrapolate_to_zero_noise(results, noise_factors) - return extrapolated_result - - def readout_correction(self, circuit, shots): - """Readout error correction.""" - - # Calibrate readout errors - calibration_matrix = self.calibrate_readout_errors() - - # Run original circuit - raw_result = self.base_algorithm.backend.run(circuit, shots=shots) - raw_counts = raw_result.get_counts() - - # Apply correction - corrected_counts = self.apply_readout_correction( - raw_counts, - calibration_matrix - ) - - return corrected_counts - -# Example usage -base_vqe = sqx.VQE(hamiltonian=my_hamiltonian, backend='qiskit') -mitigated_vqe = ErrorMitigatedAlgorithm(base_vqe) - -# Run with error mitigation -results = mitigated_vqe.run_with_mitigation(vqe_circuit) -print("Results with error mitigation:", results) +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=60, noise=0.15, random_state=0) +comparison = sqx.compare_to_classical(X, y, sqx.QuantumSVM(backend='simulator'), cv=3, seed=0) +print(comparison.table()) +print(comparison.verdict) ``` ## 📚 Algorithm Selection Guide -### Decision Tree - ```python -def recommend_algorithm(problem_type, problem_size, available_backends, objectives): - """Recommend best algorithm based on problem characteristics.""" - - recommendations = [] - - if problem_type == 'classification': - if problem_size < 1000: - recommendations.append(('QuantumSVM', 'pennylane', 'Good for small datasets')) - else: - recommendations.append(('VariationalQuantumClassifier', 'pennylane', 'Scalable approach')) - - elif problem_type == 'optimization': - if problem_size < 50: - recommendations.append(('QAOA', 'qiskit', 'Combinatorial optimization')) - else: - recommendations.append(('QuantumAnnealing', 'ocean', 'Large-scale problems')) - - elif problem_type == 'simulation': - if 'quantum_system' in objectives: - recommendations.append(('VQE', 'pennylane', 'Ground state finding')) - if 'dynamics' in objectives: - recommendations.append(('QuantumSimulator', 'cirq', 'Time evolution')) - - elif problem_type == 'search': - if problem_size <= 2**16: - recommendations.append(('GroversAlgorithm', 'simulator', 'Unstructured search')) - else: - recommendations.append(('QuantumWalk', 'cirq', 'Large search spaces')) - - # Filter by available backends - filtered_recommendations = [ - (algo, backend, desc) for algo, backend, desc in recommendations - if backend in available_backends - ] - - return filtered_recommendations - -# Example usage -available_backends = sqx.list_available_backends() -recommendations = recommend_algorithm( - problem_type='optimization', - problem_size=20, - available_backends=available_backends, - objectives=['combinatorial'] -) - -print("🎯 Algorithm Recommendations:") -for algo, backend, description in recommendations: - print(f" {algo} on {backend}: {description}") +def recommend_algorithm(problem_type): + """Map a problem type to the 0.3.0 class to start with.""" + return { + 'classification': 'QuantumSVM (kernel) or QuantumNN (variational)', + 'clustering': 'QuantumKMeans', + 'dimensionality_reduction': 'QuantumPCA', + 'combinatorial_optimization': 'QAOA, or OceanBackend.solve_qubo on annealers', + 'ground_state': 'VQE', + 'portfolio': 'QuantumPortfolioAgent', + }.get(problem_type, 'not covered in 0.3.0') + + +available = [name for name, info in sqx.list_available_backends().items() if info['available']] +print("Available backends:", available) +for problem in ['classification', 'combinatorial_optimization', 'ground_state', 'search']: + print(f"{problem}: {recommend_algorithm(problem)}") ``` ## 📞 Getting Help -For algorithm-specific help: - -- **[Tutorials](../tutorials/quantum-ml.md)**: Step-by-step algorithm tutorials -- **[API Reference](../api/algorithms.md)**: Detailed function documentation -- **[Examples](../showcase.md)**: Real-world algorithm applications -- **[GitHub Issues](https://github.com/SuperagenticAI/superquantx/issues)**: Report algorithm bugs - ---- - -!!! tip "Algorithm Selection" - Start with fundamental algorithms to understand quantum computing principles, then move to specialized ML or optimization algorithms based on your research needs. - -!!! warning "NISQ Limitations" - Current quantum hardware has limitations (noise, limited qubits, short coherence times). Consider these when selecting algorithms for real hardware execution. +- **[Tutorials](../tutorials/quantum-ml.md)**: step-by-step algorithm tutorials +- **[API Reference](../api/algorithms.md)**: class and method reference +- **[Showcase](../showcase.md)**: a full benchmark run with its output +- **[GitHub Issues](https://github.com/SuperagenticAI/superquantx/issues)**: report bugs -!!! info "Performance Optimization" - For best performance, choose backends that are optimized for your specific algorithm type (e.g., PennyLane for ML, Qiskit for IBM hardware access). \ No newline at end of file +!!! warning "NISQ limitations" + Current quantum hardware is noisy and small. Every result on this page comes from noiseless simulation; expect lower accuracy on hardware. diff --git a/docs/user-guide/overview.md b/docs/user-guide/overview.md index 8b9d850..6639ce4 100644 --- a/docs/user-guide/overview.md +++ b/docs/user-guide/overview.md @@ -1,9 +1,5 @@ # 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 an **experimental quantum AI research toolkit** 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 @@ -52,13 +48,15 @@ circuit_cirq.append(cirq.H(qubit)) # With SuperQuantX: One API for everything import superquantx as sqx -# Same code works with any backend! +# Same code works with any gate-model backend for backend_name in ['pennylane', 'qiskit', 'cirq']: backend = sqx.get_backend(backend_name) circuit = backend.create_circuit(2) - circuit.h(0) # Same interface everywhere - result = backend.run(circuit, shots=1000) - print(f"{backend_name}: {result.get_counts()}") + circuit = backend.add_gate(circuit, 'H', 0) # same gate names everywhere + circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) + circuit = backend.add_measurement(circuit) + result = backend.execute_circuit(circuit, shots=1000) + print(f"{backend_name}: {result['counts']}") ``` ## 🧠 Core Concepts @@ -70,20 +68,21 @@ SuperQuantX provides a common interface over different quantum computing framewo ```python import superquantx as sqx -# All backends follow the same interface -backend = sqx.get_backend('pennylane') # or 'qiskit', 'cirq', etc. +# All gate-model backends follow the same interface +backend = sqx.get_backend('pennylane') # or 'qiskit', 'cirq', 'braket', 'tket', 'simulator' # Create circuit -circuit = backend.create_circuit(num_qubits=3) +circuit = backend.create_circuit(3) -# Add gates (same syntax across all backends) -circuit.h(0) # Hadamard gate -circuit.cx(0, 1) # CNOT gate -circuit.ry(0.5, 2) # Y-rotation gate +# Add gates (same names across all backends) +circuit = backend.add_gate(circuit, 'H', 0) # Hadamard +circuit = backend.add_gate(circuit, 'CNOT', [0, 1]) # CNOT +circuit = backend.add_gate(circuit, 'RY', 2, [0.5]) # Y rotation # Execute circuit -result = backend.run(circuit, shots=1000) -counts = result.get_counts() +circuit = backend.add_measurement(circuit) +result = backend.execute_circuit(circuit, shots=1000) +counts = result['counts'] ``` ### 2. Quantum-Agentic Systems @@ -91,22 +90,28 @@ counts = result.get_counts() SuperQuantX is designed for research in **quantum-agentic systems** - AI agents that leverage quantum computation: ```python +import numpy as np import superquantx as sqx -# Example: Quantum-enhanced reinforcement learning agent + +# Example: a quantum neural network as the policy of a simple agent class QuantumAgent: def __init__(self, backend='pennylane'): - self.backend = sqx.get_backend(backend) - self.quantum_nn = sqx.QuantumNeuralNetwork( - n_qubits=4, - n_layers=3, - backend=self.backend - ) - + self.policy = sqx.QuantumNN(backend=backend, n_layers=2, max_epochs=10, seed=0) + + def learn(self, states, good_actions): + self.policy.fit(states, good_actions) + return self + def decide_action(self, state): - # Process state through quantum neural network - q_output = self.quantum_nn.forward(state) - return self.classical_decision_layer(q_output) + return int(self.policy.predict(np.atleast_2d(state))[0]) + + +rng = np.random.default_rng(0) +states = rng.uniform(-1, 1, size=(30, 2)) +actions = (states[:, 0] > 0).astype(int) # move right when x > 0 +agent = QuantumAgent().learn(states, actions) +print(agent.decide_action([0.8, 0.1])) ``` ### 3. Research-First Design @@ -123,15 +128,18 @@ Every feature in SuperQuantX is designed with research needs in mind: ### Unified Quantum Framework API ```python +from sklearn.datasets import make_moons +from sklearn.model_selection import train_test_split + +X, y = make_moons(n_samples=40, noise=0.1, random_state=0) +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) + # Switch backends without changing your code -backends = ['simulator', 'pennylane', 'qiskit', 'cirq'] results = {} - -for backend_name in backends: - backend = sqx.get_backend(backend_name) - qsvm = sqx.QuantumSVM(backend=backend) - accuracy = qsvm.fit_and_score(X_train, y_train, X_test, y_test) - results[backend_name] = accuracy +for backend_name in ['simulator', 'pennylane', 'qiskit', 'cirq']: + qsvm = sqx.QuantumSVM(backend=backend_name, feature_map='ZFeatureMap') + qsvm.fit(X_train, y_train) + results[backend_name] = float(np.mean(qsvm.predict(X_test) == y_test)) print(f"Backend comparison: {results}") ``` @@ -141,19 +149,24 @@ print(f"Backend comparison: {results}") Ready-to-use quantum ML algorithms: ```python +from superquantx.datasets import load_iris_quantum + +X_train, X_test, y_train, y_test, _ = load_iris_quantum(n_features=2, encoding='angle') + # Quantum Support Vector Machine qsvm = sqx.QuantumSVM(backend='pennylane', feature_map='ZZFeatureMap') qsvm.fit(X_train, y_train) predictions = qsvm.predict(X_test) # Variational Quantum Eigensolver -vqe = sqx.VQE(hamiltonian=H, backend='qiskit') +H = sqx.Hamiltonian.from_dict({'ZZ': 1.0, 'XI': 0.5, 'IX': 0.5}) +vqe = sqx.VQE(hamiltonian=H, backend='qiskit', seed=0) ground_energy = vqe.find_ground_state() # Quantum Neural Network -qnn = sqx.QuantumNeuralNetwork(n_qubits=6, n_layers=4) -qnn.compile(optimizer='adam', loss='binary_crossentropy') -qnn.fit(X, y, epochs=100) +qnn = sqx.QuantumNN(backend='simulator', n_layers=2, learning_rate=0.1, max_epochs=10, seed=0) +qnn.fit(X_train[y_train < 2], y_train[y_train < 2]) +print(f"VQE energy {ground_energy:.4f} (exact {H.ground_state_energy():.4f})") ``` ### Advanced Circuit Building @@ -161,20 +174,20 @@ qnn.fit(X, y, epochs=100) Flexible circuit construction with optimization: ```python -# Build complex circuits +# Build a layered circuit with the shared gate names +backend = sqx.get_backend('qiskit') circuit = backend.create_circuit(4) -# Add parameterized layers -circuit.add_layer('ry_layer', [0.1, 0.2, 0.3, 0.4]) -circuit.add_entangling_layer('cnot', [(0,1), (2,3), (1,2)]) +for q, angle in enumerate([0.1, 0.2, 0.3, 0.4]): # RY layer + circuit = backend.add_gate(circuit, 'RY', q, [angle]) +for a, b in [(0, 1), (2, 3), (1, 2)]: # entangling layer + circuit = backend.add_gate(circuit, 'CNOT', [a, b]) -# Circuit optimization -optimized_circuit = circuit.optimize(level=2) +# Or use a library ansatz +ansatz = backend.create_ansatz('RealAmplitudes', 4, np.zeros(backend.ansatz_param_count('RealAmplitudes', 4, reps=1)), reps=1) -# Circuit analysis -depth = circuit.depth() -gate_count = circuit.gate_count() -print(f"Depth: {depth}, Gates: {gate_count}") +# Analysis with the native framework (here a qiskit.QuantumCircuit) +print(f"Depth: {circuit.depth()}, Gates: {circuit.size()}") ``` ### Comprehensive Visualization @@ -182,17 +195,28 @@ print(f"Depth: {depth}, Gates: {gate_count}") Built-in tools for understanding quantum systems: ```python -# Circuit visualization -circuit.draw() # ASCII diagram -circuit.draw('matplotlib') # Professional plots -circuit.draw_bloch_sphere() # Bloch sphere representation - -# Result visualization -result.plot_histogram() # Measurement histograms -result.plot_state_vector() # Quantum state visualization -result.plot_probability_distribution() # Probability distributions +# Circuit visualization: the backend-independent description draws as text +circuit = sqx.QuantumCircuit(2) +circuit.h(0) +circuit.cx(0, 1) +circuit.measure_all() +print(circuit.draw()) + +# Result visualization: plot counts with matplotlib +import matplotlib.pyplot as plt + +backend = sqx.get_backend('simulator') +native = backend.create_circuit(2) +native.h(0) +native.cx(0, 1) +native.measure_all() +counts = backend.run(native, shots=1000).get_counts() +plt.bar(list(counts), list(counts.values())) +plt.title("Bell state counts") ``` +Bloch-sphere plots and `result.plot_*` helpers are not available in 0.3.0. + ## 🔍 Architecture Overview ### Layered Design @@ -225,16 +249,13 @@ SuperQuantX follows a layered architecture: ### Backend Management ```python -# Backend registration and management -available_backends = sqx.list_available_backends() -print(f"Available: {available_backends}") - -# Backend capabilities -backend = sqx.get_backend('pennylane') -capabilities = backend.get_capabilities() -print(f"Max qubits: {capabilities.max_qubits}") -print(f"Supported gates: {capabilities.native_gates}") -print(f"Has noise model: {capabilities.has_noise}") +# Backend discovery and capabilities +available = sqx.list_available_backends() +print("Available:", [name for name, info in available.items() if info['available']]) + +backend = sqx.get_backend('qiskit') +print(backend.capabilities) # capability flags for this backend +print(backend.get_version_info()) # installed framework versions ``` ## 🎯 Use Cases @@ -243,34 +264,54 @@ print(f"Has noise model: {capabilities.has_noise}") ```python # Compare ML algorithms across quantum backends -algorithms = ['QuantumSVM', 'QuantumNeuralNetwork', 'VQC'] -backends = ['pennylane', 'qiskit', 'cirq'] +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=40, noise=0.1, random_state=0) +models = { + 'QuantumSVM': lambda b: sqx.QuantumSVM(backend=b, feature_map='ZFeatureMap'), + 'QuantumNN': lambda b: sqx.QuantumNN(backend=b, n_layers=2, max_epochs=10, seed=0), +} results_matrix = {} -for algo_name in algorithms: +for algo_name, make in models.items(): results_matrix[algo_name] = {} - for backend_name in backends: - algo = getattr(sqx, algo_name)(backend=backend_name) - accuracy = algo.fit_and_score(X, y) - results_matrix[algo_name][backend_name] = accuracy + for backend_name in ['simulator', 'pennylane']: + model = make(backend_name).fit(X, y) + results_matrix[algo_name][backend_name] = float(np.mean(model.predict(X) == y)) + +print(results_matrix) ``` ### 2. Quantum Algorithm Development ```python +import numpy as np + + # Implement and test new quantum algorithms class MyQuantumAlgorithm(sqx.BaseQuantumAlgorithm): - def __init__(self, backend='simulator'): - super().__init__(backend) - - def run(self, problem_instance): - circuit = self.create_ansatz(problem_instance) - result = self.backend.run(circuit) - return self.process_result(result) - - def create_ansatz(self, problem): - # Your quantum circuit construction logic - pass + """Learns a single RY angle so that P(1) matches a target probability.""" + + def fit(self, X, y=None, **kwargs): + target = float(np.mean(y)) + angles = np.linspace(0, np.pi, 50) + self.theta_ = min(angles, key=lambda t: abs(self._p1(t) - target)) + self.is_fitted = True + return self + + def predict(self, X, **kwargs): + return np.full(len(X), self._p1(self.theta_)) + + def _p1(self, theta): + circuit = self.backend.create_circuit(1) + self.backend.add_gate(circuit, 'RY', 0, [theta]) + self.backend.add_measurement(circuit) + counts = self.backend.execute_circuit(circuit, shots=500)['counts'] + return counts.get('1', 0) / 500 + + +algo = MyQuantumAlgorithm(backend='simulator', seed=0).fit(np.zeros((8, 1)), [1, 1, 0, 0, 0, 0, 0, 0]) +print(f"P(1) learned: {algo.predict([[0]])[0]:.2f} (target 0.25)") ``` ### 3. Educational Quantum Computing @@ -281,35 +322,51 @@ class QuantumLesson: def __init__(self, title): self.title = title self.backend = sqx.get_backend('simulator') - + def demonstrate_superposition(self): circuit = self.backend.create_circuit(1) - circuit.h(0) # Create superposition + circuit.h(0) # create superposition circuit.measure_all() - - result = self.backend.run(circuit, shots=1000) - counts = result.get_counts() - - self.visualize_results(counts, "Superposition") + + counts = self.backend.run(circuit, shots=1000).get_counts() + print(f"{self.title}: {counts} (about half 0, half 1)") return counts + + +QuantumLesson("Superposition").demonstrate_superposition() ``` ### 4. Hardware Benchmarking +!!! note "Requires credentials" + Hardware backends need provider accounts (IBM Quantum, AWS, Quantinuum). The loop below runs on the local backends; add a hardware backend name once its credentials are set up. + ```python -# Compare quantum hardware performance -def benchmark_hardware(): - hardware_backends = ['ibm_quantum', 'google_quantum', 'aws_braket'] - benchmark_circuits = create_benchmark_suite() - +import time + + +def ghz_circuit(backend, n): + circuit = backend.create_circuit(n) + backend.add_gate(circuit, 'H', 0) + for q in range(n - 1): + backend.add_gate(circuit, 'CNOT', [q, q + 1]) + backend.add_measurement(circuit) + return circuit + + +def benchmark_backends(names=('simulator', 'qiskit', 'cirq', 'pennylane'), n=3, shots=1000): + """Run the same GHZ circuit everywhere: time taken and fraction of ideal outcomes.""" results = {} - for hw_backend in hardware_backends: - results[hw_backend] = run_benchmark_suite( - benchmark_circuits, - backend=hw_backend - ) - - return analyze_benchmark_results(results) + for name in names: + backend = sqx.get_backend(name) + start = time.time() + counts = backend.execute_circuit(ghz_circuit(backend, n), shots=shots)['counts'] + ideal = counts.get('0' * n, 0) + counts.get('1' * n, 0) + results[name] = {'seconds': round(time.time() - start, 3), 'ideal_fraction': ideal / shots} + return results + + +print(benchmark_backends()) ``` ## 🛠️ Development Philosophy @@ -324,49 +381,38 @@ def benchmark_hardware(): ### Code Example: Research Workflow ```python +import numpy as np import superquantx as sqx -# Set up reproducible experiment -sqx.set_seed(42) -experiment = sqx.Experiment("quantum_svm_comparison") - -# Define experiment parameters -backends = ['simulator', 'pennylane', 'qiskit'] -datasets = ['iris', 'wine', 'breast_cancer'] -feature_maps = ['ZFeatureMap', 'ZZFeatureMap', 'PauliFeatureMap'] - -# Run systematic comparison -with experiment: - for backend_name in backends: - for dataset_name in datasets: - for feature_map in feature_maps: - # Load data - X, y = sqx.datasets.load(dataset_name) - - # Create and train model - qsvm = sqx.QuantumSVM( - backend=backend_name, - feature_map=feature_map - ) - - # Cross-validation - scores = sqx.cross_val_score(qsvm, X, y, cv=5) - - # Log results - experiment.log_result({ - 'backend': backend_name, - 'dataset': dataset_name, - 'feature_map': feature_map, - 'mean_accuracy': scores.mean(), - 'std_accuracy': scores.std() - }) - -# Analyze results -results_df = experiment.get_results_dataframe() -best_config = experiment.get_best_configuration() -experiment.plot_comparison() +# Reproducible comparison: fixed dataset splits (random_state) and seeds +datasets = { + 'iris': sqx.datasets.load_iris_quantum, + 'wine': sqx.datasets.load_wine_quantum, +} +feature_maps = ['ZFeatureMap', 'ZZFeatureMap'] + +results = [] +for dataset_name, loader in datasets.items(): + X_train, X_test, y_train, y_test, metadata = loader( + n_features=4, encoding='angle', random_state=42 + ) + for feature_map in feature_maps: + qsvm = sqx.QuantumSVM(backend='simulator', feature_map=feature_map, seed=42) + qsvm.fit(X_train, y_train) + results.append({ + 'dataset': dataset_name, + 'feature_map': feature_map, + 'accuracy': float(np.mean(qsvm.predict(X_test) == y_test)), + }) + +for row in results: + print(row) +best = max(results, key=lambda r: r['accuracy']) +print("Best configuration:", best) ``` +There is no `Experiment` tracker, `set_seed` or `cross_val_score` in 0.3.0; pass `seed=` to each algorithm and use your own logging (or `sqx.compare_to_classical` for cross-validated comparisons). + ## 🌟 What Makes SuperQuantX Different? ### Compared to Individual Frameworks diff --git a/scripts/check_docs_examples.py b/scripts/check_docs_examples.py new file mode 100644 index 0000000..ab8fb79 --- /dev/null +++ b/scripts/check_docs_examples.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +"""Run the Python code blocks in the docs against the installed SuperQuantX. + +Blocks on one page run in order in a shared namespace, the way a reader +follows the page. Put ```` on the line before a +fence to skip that block (for hardware snippets that need credentials, or +code that only illustrates a pattern). Every page runs in its own process. + +Pages that define pytest tests (``def test_...``) are also run through +pytest, so the test bodies are executed and not only defined. + +Usage: + python scripts/check_docs_examples.py [paths...] # default: docs/ and README.md + +Environment: + DOCS_CHECK_TIMEOUT seconds allowed per page (default 600) + DOCS_CHECK_SLOW report blocks slower than this many seconds (default 10) +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +FENCE = re.compile(r"^(?P[ \t]*)```python[^\n]*\n(?P.*?)^(?P=indent)```", re.S | re.M) +SKIP = "" +TIMEOUT = int(os.environ.get("DOCS_CHECK_TIMEOUT", "600")) +SLOW = float(os.environ.get("DOCS_CHECK_SLOW", "10")) + +RUNNER = r''' +import json, os, sys, time, warnings +os.environ.setdefault("MPLBACKEND", "Agg") +warnings.filterwarnings("ignore") +blocks = json.loads(sys.stdin.read()) +ns = {"__name__": "__main__"} +real_stdout = sys.stdout +sys.stdout = open(os.devnull, "w") +for line, code in blocks: + t0 = time.time() + real_stdout.write(f"@@START {line}\n"); real_stdout.flush() + try: + exec(compile(code, f"block@{line}", "exec"), ns) + err = None + except BaseException as e: + err = f"{type(e).__name__}: {e}"[:300] + real_stdout.write("@@RES " + json.dumps([line, err, round(time.time() - t0, 1)]) + "\n") + real_stdout.flush() +''' + + +def blocks_for(path: Path): + text = path.read_text() + out, skipped = [], 0 + for m in FENCE.finditer(text): + line = text.count("\n", 0, m.start()) + 1 + before = text[: m.start()].rstrip().splitlines() + if before and before[-1].strip() == SKIP: + skipped += 1 + continue + indent = m.group("indent") + body = "\n".join(l[len(indent):] if l.startswith(indent) else l for l in m.group("body").splitlines()) + out.append((line, body)) + return out, skipped + + +def run_pytest(rel: Path, blocks) -> tuple[int, int]: + """Run a page's blocks as one pytest module. Returns (tests run, failures).""" + try: + import pytest # noqa: F401 + except ImportError: + print(f"NOTE {rel}: pytest not installed, test bodies not executed") + return 0, 0 + with tempfile.TemporaryDirectory() as tmp: + mod = Path(tmp) / f"test_docs_{rel.stem.replace('-', '_')}.py" + mod.write_text("\n\n".join(code for _, code in blocks)) + try: + p = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(mod)], + capture_output=True, text=True, timeout=TIMEOUT, cwd=ROOT) + except subprocess.TimeoutExpired: + print(f"FAIL {rel} pytest timed out") + return 0, 1 + fails = [l.split("::", 1)[1] for l in p.stdout.splitlines() if l.startswith(("FAILED", "ERROR")) and "::" in l] + for name in fails: + print(f"FAIL {rel} test {name}") + m = re.search(r"(\d+) passed", p.stdout) + passed = int(m.group(1)) if m else 0 + if p.returncode not in (0, 5) and not fails: + print(f"FAIL {rel} pytest exited {p.returncode}") + return passed, 1 + return passed + len(fails), len(fails) + + +def main(argv): + targets = [Path(a).resolve() for a in argv] or [ROOT / "docs", ROOT / "README.md"] + files = [] + for t in targets: + files += sorted(t.rglob("*.md")) if t.is_dir() else [t] + ran = failed = skipped = tests = 0 + for f in files: + blocks, sk = blocks_for(f) + skipped += sk + if not blocks: + continue + rel = f.relative_to(ROOT) + try: + p = subprocess.run([sys.executable, "-c", RUNNER], input=json.dumps(blocks), + capture_output=True, text=True, timeout=TIMEOUT, cwd=ROOT) + out, crashed = p.stdout, p.returncode != 0 + except subprocess.TimeoutExpired as e: + out = e.stdout.decode() if isinstance(e.stdout, bytes) else (e.stdout or "") + crashed = True + done = [json.loads(l[6:]) for l in out.splitlines() if l.startswith("@@RES ")] + for line, err, secs in done: + ran += 1 + if err: + failed += 1 + print(f"FAIL {rel}:{line} {err}") + elif secs > SLOW: + print(f"SLOW {rel}:{line} {secs}s") + if crashed and len(done) < len(blocks): + starts = re.findall(r"@@START (\d+)", out) + ran += 1 + failed += 1 + print(f"FAIL {rel}:{starts[-1] if starts else '?'} timed out or crashed") + if any("def test_" in code for _, code in blocks): + f_tests, f_fail = run_pytest(rel, blocks) + tests += f_tests + failed += f_fail + print(f"\n{tests} doc tests run under pytest") + print(f"{ran} blocks run, {failed} failed, {skipped} skipped") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))