Skip to content

Getting Started with pyqpanda3 ​

This tutorial walks you through installing pyqpanda3, verifying your setup, and writing your first quantum program. By the end, you will have a working development environment and a solid understanding of how the SDK is organized.


Table of Contents ​


What is pyqpanda3? ​

pyqpanda3 is the Python SDK for QPanda3, OriginQ's high-performance quantum computing framework. It provides a comprehensive set of tools for constructing quantum circuits, running simulations on CPU or GPU, modeling noise, optimizing variational quantum circuits, and connecting to real quantum hardware through OriginQ's cloud service.

The SDK is designed around three core principles:

  1. Expressiveness -- Build quantum programs using an intuitive QProg API with the << operator for circuit composition.
  2. Performance -- Under the hood, pyqpanda3 wraps a C++ engine that handles statevector simulation, density matrix evolution, and circuit optimization at native speed.
  3. Completeness -- From basic gate operations to variational algorithms, transpilation, and cloud execution, the entire quantum computing workflow is covered in a single package.

What Can You Do with pyqpanda3? ​

CapabilityDescription
Quantum circuit construction37+ built-in gates, custom gates, dynamic circuits
SimulationCPU, GPU, density matrix, stabilizer, partial amplitude
Noise modeling7 error channels with per-gate, per-qubit configuration
Variational circuitsParameterized gates, automatic gradient computation
Quantum informationState vectors, density matrices, channel representations
TranspilationTopology-aware gate decomposition and optimization
VisualizationBloch sphere, circuit diagrams, probability plots
Cloud computingSubmit jobs to real quantum processors

System Requirements ​

Before installing pyqpanda3, make sure your system meets the following requirements.

Python Version ​

pyqpanda3 supports Python 3.10 through 3.14. You can check your current Python version with:

bash
python --version

The output should show a version in the range 3.10.x through 3.14.x:

Python 3.11.8

Required Dependencies ​

pyqpanda3 depends on the following Python packages, which are installed automatically:

PackageMinimum VersionPurpose
numpy>= 1.20Numerical array operations
matplotlib>= 3.3Plotting and visualization
scipy>= 1.7Scientific computing
Cython>= 0.29C extension compilation
networkx>= 2.6Graph and network analysis
mypy>= 1.14.0Static type checking
setuptools>= 60.0Package build and distribution
graphviz>= 0.17Graph visualization

Operating System Support ​

OSSupport LevelAdditional Requirements
Linux (x86_64)Fully supportedGCC >= 8.5
macOS (ARM64)Fully supportedClang >= 15.0
Windows (x86_64)Fully supportedMicrosoft Visual C++ Redistributable x64 (2015-2022)

Hardware Notes ​

  • CPU simulation works on any modern processor.
  • GPU simulation (GPUQVM) requires an NVIDIA GPU with CUDA support and the CUDA toolkit installed. This is optional and not needed for most tutorials.

Installation ​

You can install pyqpanda3 from PyPI.

Install from PyPI ​

The simplest way to install pyqpanda3 is using pip. This downloads a pre-built binary wheel, so no compilation is needed.

Install the latest stable release:

bash
pip install pyqpanda3

If you want to upgrade an existing installation to the latest version:

bash
pip install --upgrade pyqpanda3

To install a specific version:

bash
pip install pyqpanda3==0.5.1

We strongly recommend installing pyqpanda3 inside a virtual environment to avoid conflicts with other Python packages.

Create and activate a virtual environment, then install pyqpanda3:

bash
python -m venv qpanda3-env
source qpanda3-env/bin/activate
pip install pyqpanda3

On Windows, the activation command differs slightly:

bat
python -m venv qpanda3-env
qpanda3-env\Scripts\activate
pip install pyqpanda3

Installation Troubleshooting ​

ImportError: No module named 'pyqpanda3' ​

This error means pyqpanda3 is not installed in the active Python environment. Verify you are using the correct environment:

bash
# Check which Python is being used
which python

