Chuyển đến nội dung

Bài 12 · Gates and Circuits

Building a Circuit Simulator

Build a small but complete state-vector quantum circuit simulator in about 40 lines of NumPy: apply gates to chosen qubits, read probabilities, sample shots and create GHZ states.

You now know the three ingredients of a simulator: states are vectors, gates are unitary matrices, and measurement samples from squared amplitudes. This lesson combines them into a small, readable state-vector simulator that can apply any gate to any qubits of an n-qubit register. You will reuse the same idea throughout the course, and it is exactly what libraries such as Qiskit and Cirq do internally (with a great deal more engineering).

The challenge: gates on chosen qubits

On two qubits you could build kron(H, I) to apply H to the first qubit. On ten qubits, building a 1024 x 1024 matrix for every gate wastes memory and time, and gets worse every qubit. A better method never builds the big matrix at all.

The trick: reshape the state vector of 2^n entries into an array with n axes, each of length 2, one axis per qubit. A k-qubit gate is a tensor with k input axes and k output axes. Applying it to qubits q1 ... qk is a tensor contraction over those axes. NumPy's np.tensordot does the work, followed by np.moveaxis to put the output axes back where the qubits belong.

flowchart LR
    V["state vector<br/>2^n entries"] --> R["reshape to<br/>[2] * n"]
    R --> C["tensordot with gate<br/>over chosen axes"]
    C --> M["moveaxis back"]
    M --> F["flatten to<br/>2^n entries"]

The gate touches only the axes of the qubits it acts on.

The simulator

Here is the whole thing. Read it slowly: every method is a few lines, and each idea comes from an earlier lesson.

Python A 40-line state-vector simulator

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The circuit (Hadamard on qubit 0, then CNOT from 0 to 1) produces (|00> + |11>)/sqrt(2). Only two outcomes ever appear, 00 and 11, each about half the time: a perfectly correlated pair of random bits.

Checking the simulator

A simulator you cannot trust is worse than none. Compare it against the slow-but-obvious method (building the full matrix with np.kron) on a few random-looking circuits. If the two methods agree, the tensor trick is implemented correctly.

Python Verify against full Kronecker matrices

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last circuit shows the benefit: a CNOT between qubits 0 and 2 works without any manual swapping or matrix construction. (Real hardware cannot do this when qubits are far apart, but a simulator can.)

Uniform superposition and GHZ states

With the simulator, big ideas shrink to one-liners:

  • Uniform superposition: apply H to every qubit, producing equal amplitudes 1/sqrt(2^n) on all 2^n strings. Almost every algorithm starts like this.
  • GHZ state: H on qubit 0 followed by CNOTs from qubit 0 to each other qubit gives (|00...0> + |11...1>)/sqrt(2), an entangled state of any number of qubits where all measurements agree.
Python Uniform superposition and a 4-qubit GHZ state

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Where to go from here

This simulator is complete for noise-free circuits up to about 20 qubits on a laptop (a 20-qubit state has a million entries). Natural extensions are exercises you can try:

  • Add convenience methods h(q), x(q), cx(c, t) that call gate.
  • Add mid-circuit measurement using the collapse logic from Multi-Qubit States and the Tensor Product.
  • Add a method that prints a text diagram of the gates applied.
  • Add noise (see the chapter on error correction).

Qubit ordering is a frequent source of confusion. Here qubit 0 is the leftmost bit of the printed string. Qiskit prints with qubit 0 on the right. If you compare outputs with another tool, reverse the bit strings.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the simulator reshape the state vector to [2] * n?

    With one axis per qubit, a k-qubit gate contracts with exactly those k axes, with no large matrix needed.
  2. 2. After H on qubit 0 and CNOT(0, 1) on |00>, which outcomes can be measured?

    The state is (|00> + |11>)/sqrt(2): perfectly correlated bits.
  3. 3. How many amplitudes does a 20-qubit simulation store?

    2^20 = 1,048,576 complex numbers, about 16 MB.
  4. 4. What does applying H to every qubit of |000> produce?

    Each qubit becomes |+>, so the product state has equal amplitude 1/sqrt(8) on every bit string.

Summary

  • Reshape the state to one axis per qubit; apply a gate by np.tensordot and np.moveaxis.
  • A k-qubit gate is a 2^k x 2^k matrix reshaped to 2k axes of length 2.
  • Verify any simulator against a slow Kronecker-product reference.
  • H on every qubit gives a uniform superposition; H plus a chain of CNOTs gives a GHZ state.
  • Memory doubles with each qubit, limiting simulation to a few dozen qubits.

Next: Universal Gate Sets and Circuit Identities

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.