Advanced coding rules for building, testing, and operating quantum-computing workloads in Python with Qiskit, Cirq, and PennyLane.
Transform your quantum computing research with production-ready Python tooling that eliminates SDK friction and accelerates real hardware validation.
You're building the future of computing, but your development workflow is stuck in the past. Sound familiar?
Every quantum developer knows this pain. You're not just writing algorithms—you're wrestling with immature toolchains, inconsistent APIs, and the fundamental challenge of debugging probabilistic systems.
These Cursor Rules transform your Python quantum development into a streamlined, hardware-validated workflow. Built specifically for researchers and engineers working with real quantum systems, not toy problems.
What This Does:
Example Impact:
# Before: Manual hardware validation, prone to runtime failures
circuit = QuantumCircuit(5)
# ... build circuit
backend = provider.get_backend('ibm_nighthawk')
job = backend.run(circuit) # Hope it works
# After: Automated validation with comprehensive error context
@quantum_algorithm(max_depth=50, validate_hardware=True)
def build_vqe_circuit(params: VQEParams) -> QuantumCircuit:
# Circuit construction with built-in validation
circuit = create_ansatz(params.num_qubits, params.layers)
return optimize_for_hardware(circuit, target_backend='ibm_nighthawk')
Stop discovering device limitations at runtime. Every algorithm validates against real hardware constraints during development:
# Automatic qubit capacity validation
@validate_backend_compatibility
def create_quantum_classifier(num_features: int) -> QuantumCircuit:
if num_features > get_backend_capacity('rigetti_aspen'):
raise QuantumResourceError(f"Feature count {num_features} exceeds device limit")
Transform cryptic quantum failures into actionable debugging information:
# Rich error context for quantum operations
try:
result = execute_quantum_algorithm(circuit, shots=1000)
except QuantumExecutionError as e:
# Get: backend name, job ID, circuit depth, transpilation logs
logger.error(f"Quantum execution failed on {e.backend_name}: {e.debug_context}")
Seamless integration between quantum circuits and classical ML without SDK-specific boilerplate:
# Unified interface across all quantum SDKs
@qml.qnode(device="qiskit.ibm", interface="torch")
def quantum_layer(inputs, weights):
# PennyLane syntax works with Qiskit hardware
encode_features(inputs)
return qml.expval(qml.PauliZ(0))
Test quantum algorithms with the same rigor as classical systems:
@pytest.mark.hardware
@pytest.mark.parametrize("backend", ["ibm_nighthawk", "google_willow"])
def test_vqe_convergence(backend, random_seed):
"""Validate VQE convergence across real hardware with statistical significance"""
results = run_quantum_experiment(vqe_circuit, backend=backend, shots=5000)
assert convergence_test(results, confidence=0.95)
Before: Spend 2 hours debugging why your algorithm works in simulation but fails on hardware
After: Run pytest tests/hardware/ and get immediate feedback on device compatibility
Before: Write → Simulate → Submit to hardware queue → Wait → Debug → Repeat After: Write → Auto-validate → Parallel hardware testing → Comprehensive error reports
Before: Rewrite algorithms for each quantum SDK with platform-specific optimizations After: Write once, deploy everywhere with automatic transpilation and optimization
# Single algorithm definition works across all platforms
@quantum_algorithm
def create_qaoa_circuit(graph: nx.Graph, gamma: float, beta: float) -> QuantumCircuit:
"""QAOA circuit that auto-optimizes for target backend"""
return build_qaoa_ansatz(graph, gamma, beta)
# Deploy to any backend
results = {
'ibm': execute_on_backend(qaoa_circuit, 'ibm_nighthawk'),
'google': execute_on_backend(qaoa_circuit, 'google_willow'),
'ionq': execute_on_backend(qaoa_circuit, 'ionq_aria')
}
# Set up your quantum development environment
pip install qiskit>=0.45 cirq>=1.2 pennylane>=0.33 pytket>=1.28
pip install torch jax numpy pytest-xdist mypy
.cursorrules file.env:QISKIT_IBM_TOKEN=your_token_here
BRAKET_AWS_ACCESS_KEY=your_key_here
# Test file: tests/test_quantum_setup.py
@pytest.mark.hardware
def test_hardware_connectivity():
"""Verify connection to all configured quantum backends"""
backends = ['ibm_nighthawk', 'google_willow', 'ionq_aria']
for backend in backends:
assert can_connect_to_backend(backend)
# algorithms/vqe_optimizer.py
@quantum_algorithm(validate_hardware=True, max_depth=100)
def build_molecular_vqe(molecule: MolecularData) -> QuantumCircuit:
"""VQE circuit for molecular ground state calculation"""
circuit = create_ucc_ansatz(molecule)
return optimize_for_target_backend(circuit)
# Automatic hardware validation and optimization
vqe_circuit = build_molecular_vqe(h2_molecule)
result = execute_on_hardware(vqe_circuit, backend='ibm_nighthawk')
# Example: Production quantum optimization service
@dataclass
class QuantumOptimizationResult:
optimal_params: np.ndarray
final_energy: float
convergence_data: List[float]
hardware_metadata: Dict[str, Any]
def run_production_vqe(molecule: str) -> QuantumOptimizationResult:
"""Production-ready VQE with comprehensive error handling and logging"""
with quantum_execution_context(audit_log=True, error_mitigation=True):
return execute_vqe_optimization(molecule)
Your quantum algorithms will run reliably in production, with the same development experience as mature classical frameworks. No more SDK wrestling, no more hardware surprises, no more debugging quantum systems in the dark.
Start building the quantum future with tools that actually work.
You are an expert in Quantum Computing with Python 3.11+, Qiskit, Cirq, PennyLane, Pytket, Amazon Braket, and supporting ML libraries (PyTorch, JAX, NumPy).
Technology Stack Declaration
- Primary language: Python with strict type-hints (PEP 484) and pytest for testing.
- Quantum SDKs: Qiskit ≥0.45, Cirq ≥1.2, PennyLane ≥0.33, Pytket ≥1.28.
- Hardware back-ends: IBM Nighthawk, Google Willow, IonQ, Rigetti, OQC via Amazon Braket.
- Classical accelerators: CUDA GPUs for tensor-network simulation, AWS Fargate/Kubernetes for scalable hybrid workflows.
Key Principles
- Hands-on validation on real hardware: every algorithm must be exercised on at least one NISQ device in CI.
- Hybrid first: decompose problems into classical pre/post-processing + quantum core; use PennyLane “qml.qnode” or Qiskit Runtime primitives.
- Error-tolerant design: logical qubits, surface/geometric codes, and active decoding are mandatory for circuits >50 depth.
- Determinism: set explicit random_seeds for transpilation, sampling and ML initialisation.
- Modularity: keep circuit generators pure and stateless; pass parameters explicitly.
- Reproducible artefacts: pin SDK versions in requirements.txt and freeze transpiler passes.
Python
- Follow PEP 8 + isort; line length 100.
- Enable mypy with “--strict”; prohibit “Any”.
- Use dataclasses for immutable configs; pydantic only for user-facing schemas.
- Use snake_case for functions, SCREAMING_SNAKE_CASE for constants, CamelCase for class-level abstractions (e.g., Optimizer).
- Group files:
├─ qc_algorithms/ # circuit factories
├─ decoders/ # ML or BP decoders
├─ runners/ # execution orchestration
├─ tests/ # pytest suites
└─ notebooks/ # exploratory work, never imported by src code
- Prefer list comprehensions and functional tools (map, filter) over imperative loops for circuit construction.
- Never suppress warnings from SDKs; upgrade or document.
Error Handling and Validation
- Validate qubit count vs back-end capacity before transpilation; raise ValueError early.
- Wrap provider exceptions with custom QuantumExecutionError carrying back-end name, job_id, and log_url.
- For ML-based decoders, use try/except around torch inference; fall back to classical decoder on GPU OOM.
- Assert circuit.depth() < MAX_DEPTH in CI gatesize checks; fail pipeline if exceeded.
- Store job metadata (shots, layout, seed, noise_model) in a JSON Lines audit log.
Qiskit
- Build circuits with QuantumCircuit builder functions; never hard-code QASM strings.
- Always transpile with optimization_level=3 then run pass_manager=generate_error_mitigation.
- Use Qiskit Runtime primitives (Sampler, Estimator) for production; set resilience_level=2 for error suppression.
- Register back-end via qiskit_ibm_provider; disable auto-layout to preserve logical mapping.
- Use qiskit-nature for chemistry, qiskit-finance for portfolio optimisation; pin these extras separately.
Cirq
- Annotate qubits with meaningful names (e.g., cirq.NamedQubit("q_data_0")); avoid GridQubit unless hardware-specific.
- Use cirq.optimize_for_target_gateset after circuit construction; set csp_routing=True for Google devices.
- Prefer cirq.StabilizerStateChForm for fast Clifford simulation during unit tests.
- Capture calibration metrics via cirq.google.eng.process_characterization; persist to ./artifacts/calibrations/.
PennyLane
- Decorate quantum functions with @qml.qnode(device) and enable diff_method="parameter-shift".
- For hybrid loops, wrap classical optimiser (e.g., optax.adam) in pl-qml workflows; batch shot-frugal execution.
- Activate qml.transforms.merge_rotations and qml.transforms.cancel_inverses by default.
- Prefer JAX interface for gradient-heavy models; seed jax.random.PRNGKey(42).
Additional Sections
Testing
- Use pytest-xdist for parallel simulation; mark "@pytest.mark.hardware" to segregate costly live runs.
- Provide golden JSON snapshots of expected statevectors; compare with np.allclose(tol=1e-5).
- Achieve >90 % branch coverage; circuit factories must be exercised with random parameter sweeps.
Performance
- Cache transpiled circuits keyed by (circuit.hash(), backend.name, coupling_map_id).
- Leverage qiskit-aer GPU simulator for >20-qubit Monte-Carlo; fall back to quimb tensor network if memory >16 GB.
- Apply noise-adaptive transpiler passes when device T1 < 100 µs: swap_noise_adaptive=True.
Security & Compliance
- Never log raw calibration data or credentials; use dotenv and AWS Secrets Manager.
- Encrypt all job artefacts at rest (AES-256) and in transit (TLS 1.3).
- Conform to ITAR when exporting circuits containing >1000 logical qubits.
Documentation
- Generate API docs with pdoc3; host via GitHub Pages.
- Each public function requires a doctest showing creation, transpilation, and execution.
Continuous Integration
- GitHub Actions: matrix {python-version: [3.11, 3.12-dev], sdk: [qiskit, cirq, pennylane]}, run "simulate-and-smoke" workflow.
- Fail build on any TODO or FIXME in committed lines.
Release & Versioning
- Semantic Versioning: MAJOR incompatible circuits, MINOR algorithm additions, PATCH noise-model tweaks.
- Publish docker images ghcr.io/org/quantum-lab:<tag> containing pinned SDKs and sample notebooks.