# Reinstall pyqpanda3
pip install pyqpanda3

If you are using a virtual environment, make sure it is activated:

bash
source qpanda3-env/bin/activate  # Linux/macOS
qpanda3-env\Scripts\activate     # Windows

ImportError: libstdc++.so.6: version not found ​

This occurs on older Linux systems where the C++ standard library is outdated. Update your compiler toolchain or install a newer libstdc++:

bash
# Ubuntu/Debian
sudo apt-get install libstdc++6

# Check the current version
strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBCXX | tail -5

Missing libidn2 (macOS) ​

If you see symbol errors related to pyqpanda3:

bash
# Install the library
brew reinstall libidn2

# Reinstall pyqpanda3
pip install --force-reinstall pyqpanda3

pip install fails with wheel error ​

Pre-built wheels may not be available for all platform and Python version combinations. If pip install fails, contact qcloud@originqc.com for installation support.


Verifying Your Installation ​

After installing pyqpanda3, run the following quick check to confirm everything is working correctly.

Import pyqpanda3 and print the version to verify the package can be imported correctly:

python
import pyqpanda3
print(pyqpanda3.__version__)

运行结果:

0.5.1

You should see the installed version number printed, for example:

0.5.1

Next, verify that the core module loads and a simulator can be instantiated:

python
from pyqpanda3 import core

machine = core.CPUQVM()
print("CPUQVM created successfully")

运行结果:

CPUQVM created successfully

Expected output:

CPUQVM created successfully

Finally, run a minimal single-qubit circuit to confirm end-to-end functionality:

python
from pyqpanda3 import core

prog = core.QProg()
prog << core.H(0)
prog << core.measure([0], [0])

machine = core.CPUQVM()
machine.run(prog, shots=1000)

counts = machine.result().get_counts()
print(counts)

运行结果:

{'1': 492, '0': 508}

You should see measurement counts roughly split between 0 and 1:

{'0': 503, '1': 497}

If all three checks pass, your installation is ready for quantum programming.


Your First Quantum Program: Bell State ​

Now that pyqpanda3 is installed and verified, let us write a complete quantum program. The Bell state (also known as an EPR pair) is one of the simplest and most important examples in quantum computing. It demonstrates two fundamental quantum phenomena: superposition and entanglement.

What is a Bell State? ​

A Bell state is a maximally entangled two-qubit state. The most common one, |Φ+⟩, is defined as:

|Φ+⟩=12(|00⟩+|11⟩)

This state has a remarkable property: when you measure both qubits, they always produce the same result. You get 00 roughly half the time and 11 roughly half the time, but never 01 or 10. This correlation holds regardless of the physical distance between the qubits, which is the basis for quantum teleportation and quantum key distribution.

Step 1: Create a Quantum Program ​

A QProg (quantum program) is the top-level container for quantum operations in pyqpanda3. Think of it as a blank canvas where you add gates and measurements.

Create an empty quantum program:

python
from pyqpanda3 import core

prog = core.QProg()

At this point, prog is an empty program with no operations. We will add gates to it in the following steps.

Step 2: Apply a Hadamard Gate ​

The Hadamard gate (H) is a single-qubit gate that creates a uniform superposition. When applied to the basis state |0⟩, it produces:

H|0⟩=12(|0⟩+|1⟩)

This means qubit 0 is now in a state where measuring it would give 0 with probability 12 and 1 with probability 12.

Apply the Hadamard gate to qubit 0:

python
prog << core.H(0)

The << operator appends a gate to the program. core.H(0) creates a Hadamard gate targeting qubit index 0.

Step 3: Apply a CNOT Gate ​

The CNOT (controlled-NOT) gate is a two-qubit gate. It flips the target qubit if and only if the control qubit is in the |1⟩ state. Its matrix representation is:

CNOT=(1000010000010010)

When the control qubit is in superposition, the CNOT gate creates entanglement. After the Hadamard on qubit 0, applying CNOT with control=0 and target=1 produces:

