QUANTUM COMPUTING · HANDS-ON TRACK

量子计算实作进阶:从模拟器到真实实验

Quantum Computing Practicum: From Simulator to Experiment

After the 21-day theory course, turn understanding into code that runs, tests, and explains results. Statevector, circuit IR, Deutsch–Jozsa/Grover, QFT/phase estimation, the N=15 period outline, noise/repetition-code, VQE, QAOA, and a Qiskit transpilation workflow are available; users submit real QPU jobs from their own configured Qiskit environment.

The simulator on this page runs locally in your browser; no account, API key, or quantum hardware is required.

What this practicum is designed to teach

Build a small simulator

Work with complex-amplitude arrays, single-qubit and controlled gates, measurement sampling, and the O(2ⁿ) state-storage limit.

Implement and verify algorithms

The roadmap covers Deutsch–Jozsa, Grover, QFT/phase estimation, a small Shor example, VQE, and QAOA—with reference states, distributions, and classical cross-checks.

Complete an engineering workflow

Study noise and introductory error correction, build and transpile with Qiskit, then compare ideal, noisy, and optional QPU results.

Scope: This advanced path is not a guarantee of research-level independence. Day 1–8 teaching material and local demos are complete. Real QPU jobs require users to install Qiskit, manage provider accounts/credentials, choose a real backend, and account for cost and queue limits; this site neither collects credentials nor claims to run hardware jobs.

Practicum roadmap: build the tool, then the algorithms

Available

Day 1 | Statevector simulator

Complex amplitudes, H/X/Z/Ry, CNOT, normalization, seeded measurement, and unit tests.

Available

Day 2 | Circuit IR and tests

Add gate sequences, controlled rotations, bit-order conventions, measurement maps, Bell states, and property tests.

Available

Day 3 | Deutsch–Jozsa and Grover

Implement oracles and target probabilities, add small exhaustive classical baselines, and test query counts and overshoot.

Available

Day 4 | QFT, phase estimation, and Shor periods

Implement small-width QFT/inverse QFT, compare exact and off-grid phases, and explore N=15 periods and classical post-processing with an explicitly idealized eigenphase model.

Available

Day 5 | Noise and repetition code

Add dephasing, amplitude damping, and readout faults; simulate a three-qubit repetition-code syndrome and distinguish correction from post-selection.

Available

Day 6 | VQE and the classical optimization loop

Use a small Hamiltonian, parameterized circuit, expectation measurements, and a classical optimizer; compare exact ground states, shot noise, and optimizer stability.

Available

Day 7 | QAOA and Max-Cut

Encode triangle Max-Cut as a cost Hamiltonian, run a p=1 alternating-operator circuit, inspect the cut distribution, and compare with the exhaustive classical optimum.

Available · current lab

Day 8 | Qiskit, transpilation, and QPU workflow

Follow reproducible Qiskit build/transpile commands and interactively compare a logical circuit with SWAP routing on a constrained topology; real cloud hardware submission is documented as user-side steps, never fabricated.

Day 1 lab | Run a statevector circuit yourself

A simulator stores amplitudes for n qubits in a complex vector of length 2ⁿ. Use the two-qubit circuit below: apply H, then CNOT, to prepare a Bell state. Add gates one at a time and inspect amplitudes, probabilities, and seeded samples.

Gate controls (q0 is the least-significant bit)

Add gates or run a measurement.

|00⟩
100.0%
|01⟩
0.0%
|10⟩
0.0%
|11⟩
0.0%

Statevector and probabilities

|ψ⟩ = Σₓ αₓ|x⟩
Norm squared = 1.000000000000
Gate sequence: (no gates yet)

|00⟩  1.0000 + 0.0000i   P = 100.00%
|01⟩  0.0000 + 0.0000i   P = 0.00%
|10⟩  0.0000 + 0.0000i   P = 0.00%
|11⟩  0.0000 + 0.0000i   P = 0.00%
Sampling does not mutate the theoretical state shown here. Each gate replays the circuit from |00⟩; measurement uses the chosen seed, so the same circuit, shot count, and seed produce identical counts.

Day 2 lab | Circuit IR, controlled rotations, and bit order

A circuit intermediate representation (IR) stores which gates to execute and in what order, then replays them from |00⟩. A measurement map explicitly defines which qubit is recorded in each classical bit cᵢ. Build a gate sequence, inspect its IR, and compare outcomes under two bit orders.

Add gates (q0 is the least-significant bit)

Add gates to inspect the circuit IR; measurement uses the selected bit order.

|00⟩
100.0%
|01⟩
0.0%
|10⟩
0.0%
|11⟩
0.0%

Circuit IR and state