CNOT01⋅(H⊗I)⋅|00⟩=12(|00⟩+|11⟩)

This is exactly the Bell state |Φ+⟩.

Apply the CNOT gate with qubit 0 as control and qubit 1 as target:

python
prog << core.CNOT(0, 1)

Step 4: Add Measurement ​

Quantum measurement collapses the qubits into classical bits. In pyqpanda3, measure maps qubits to classical bits. The first argument is a list of qubit indices, and the second is a list of classical bit indices.

Measure both qubits and store the results in classical bits 0 and 1:

python
prog << core.measure([0, 1], [0, 1])

Step 5: Run on a Simulator ​

The CPUQVM is a statevector simulator that runs on the CPU. It simulates the quantum circuit by tracking the full 2n-dimensional state vector, where n is the number of qubits.

Create a simulator and run the program with 10,000 shots:

python
machine = core.CPUQVM()
machine.run(prog, shots=10000)

The shots parameter determines how many times the circuit is executed. Each shot simulates a full run including measurement collapse. More shots give you better statistical accuracy.

Step 6: Retrieve and Display Results ​

After running the program, retrieve the measurement counts:

python
counts = machine.result().get_counts()
print(counts)

运行结果:

{'11': 5002, '00': 4998}

Complete Program ​

Here is the complete Bell state program in one block. Each section is annotated with comments explaining its purpose:

python
# Import the core module which provides gates, simulators,
# and the QProg circuit builder
from pyqpanda3 import core

# Create an empty quantum program.
# QProg is the main container for quantum operations.
prog = core.QProg()

# Apply a Hadamard gate to qubit 0.
# This puts qubit 0 into an equal superposition of |0> and |1>.
prog << core.H(0)

# Apply a CNOT gate with qubit 0 as control and qubit 1 as target.
# This entangles the two qubits, creating the Bell state |Phi+>.
prog << core.CNOT(0, 1)

# Measure both qubits and store results in classical bits 0 and 1.
# Without measurement, the simulator cannot produce output counts.
prog << core.measure([0, 1], [0, 1])

# Create a CPU-based quantum virtual machine (simulator).
# CPUQVM performs exact statevector simulation.
machine = core.CPUQVM()

# Run the program 10,000 times.
# Each "shot" is a full execution of the circuit, including
# the probabilistic measurement collapse.
machine.run(prog, shots=10000)

# Retrieve the measurement counts as a dictionary.
# Keys are bitstrings (e.g., "00", "11") and values are counts.
counts = machine.result().get_counts()
print("Measurement counts:", counts)

运行结果:

Measurement counts: {'11': 4993, '00': 5007}

When you run this program, you will see output similar to:

Measurement counts: {'00': 4973, '11': 5027}

The exact numbers vary slightly each time due to the inherent randomness of quantum measurement, but the distribution should be close to 50/50 between 00 and 11.

pyqpanda3 can display a text representation of your circuit using print():

python
print(prog)

运行结果:

          ┌─┐         ┌─┐     
q_0:  |0>─┤H├ ───*── ─┤M├──── 
          └─┘ ┌──┴─┐  └╥┘ ┌─┐ 
q_1:  |0>──── ┤CNOT├ ──╫──┤M├ 
              └────┘   ║  └╥┘ 
 c :   / ══════════════╩═══╩═
                        0   1

This produces a text circuit diagram showing the gate sequence:

          ┌─┐         ┌─┐
q_0:  |0>─┤H├ ───*── ─┤M├────
          └─┘ ┌──┴─┐  └╥┘ ┌─┐
q_1:  |0>──── ┤CNOT├ ──╫──┤M├
              └────┘   ║  └╥┘
 c :   / ══════════════╩═══╩═
                        0   1

In this diagram:

  • H represents the Hadamard gate on qubit 0
  • * is the control of the CNOT gate (on qubit 0)
  • X is the target of the CNOT gate (on qubit 1)
  • M marks measurement operations on both qubits

Understanding the Output ​

Let us analyze the Bell state results in more detail.

Statistical Distribution ​

When you run the Bell state program, you should observe two things:

  1. Only 00 and 11 appear -- the outcomes 01 and 10 are never observed.
  2. The counts are roughly equal -- each outcome appears approximately shots / 2 times.

This is a direct consequence of the Bell state:

P(00)=|⟨00|Φ+⟩|2=12P(11)=|⟨11|Φ+⟩|2=12P(01)=P(10)=0

Expected vs. Observed Counts ​

With 10,000 shots, the expected counts are:

OutcomeExpected CountObserved (example)
005,0004,973
115,0005,027
0100
1000

The small deviation from exactly 5,000/5,000 is due to statistical sampling. The law of large numbers ensures that as you increase the number of shots, the observed frequencies converge to the true probabilities:

limN→∞n00N=12

Visualizing the Distribution ​

You can compute and display the probability distribution from the raw counts:

python
# Calculate probabilities from counts
total = sum(counts.values())
probabilities = {state: count / total for state, count in counts.items()}

print("Probabilities:")
for state, prob in sorted(probabilities.items()):
    print(f"  |{state}>: {prob:.4f}")

运行结果:

Probabilities:
  |00>: 0.5080
  |11>: 0.4920

Expected output:

Probabilities:
  |00>: 0.4973
  |11>: 0.5027

The Role of Entanglement ​

The key insight of the Bell state is that the two qubits are entangled. This means their measurement outcomes are correlated in a way that cannot be explained by classical probability theory.

If qubit 0 is measured and yields 0, qubit 1 is guaranteed to also yield 0. If qubit 0 yields 1, qubit 1 is guaranteed to yield 1. This perfect correlation is what distinguishes entanglement from mere statistical coincidence.

This can be verified by examining the conditional probabilities:

P(q1=0∣q0=0)=1P(q1=1∣q0=1)=1

The Circuit Flow ​

The following diagram shows the complete flow of data through the Bell state circuit:

mermaid
flowchart LR
    subgraph Initial State
        Q0["|0>"]
        Q1["|0>"]
    end

    subgraph After H
        Q0h["1/sqrt(2) * (|0> + |1>)"]
        Q1a["|0>"]
    end

    subgraph After CNOT
        Q0c["1/sqrt(2) * (|00> + |11>)"]
    end

    subgraph Measurement
        M["00 or 11<br/>(50% each)"]
    end

    Q0 --> H --> Q0h
    Q1 --> Q1a
    Q0h --> CNOT2["CNOT"] --> Q0c
    Q1a --> CNOT2
    Q0c --> M

Package Architecture & Module Structure ​

Now that you have run your first program, let us explore pyqpanda3's complete module system. You do not need to learn all of them at once -- start with core and explore others as your needs grow.

pyqpanda3 is organized into independent modules, each responsible for a specific area of quantum computing:

mermaid
graph TB
    subgraph pyqpanda3
        CORE["core<br/>Gates, Simulators,<br/>Circuits, Noise, Encode"]
        HAMILTONIAN["hamiltonian<br/>PauliOperator,<br/>Hamiltonian"]
        QINFO["quantum_info<br/>StateVector,<br/>DensityMatrix"]
        VQC["vqcircuit<br/>VQCircuit,<br/>Parameter, Gradients"]
        TRANS["transpilation<br/>Transpiler,<br/>Decomposition"]
        IR["intermediate_compiler<br/>OriginIR, QASM"]
        VIS["visualization<br/>Bloch Sphere,<br/>Circuit Drawing"]
        QCLOUD["qcloud<br/>Cloud Service,<br/>Job Management"]
        PROF["profiling<br/>Circuit Analysis,<br/>Profiling"]
    end

    CORE --> HAMILTONIAN
    CORE --> QINFO
    CORE --> VQC
    CORE --> TRANS
    CORE --> IR
    CORE --> VIS
    CORE --> QCLOUD
    CORE --> PROF

    VQC --> HAMILTONIAN
    TRANS --> IR
    QCLOUD --> TRANS

    style CORE fill:#4a90d9,color:#fff,stroke:#2c5f9e
    style HAMILTONIAN fill:#7b68ee,color:#fff,stroke:#4a3db5
    style QINFO fill:#7b68ee,color:#fff,stroke:#4a3db5
    style VQC fill:#7b68ee,color:#fff,stroke:#4a3db5
    style TRANS fill:#50c878,color:#fff,stroke:#2d8a4e
    style IR fill:#50c878,color:#fff,stroke:#2d8a4e
    style VIS fill:#f4a460,color:#fff,stroke:#b87333
    style QCLOUD fill:#f4a460,color:#fff,stroke:#b87333
    style PROF fill:#f4a460,color:#fff,stroke:#b87333