{
  "numQubits": 2,
  "gates": [],
  "measurementMap": [
    0,
    1
  ],
  "basisOrder": "q0 is the least-significant bit",
  "classicalBits": [
    {
      "classicalBit": 0,
      "measuredQubit": 0
    },
    {
      "classicalBit": 1,
      "measuredQubit": 1
    }
  ],
  "displayOrder": "c1 … c0"
}
|ψ⟩ = Σₓ αₓ|x⟩
Norm squared = 1.000000000000

|00⟩  1.0000 + 0.0000i   P = 100.00%
|01⟩  0.0000 + 0.0000i   P = 0.00%
|10⟩  0.0000 + 0.0000i   P = 0.00%
|11⟩  0.0000 + 0.0000i   P = 0.00%

Bit-order rule: Entry i of the map means cᵢ ← q[mapping[i]]. With [0,1], c0 reads q0 and c1 reads q1; outcome strings display c1c0. A Bell state remains 00/11 when the map is reversed. Prepare |01⟩ with X(q0) to see it displayed as |10⟩ under [1,0].

Exercises and automated properties

  1. Add H(q0), then CNOT(q0,q1). Inspect the IR order and Bell probabilities. Clear the circuit, add X(q0), switch the measurement map, and observe the |01⟩ to |10⟩ label change.
  2. Add X(q0), set CRy's angle to π, then add CRy(q0,q1). With the control set, the target rotates from 0 to 1, producing |11⟩.
  3. Run the property tests: 80 seeded random small circuits are checked for unit norm, mapped probabilities summing to one, conserved shot totals, and reproducible sampling.

Day 3 lab | Deutsch–Jozsa and Grover search

Both algorithms illustrate oracle query complexity, but solve different problems: Deutsch–Jozsa classifies a function under a constant-or-balanced promise; Grover amplifies the marked state in an unstructured search. These are small ideal statevector experiments (two input bits / four items), not hardware runs or evidence that quantum computing gives exponential speedups for every task.

A. Deutsch–Jozsa: verify the promise, then inspect interference

The function oracle implements |x,y⟩ → |x, y XOR f(x)⟩. Preparing the ancilla in |−⟩ turns function values into phases; Hadamards on the input bits reveal the result. A constant function yields input 00, while a balanced function gives it zero probability. “One quantum oracle query vs at most three deterministic classical queries” applies only to this two-input-bit promise problem.

Choose an oracle that satisfies the promise, then run the experiment.

Truth table, query baseline, and circuit summary


        

B. Grover: amplify the target and observe overshooting

Mark one of four candidates in a uniform superposition. Each round applies a phase oracle and diffuser; the theoretical success probability is sin²((2k+1)θ), where sin²θ=1/4. Here k=1 happens to reach 100%; k=0 gives 25%, and another round (k=2) drops back to 25%, illustrating discrete-iteration overshoot. General searches must choose iterations based on the number of marked items—one round is not a universal rule.

Choose a marked state and iteration count, then run the search.

Theoretical probability, gate count, and samples


        

Scope: Oracles are decomposed into H/X/CNOT gates supported by this simulator. Displayed gate counts exclude noise, hardware routing, and compilation overhead. “Query count” counts oracle uses, not elementary gates. All computation runs locally in the browser, and sampling uses a seeded pseudorandom generator.

Exercises and checks

  1. Try all five DJ oracles and inspect their truth tables. Constant functions should yield only 00; balanced functions must exclude 00.
  2. Set Grover iterations to 0, 1, and 2. Observe target probabilities of 25% → 100% → 25%, then change the marked state to check bit ordering.
  3. Change shots and seed: ideal probabilities stay fixed, counts sum to shots, and identical parameters reproduce the same samples.
  4. Explain why the Deutsch–Jozsa query separation depends on its promise and why Grover can overshoot; derive a suitable iteration count for general N from sin²θ=M/N.

Day 4 lab | QFT, phase estimation, and N=15 period finding

The QFT encodes a basis index as a phase ramp; the inverse QFT turns phase back into measurable frequency. This lab constructs controlled-phase gate sequences using q0 as the least-significant bit, up to five qubits, and checks the transform by applying QFT followed by its inverse. Results are ideal statevector simulations in your browser.

A. QFT / inverse QFT: inspect amplitudes and round-trip error

Choose a basis input and transform, then run.

Output distribution and gate sequence


        

B. Phase estimation: grid-aligned and off-grid phases

With four estimation qubits, encode phase kickback and apply the inverse QFT. Enter φ∈[0,1): when φ=k/16, the ideal result is concentrated at k; phases between grid points spread probability across outcomes. This directly encodes a known eigenphase in a controlled model—it does not implement a general target register or a modular-multiplication oracle.

Choose a grid-aligned or off-grid phase, then run phase estimation.

Phase resolution, probability peaks, and gate sequence


        

C. Shor outline: N=15 period and classical factor post-processing