The core module is the foundation. Every other module either extends core functionality or consumes the data structures it produces.

pyqpanda3.core -- The Foundation ​

The core module is the heart of pyqpanda3. It provides everything you need to build and simulate quantum circuits.

Circuit construction:

  • QProg -- Top-level quantum program container
  • QCircuit -- Reusable sub-circuit (supports nested composition)
  • The << operator -- Append gates, circuits, or control flow to a program

Quantum gates (37+):

Simulators:

Noise modeling:

  • NoiseModel -- Container for quantum error specifications
  • 7 error channels: Pauli X/Y/Z, depolarizing, phase damping, amplitude damping, decoherence
  • Per-gate and per-qubit noise assignment

Dynamic circuits:

  • qif / QElseif -- Conditional execution based on measurement results
  • qwhile -- Loop constructs for repeated operations

This example shows a quick tour of some core features:

python
from pyqpanda3 import core

# Create a slightly more complex circuit
prog = core.QProg()

# Apply a sequence of gates
prog << core.H(0)          # Superposition on qubit 0
prog << core.H(1)          # Superposition on qubit 1
prog << core.CNOT(0, 2)    # Entangle qubits 0 and 2
prog << core.CNOT(1, 3)    # Entangle qubits 1 and 3

# Measure all four qubits
prog << core.measure([0, 1, 2, 3], [0, 1, 2, 3])

# Run the simulation
machine = core.CPUQVM()
machine.run(prog, shots=1000)

counts = machine.result().get_counts()
print("4-qubit GHZ-like counts:", counts)

运行结果:

4-qubit GHZ-like counts: {'1111': 225, '1010': 228, '0101': 281, '0000': 266}

pyqpanda3.hamiltonian -- Operators and Hamiltonians ​

The hamiltonian module provides tools for working with Pauli operators and constructing Hamiltonians, which are essential for variational algorithms like VQE and QAOA.

Key classes:

Pauli operators support standard arithmetic:

python
from pyqpanda3.hamiltonian import PauliOperator

# Define Pauli operators on specific qubits
z0 = PauliOperator({"Z0": 1.0})
z1 = PauliOperator({"Z1": 1.0})
x0 = PauliOperator({"X0": 1.0})

# Combine operators with arithmetic
h = 0.5 * z0 * z1 + 0.3 * x0
print(h)

运行结果:

{ qbit_total = 2, pauli_with_coef_s = { 'Z0 Z1 ':0.5 + 0j, 'X0 ':0.3 + 0j, } }

pyqpanda3.quantum_info -- Quantum State Analysis ​

The quantum_info module provides classes for analyzing quantum states and channels.

Key classes:

python
from pyqpanda3.quantum_info import StateVector
import numpy as np

# Create a Bell state vector
bell = StateVector(np.array([1, 0, 0, 1]) / np.sqrt(2))
print(f"Purity: {bell.purity()}")
print(f"Dimension: {bell.dim()}")

运行结果:

Purity: (1.0000000000000004+0j)
Dimension: 4

pyqpanda3.vqcircuit -- Variational Quantum Circuits ​

The vqcircuit module supports building parameterized circuits for variational algorithms. It provides automatic gradient computation using adjoint differentiation.

Key classes:

  • VQCircuit -- Parameterized quantum circuit
  • Parameter -- A trainable parameter
  • Gradient computation with configurable differentiation methods

pyqpanda3.transpilation -- Circuit Optimization ​

The transpilation module handles converting abstract circuits into hardware-compatible ones. It considers device topology (which qubits are physically connected) and decomposes unsupported gates into the native gate set.

Key class:

  • Transpiler -- Converts circuits considering topology and gate constraints

pyqpanda3.intermediate_compiler -- IR Conversion ​

The intermediate_compiler module provides bidirectional conversion between pyqpanda3 circuits and standard intermediate representations.

Supported formats:

  • OriginIR -- OriginQ's native intermediate representation
  • QASM -- OpenQASM 2.0
python
from pyqpanda3.intermediate_compiler import convert_qprog_to_originir
from pyqpanda3 import core

prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1)

# Convert to OriginIR string
ir_string = convert_qprog_to_originir(prog)
print(ir_string)

运行结果:

QINIT 2
CREG 1
H q[0]
CNOT q[0],q[1]

pyqpanda3.visualization -- Drawing and Plots ​

The visualization module produces visual representations of quantum states and circuits.

Capabilities:

  • Bloch sphere rendering for single-qubit states
  • Circuit diagrams in text, image, and LaTeX formats
  • Probability bar charts for measurement outcomes
  • State city plots and density matrix visualizations

pyqpanda3.qcloud -- Cloud Quantum Computing ​

The qcloud module connects to OriginQ's cloud platform, allowing you to submit circuits to real quantum processors.

Key classes:

  • QCloudService -- Main interface for cloud interaction
  • QCloudJob -- Represents a submitted job with status tracking

pyqpanda3.profiling -- Circuit Analysis ​

The profiling module provides tools for analyzing circuit complexity, depth, gate counts, and performance characteristics.

python
from pyqpanda3.profiling import draw_circuit_features
from pyqpanda3 import core

circuit = core.QCircuit(2)
circuit << core.H(0) << core.CNOT(0, 1)

# Visualize circuit features (connectivity, activity, parallelism, entanglement, depth)
draw_circuit_features(circuit, save_fn="circuit_features.png")

Module Overview ​

ModuleKey Classes / FunctionsRole
pyqpanda3.coreQProg, CPUQVM, NoiseModel, H, CNOTFoundation: gates, simulators, circuits
pyqpanda3.hamiltonianPauliOperator, HamiltonianOperator algebra, expectation values
pyqpanda3.quantum_infoStateVector, DensityMatrixQuantum state analysis and channels
pyqpanda3.vqcircuitVQCircuit, ParameterVariational circuits and gradients
pyqpanda3.transpilationTranspilerHardware-aware circuit optimization
pyqpanda3.intermediate_compilerconvert_qprog_to_originir, convert_qasm_string_to_qprogIR conversion (OriginIR, QASM)
pyqpanda3.visualizationplot_bloch, circuit_summaryVisual output for circuits and states
pyqpanda3.qcloudQCloudService, QCloudJobCloud quantum computing
pyqpanda3.profilingdraw_circuit_profile, draw_circuit_featuresCircuit performance analysis

A Slightly Larger Example: GHZ State ​

Before moving on, let us build a slightly more complex program -- a Greenberger-Horne-Zeilinger (GHZ) state on three qubits. The GHZ state extends the concept of entanglement beyond two qubits:

|GHZ3⟩=12(|000⟩+|111⟩)

Create a 3-qubit GHZ state using a chain of CNOT gates:

python
from pyqpanda3 import core

# Build a 3-qubit GHZ state
prog = core.QProg()

# Step 1: Put qubit 0 into superposition
prog << core.H(0)