Choose a base a coprime to 15 and inspect continued-fraction denominator candidates for measured y/16. Classical post-processing verifies aʳ mod 15=1, then computes gcd(a^(r/2)±1,15) only when r is even and a^(r/2) is not −1 mod 15. y=0, unreliable denominators, and failed factor conditions require retries. To keep this lab bounded, a classical enumeration supplies the reference period; an equal mixture of its eigenphases is passed through four-bit QPE. This is not a reversible modular-exponentiation circuit, a demonstration of Shor speedup, or a QPU run. A non-coprime base returns a factor through a classical gcd pre-check.

Choose a base and run idealized period finding with classical post-processing.

Outcomes, continued fractions, and retry conditions


        

Exercises: Verify that a three-qubit QFT followed by its inverse returns |x⟩. For φ=5/16, only y=5 should appear; for φ=0.30, inspect the broadened peak near y=5. Compare a=2 and a=4 to recover r=4 and r=2 and factors 3 and 5, then explain why the gcd pre-check suffices for a=3. QPE sampling and the Shor model are seeded, local simulations.

Day 5 lab | Noise channels, three-qubit repetition code, and post-selection

Sample independent X flips, Z dephasing, amplitude damping, and classical readout faults on a three-physical-qubit encoded state. Switch between the bit-flip code (|000⟩/|111⟩) and phase-flip code (|+++⟩/|---⟩), inspect how syndromes locate a single correctable error, and compare raw logical readout, syndrome correction, and post-selection that keeps only zero-syndrome shots. This Monte Carlo trajectory model omits gate faults, leakage, correlated noise, and full fault-tolerant architecture.

Set noise strengths, then run the seeded trajectory simulation.

Raw outcomes, syndromes, and three strategies


        

How to read it: s₀=q₀⊕q₁ and s₁=q₁⊕q₂; 01, 11, and 10 point to single-qubit errors on q₀, q₁, and q₂. Correction actively flips the indicated physical bit. Post-selection merely discards nonzero syndromes, reducing usable shots while missing zero-syndrome logical errors such as 000→111; readout faults also corrupt syndromes. A repetition code corrects one Pauli-flip type in its chosen basis; the complementary type can become a logical error.

Day 6 lab | VQE, Pauli measurements, and classical optimization

The variational quantum eigensolver (VQE) prepares |ψ(θ,φ)⟩ with a parameterized circuit, estimates each Pauli term in the Hamiltonian, and lets a classical optimizer update the parameters. This two-qubit isotropic Heisenberg model is H = ½(XX + YY + ZZ). Its known singlet ground state has energy −1.5; the compact ansatz here can reach it, making measurements and optimization easy to verify.

The gate order is X(q0) → Ry(q1, θ) → CNOT(q1→q0) → Rz(q1, φ), with q0 as the least-significant bit. θ=π/2 and φ=π prepare the singlet up to global phase. Each Pauli term is measured in its own basis with the requested number of shots, so the total is 3×shots.

Set parameters to measure the three Pauli terms, or run the classical optimizer.

Exact expectations, shot estimates, and optimizer trace


        

Model and optimizer limits: The exact ground energy −1.5 comes from the analytic spectrum of this two-qubit Hamiltonian, not a quantum-hardware measurement. Finite shots independently sample XX, YY, and ZZ, so the energy estimate has statistical error. This demo computes parameter-shift gradients from exact local statevector expectations; shot estimates are shown for comparison but do not feed parameter updates. Real VQE is affected by finite shots, noise, ansatz expressibility, optimizer behavior, and device transpilation.

Day 7 lab | QAOA and triangle Max-Cut

Max-Cut divides a graph's vertices into two sets and tries to maximize crossing edges. This fixed three-node triangle has edges (0,1), (1,2), and (0,2). With bᵢ∈{0,1} denoting the set, the classical cost is C(b)=Σ(bᵢ XOR bⱼ), with quantum cost Hamiltonian HC=Σ(1−ZᵢZⱼ)/2. A triangle is not bipartite, so exhaustive classical search gives a maximum cut of two edges.

For p=1, QAOA starts in a uniform superposition, alternates cost evolution UC(γ)=e−iγHC and mixer evolution UB(β)=e−iβ(X₀+X₁+X₂), then measures a bitstring. Each edge cost is decomposed into CNOT—Rz(−γ)—CNOT (up to global phase); the mixer uses Rx(2β) on each qubit. Bitstrings display as q₂q₁q₀, with q0 the least-significant bit.

Set β, γ, and shots, then run the p=1 Max-Cut QAOA circuit.

Ideal distribution, shots, and classical baseline


        

Scope: The graph and circuit use only three qubits, so the statevector and all eight cuts are classically enumerable. The optimizer performs a uniform two-dimensional grid search on the CPU using the exact ideal statevector objective; shots sample only the selected final circuit. This is not a hardware run, shot-feedback optimization, or evidence of quantum speedup. Grid resolution limits parameter precision.