# Step 2: Entangle qubit 0 with qubit 1
prog << core.CNOT(0, 1)

# Step 3: Entangle qubit 1 with qubit 2
# Now all three qubits share the same superposition
prog << core.CNOT(1, 2)

# Measure all three qubits
prog << core.measure([0, 1, 2], [0, 1, 2])

# Run the simulation
machine = core.CPUQVM()
machine.run(prog, shots=10000)

counts = machine.result().get_counts()
print("GHZ state counts:", counts)

运行结果:

GHZ state counts: {'111': 5033, '000': 4967}

Expected output (approximately):

GHZ state counts: {'000': 5003, '111': 4997}

Just like the Bell state, you should see only 000 and 111 outcomes, with roughly equal frequency. No outcomes like 001, 010, 100, 011, 101, or 110 should appear.

The GHZ state demonstrates multi-qubit entanglement. Extending to more qubits is straightforward -- simply add more CNOT gates in the chain:

mermaid
flowchart LR
    H0["H(0)"] --> CNOT01["CNOT(0,1)"] --> CNOT12["CNOT(1,2)"] --> M["Measure"]

This pattern generalizes: for n-qubit GHZ state, apply one Hadamard followed by n−1 CNOT gates in a chain.


Working with Noise Models ​

Real quantum hardware is noisy. pyqpanda3 allows you to simulate this noise to understand how your circuits would behave on actual devices. Here is a quick preview of noise simulation using the Bell state from earlier.

Apply a depolarizing noise model to the CNOT gate:

python
from pyqpanda3 import core

# Build the same Bell state circuit
prog = core.QProg()
prog << core.H(0)
prog << core.CNOT(0, 1)
prog << core.measure([0, 1], [0, 1])

# Create a noise model with 1% depolarizing error on the CNOT gate
noise = core.NoiseModel()
noise.add_quantum_error(
    core.depolarizing_error(0.01),
    core.GateType.CNOT,
    [0, 1]
)

# Run with the noise model
machine = core.CPUQVM()
machine.run(prog, shots=10000, model=noise)

counts = machine.result().get_counts()
print("Noisy Bell state counts:", counts)

运行结果:

Noisy Bell state counts: {'01': 60, '10': 45, '11': 5003, '00': 4892}

With noise, you will now see small but non-zero counts for 01 and 10:

Noisy Bell state counts: {'00': 4912, '11': 4953, '01': 72, '10': 63}

The noise model injects errors that occasionally flip qubits, causing the previously impossible outcomes (01 and 10) to appear with small probability. This is a realistic simulation of what happens on actual quantum hardware.


Circuit Composition Patterns ​

pyqpanda3 offers several patterns for building circuits. Understanding these patterns early will help you write cleaner, more reusable code.

Chaining with the << Operator ​

The most common pattern is chaining gates with <<:

python
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])

Building Programs Incrementally ​

You can also build programs step by step, which is useful for conditional construction:

python
prog = core.QProg()
prog << core.H(0)

# Add gates conditionally
n_qubits = 3
for i in range(1, n_qubits):
    prog << core.CNOT(i - 1, i)

prog << core.measure(list(range(n_qubits)), list(range(n_qubits)))

This pattern is especially useful when the circuit structure depends on runtime parameters.

Printing Circuit Information ​

You can inspect a circuit at any time by printing it:

python
print(prog)

运行结果:

          ┌─┐               ┌─┐          
q_0:  |0>─┤H├ ───*── ───────┤M├ ──────── 
          └─┘ ┌──┴─┐        └╥┘  ┌─┐     
q_1:  |0>──── ┤CNOT├ ───*────╫─ ─┤M├──── 
              └────┘ ┌──┴─┐  ║   └╥┘ ┌─┐ 
q_2:  |0>──── ────── ┤CNOT├──╫─ ──╫──┤M├ 
                     └────┘  ║    ║  └╥┘ 
 c :   / ════════════════════╩════╩═══╩═
                              0    1   2

This displays a text diagram of the circuit, which is useful for debugging and verifying that your circuit has the intended structure.


Performance Considerations ​

Understanding the computational cost of simulation helps you choose the right parameters.

Statevector Simulation Scaling ​

The CPUQVM stores the full statevector of n qubits, which has 2n complex amplitudes. Memory usage scales exponentially:

Qubits (n)Statevector SizeMemory (128 bytes/amplitude)
101,02416 KB
201,048,57616 MB
2533,554,432512 MB
301,073,741,82416 GB
324,294,967,29664 GB

For circuits beyond 25-30 qubits, consider:

  • PartialAmplitudeQVM -- Computes only a subset of amplitudes
  • Stabilizer -- Efficient simulation for Clifford-only circuits (no T gates)
  • GPUQVM -- Offloads computation to a GPU for faster statevector updates

Shot Count Trade-off ​

Higher shot counts give better statistical accuracy but take more time. A practical guideline:

ShotsUse Case
100 - 1,000Quick testing and debugging
1,000 - 10,000Standard simulations
10,000 - 100,000High-precision probability estimation

The Development Workflow ​

Here is the typical workflow for developing quantum programs with pyqpanda3:

mermaid
flowchart TD
    A["1. Import core"] --> B["2. Create QProg"]
    B --> C["3. Add gates"]
    C --> D["4. Add measurement"]
    D --> E["5. Create simulator"]
    E --> F["6. Run"]
    F --> G["7. Get counts"]
    G --> H{8. Analyze}
    H -->|Adjust| C
    H -->|Add noise| I["NoiseModel"]
    I --> F
    H -->|Visualize| J["visualization"]
    H -->|Done| K["Next"]

This iterative loop -- build, run, analyze, adjust -- is the fundamental rhythm of quantum program development. Start simple, verify each step, and gradually increase complexity.


Next Steps ​

Congratulations on completing your first quantum program with pyqpanda3! You now have a working development environment and understand the basics of circuit construction and simulation.

Learn the Fundamentals ​

If you are new to quantum computing, continue with these tutorials:

TutorialWhat You Will Learn
Quantum BasicsQubits, quantum gates, measurement, and the Bloch sphere
Circuit ConstructionAdvanced circuit patterns with QProg, QCircuit, and the << operator
SimulationAll simulator types and when to use each one

Explore Specific Features ​

If you already understand quantum computing basics and want to explore specific features:

TopicTutorial
Realistic hardware simulationNoise Simulation
Parameterized circuits and gradientsVariational Circuits
Pauli operators and expectation valuesHamiltonian & Pauli Operators
State analysis and channel theoryQuantum Information
Circuit drawing and Bloch sphereVisualization
Hardware-aware optimizationTranspilation
Real quantum processorsCloud Computing
State encoding methodsQuantum State Preparation

Try Practical Examples ​

The How-To section contains ready-to-run examples for common quantum algorithms:

Additional Resources ​

  • API Reference -- Complete API documentation for all modules
  • Concepts -- Theoretical background on quantum gates, noise, and information
  • Release Notes -- Version update history

In this tutorial, you learned:

  1. What pyqpanda3 is -- A Python SDK for quantum computing with a C++ backend, supporting circuit construction, simulation, noise modeling, and cloud execution.
  2. System requirements -- Python 3.10-3.14 and related dependencies.
  3. Installation & troubleshooting -- Installing with pip install pyqpanda3, plus solutions for common installation issues.
  4. Verification -- Three quick checks to confirm your installation works.
  5. Bell state program -- A complete quantum program using QProg, H, CNOT, measure, and CPUQVM.
  6. Output analysis -- Understanding measurement counts, probabilities, and entanglement.
  7. Module overview -- The nine modules that make up pyqpanda3 and what each one does.

You are now ready to move on to the Quantum Basics tutorial, where you will learn the mathematical foundations of quantum gates and how they manipulate quantum states.

Released under the MIT License.