Day 8 lab | Qiskit circuits, transpilation, and optional QPU

A typical Qiskit workflow is: build a QuantumCircuit → choose a backend/target instruction set → transpile (decompose, layout, route, optimize) → run on a local simulator or real backend → record backend, shots, job ID, and results. Transpilation is not simply gate-count reduction: limited coupling can require SWAP routing, and optimization level or initial layout can change the output. The topology demo below is pedagogical; a user-side Qiskit API outline follows.

Choose a physical topology and initial layout to generate a conceptual routing sketch.

Logical circuit and pedagogical routing summary


        

User-side local Qiskit example

Install compatible Qiskit packages in a separate Python environment (for example, python -m pip install qiskit qiskit-aer), save the script below, and run it locally. The simulator comes from the local install and creates no cloud job; check imports and APIs against the installed version before use.

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

qc = QuantumCircuit(3, 3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure([0, 1, 2], [0, 1, 2])

backend = AerSimulator()
compiled = transpile(qc, backend=backend, optimization_level=1, seed_transpiler=7)
result = backend.run(compiled, shots=1024, seed_simulator=2026).result()
print("depth", compiled.depth(), "ops", compiled.count_ops())
print(result.get_counts())

Optional: submit a real QPU job yourself

  1. Create a provider account using its official docs and store credentials in a local environment variable or approved credential store—never in a webpage, repository, or chat.
  2. Check the installed provider plugin's docs for account setup, backend names, qubit count, native gates, coupling map, and job API; providers differ.
  3. Transpile the same QuantumCircuit to the chosen backend and record seed_transpiler, optimization_level, initial layout, depth, operation counts, and SWAP count.
  4. Submit a bounded-shot job through that provider's documented run or Sampler API. Store the job ID securely, retrieve counts on completion, and record backend calibration and timestamp.
  5. Compare hardware counts with ideal simulation, finite-shot uncertainty, and local noise models; distinguish sampling fluctuation from gate/readout error and drift.

Hardware boundary: This page includes no provider SDK, credential entry, or network job submission, and shows no fabricated backend, calibration, job ID, or QPU counts. The topology route is a conceptual demo using fixed simplified rules, not Qiskit's transpiler output; do not treat its SWAP count as a real compilation result.

Core implementation: update amplitude pairs for one target bit

Write basis index x in binary; target qubit q corresponds to mask 2^q. Pair each basis state whose target bit is 0 with the state obtained by flipping that bit, then apply the 2×2 gate matrix. There is no need to construct a dense 2ⁿ×2ⁿ global matrix.

mask = 1 << target
for basis in 0 .. 2^n - 1:
    if basis & mask == 0:
        partner = basis | mask
        a0, a1 = state[basis], state[partner]
        state[basis]   = m00*a0 + m01*a1
        state[partner] = m10*a0 + m11*a1
CheckHow to verify
NormalizationAfter each unitary, the sum of squared amplitudes Σ|αₓ|² = 1 within a floating-point tolerance.
Known statesCheck X|0⟩=|1⟩ and H|0⟩=(|0⟩+|1⟩)/√2.
Entanglement and bit orderH(q0) followed by CNOT(q0,q1) should yield equal probabilities for |00⟩ and |11⟩, not adjacent indices.
SamplingCounts must sum to shots; a fixed seed is reproducible; empirical frequencies fluctuate around theoretical probabilities.

Scaling: statevector memory grows exponentially as 2ⁿ. Applying one single-qubit gate takes about O(2ⁿ) updates. This is useful for learning and small verification—not a way to simulate arbitrarily large circuits on a laptop.

Exercises and completion criteria

  1. Apply H(q0): |00⟩ and |01⟩ should each have probability one half. Add CNOT(q0,q1): the Bell state should contain only |00⟩ and |11⟩ outcomes.
  2. Try X, Z, Ry(π/2), and reversed CNOT. Compare phase changes that preserve probabilities with changes to bit ordering.
  3. Run the same circuit and seed twice, then change the seed. Counts may change, but |01⟩ and |10⟩ must remain impossible for this Bell state.
  4. Read the implementation and tests. Explain the indexing convention and single-gate complexity; add an inverse-gate or probability-sum test.

Companion code: statevector simulator, algorithms, QFT, noise, VQE, QAOA, and period post-processing, Day 5 noise lab, Day 6 VQE lab, Day 7 QAOA lab, and Day 8 topology-routing teaching model. Run node --test tests/quantum-simulator.test.cjs for simulator and algorithm regressions. These are small local models. Real QPU jobs require a user-managed Qiskit install and provider credentials; this page does not submit them.

觉得好用?Found it useful?