Lesson 37: IBM Qiskit I: Circuits, Simulation and Primitives¶
37.1 Learning Outcomes¶
By the end of this hour a student will be able to:
- Install Qiskit and construct circuits with
QuantumCircuit. - Apply all standard gates and read Qiskit's little-endian bit ordering correctly.
- Use the Sampler and Estimator primitives.
- Run statevector and shot-based simulations and interpret the results.
- Visualise circuits, histograms, Bloch spheres and state vectors.
37.2 Installation and Setup¶
pip install qiskit qiskit-aer qiskit-ibm-runtime
pip install matplotlib pylatexenc # for circuit drawing
import qiskit
print(qiskit.__version__) # 1.x or 2.x
Version warning. Qiskit 1.0 (2024) removed execute(), BasicAer and qiskit.providers.aer.
Tutorials written before 2024 will not run. The current pattern is primitives (Sampler,
Estimator), which is what this lesson teaches.
37.3 Building Circuits¶
The basics¶
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3) # 3 qubits, 3 classical bits
qc.h(0) # Hadamard on qubit 0
qc.cx(0, 1) # CNOT: control 0, target 1
qc.cx(0, 2) # CNOT: control 0, target 2
qc.measure([0, 1, 2], [0, 1, 2])
print(qc.draw())
Output:
┌───┐ ┌─┐
q_0: ┤ H ├──■────■──┤M├──────
└───┘┌─┴─┐ │ └╥┘┌─┐
q_1: ─────┤ X ├──┼───╫─┤M├───
└───┘┌─┴─┐ ║ └╥┘┌─┐
q_2: ──────────┤ X ├─╫──╫─┤M├
└───┘ ║ ║ └╥┘
c: 3/════════════════╩══╩══╩═
0 1 2
Gate reference¶
| Gate | Qiskit call | Note |
|---|---|---|
| \(X, Y, Z\) | qc.x(0), qc.y(0), qc.z(0) |
Paulis |
| \(H\) | qc.h(0) |
Hadamard |
| \(S, S^\dagger\) | qc.s(0), qc.sdg(0) |
phase |
| \(T, T^\dagger\) | qc.t(0), qc.tdg(0) |
\(\pi/4\) phase |
| \(R_x,R_y,R_z\) | qc.rx(theta,0) etc. |
rotations |
| \(P(\lambda)\) | qc.p(lam, 0) |
phase gate |
| \(U(\theta,\phi,\lambda)\) | qc.u(th, ph, lam, 0) |
general |
| CNOT | qc.cx(0,1) |
control, target |
| CZ | qc.cz(0,1) |
symmetric |
| SWAP | qc.swap(0,1) |
|
| Toffoli | qc.ccx(0,1,2) |
two controls |
| Controlled-\(U\) | qc.cu(...), qc.crx(...) |
|
| Barrier | qc.barrier() |
blocks optimisation across it |
The endianness trap¶
Qiskit uses little-endian ordering. The state \(|q_2q_1q_0\rangle\) is written with qubit 0 on the right. A measured bitstring
'011'means \(q_2 = 0\), \(q_1 = 1\), \(q_0 = 1\).
Concrete example.
qc = QuantumCircuit(2)
qc.x(0) # flip qubit 0 only
# Statevector is |01> in Qiskit's notation -- NOT |10>
This differs from the textbook convention used in Units I–III of this course, where \(|q_0q_1\rangle\) has qubit 0 on the left. When comparing hand calculations with Qiskit output, reverse the bitstring.
To match the textbook convention, use qc.reverse_bits() before measuring, or read results with
key[::-1].
37.4 Simulation¶
Exact statevector¶
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
sv = Statevector(qc)
print(sv)
# Statevector([0.70710678+0.j, 0.+0.j, 0.+0.j, 0.70710678+0.j], dims=(2,2))
print(sv.probabilities_dict())
# {'00': 0.5, '11': 0.5}
Shot-based sampling with the Sampler primitive¶
from qiskit_aer.primitives import SamplerV2 as Sampler
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
sampler = Sampler()
job = sampler.run([qc], shots=4096)
result = job.result()
counts = result[0].data.c.get_counts()
print(counts)
# {'00': 2043, '11': 2053} -- approximately 50/50 with shot noise
Expectation values with the Estimator primitive¶
from qiskit.quantum_info import SparsePauliOp
from qiskit_aer.primitives import EstimatorV2 as Estimator
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1) # NOTE: no measurement instruction
observable = SparsePauliOp("ZZ") # Z (x) Z
estimator = Estimator()
job = estimator.run([(qc, observable)])
print(job.result()[0].data.evs)
# 1.0 -- the Bell state |Phi+> is a +1 eigenstate of ZZ
Sampler versus Estimator — the distinction students must internalise.
| Sampler | Estimator | |
|---|---|---|
| Returns | bitstring counts / probabilities | expectation value \(\langle O\rangle\) |
| Circuit must | include measure |
exclude measure |
| Used by | Grover, Shor, sampling algorithms | VQE, QAOA, QML |
| Error mitigation | limited | built in (ZNE, PEC, twirling) |
Density-matrix simulation with noise¶
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, depolarizing_error
noise = NoiseModel()
noise.add_all_qubit_quantum_error(depolarizing_error(0.01, 1), ['h', 'x'])
noise.add_all_qubit_quantum_error(depolarizing_error(0.02, 2), ['cx'])
sim = AerSimulator(noise_model=noise)
result = sim.run(qc, shots=4096).result()
print(result.get_counts())
# {'00': 1980, '01': 60, '10': 55, '11': 2001}
# -- '01' and '10' now appear: these are noise-induced errors
37.5 Visualisation¶
from qiskit.visualization import (plot_histogram, plot_bloch_multivector,
plot_state_city)
qc.draw('mpl') # publication-quality circuit diagram
plot_histogram(counts) # measurement outcomes
plot_bloch_multivector(sv) # Bloch sphere per qubit
plot_state_city(sv) # real/imaginary amplitude bars
Note on plot_bloch_multivector. It shows the reduced state of each qubit. For an entangled
state such as \(|\Phi^+\rangle\), both Bloch vectors sit at the origin (\(\rho_A = I/2\), L08) — a
striking and pedagogically valuable visualisation of the fact that entanglement information lives in
the correlations, not in the parts.
37.6 Solved Problems¶
Problem 1 — Bell state with full analysis¶
Write Qiskit code to create \(|\Phi^+\rangle\), print the statevector, sample 8192 shots, and verify the result statistically.
Solution.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit_aer.primitives import SamplerV2 as Sampler
import numpy as np
# --- exact statevector ---
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
sv = Statevector(qc)
print("Statevector:", np.round(sv.data, 4))
# [0.7071+0.j 0.+0.j 0.+0.j 0.7071+0.j]
# --- shot-based sampling ---
qc_m = qc.copy()
qc_m.measure_all()
counts = Sampler().run([qc_m], shots=8192).result()[0].data.meas.get_counts()
print(counts)
Typical output: {'00': 4103, '11': 4089}.
Statistical verification. Expected count for each outcome: \(8192\times0.5 = 4096\).
Standard deviation of a binomial count:
Observed deviation: \(|4103 - 4096| = 7\), i.e. \(\frac{7}{45.25} = 0.15\sigma\) — entirely consistent with the prediction.
A \(\chi^2\) goodness-of-fit test.
With 1 degree of freedom, the critical value at 5 % is 3.84. Since \(0.024 \ll 3.84\), we do not reject the hypothesis of a fair 50/50 distribution ✓.
Key observation: 01 and 10 have count zero, confirming perfect correlation — the
signature of the Bell state.
Problem 2 — Endianness, demonstrated concretely¶
Create a 3-qubit circuit applying \(X\) to qubit 0 only. Predict the Qiskit output and the textbook notation, and show how to convert between them.
Solution.
qc = QuantumCircuit(3, 3)
qc.x(0) # flip ONLY qubit 0
qc.measure([0,1,2], [0,1,2])
Qiskit output: {'001': 1024}
Reading it. Qiskit prints \(c_2c_1c_0\), so '001' means \(c_2=0\), \(c_1=0\), \(c_0 = 1\) — qubit 0 is
in state 1 ✓, qubits 1 and 2 are in state 0 ✓.
Textbook notation (this course, \(|q_0q_1q_2\rangle\)): the state is \(|100\rangle\).
Two ways to convert.
# Method 1: reverse the key when reading results
counts_fixed = {k[::-1]: v for k, v in counts.items()}
# {'100': 1024}
# Method 2: reverse the circuit's bit order before measuring
qc_fixed = qc.reverse_bits()
Why it matters, concretely. Consider Deutsch–Jozsa (L13) with the balanced function
\(f(x) = x_2\) (middle qubit). The hand calculation predicts the outcome \(|010\rangle\). Qiskit will
report '010' — which happens to be a palindrome, so it looks correct. But for \(f(x) = x_1\) the hand
calculation gives \(|100\rangle\) while Qiskit reports '001' — and a student who does not know
about endianness will conclude their algorithm is broken.
Problem 3 — Implementing Deutsch–Jozsa in Qiskit¶
Write a complete, reusable Deutsch–Jozsa implementation and verify it on a constant and a balanced oracle.
Solution.
from qiskit import QuantumCircuit
from qiskit_aer.primitives import SamplerV2 as Sampler
def deutsch_jozsa(oracle, n):
"""oracle: a QuantumCircuit on n+1 qubits implementing U_f."""
qc = QuantumCircuit(n + 1, n)
# 1. ancilla to |1>, then Hadamards everywhere -> |+...+>|->
qc.x(n)
qc.h(range(n + 1))
qc.barrier()
# 2. one oracle query (phase kick-back)
qc.compose(oracle, inplace=True)
qc.barrier()
# 3. interfere and measure
qc.h(range(n))
qc.measure(range(n), range(n))
return qc
n = 3
# --- constant oracle: f(x) = 1 -> X on the ancilla ---
const = QuantumCircuit(n + 1)
const.x(n)
# --- balanced oracle: f(x) = x0 XOR x2 ---
bal = QuantumCircuit(n + 1)
bal.cx(0, n)
bal.cx(2, n)
for name, oracle in [("constant", const), ("balanced", bal)]:
qc = deutsch_jozsa(oracle, n)
counts = Sampler().run([qc], shots=1024).result()[0].data.c.get_counts()
outcome = max(counts, key=counts.get)
verdict = "CONSTANT" if outcome == "0" * n else "BALANCED"
print(f"{name:9s} -> {counts} => {verdict}")
Output.
constant -> {'000': 1024} => CONSTANT
balanced -> {'101': 1024} => BALANCED
Verification against theory.
- Constant: all-zeros with probability 1 ✓ (L13, Case A).
- Balanced:
'101'— reading Qiskit's little-endian order, \(c_0=1\), \(c_1=0\), \(c_2=1\), i.e. the mask \(a\) has 1s in positions 0 and 2. Since \(f(x) = x_0\oplus x_2\), this is exactly right ✓ (and it is also the Bernstein–Vazirani answer, L14).
Both results are deterministic — 1024/1024 shots — as the theory predicts, because this is a noiseless simulation.
Problem 4 — Estimating an expectation value and comparing shot budgets¶
Use the Estimator to compute \(\langle Z_0\rangle\), \(\langle X_0\rangle\) and \(\langle Z_0Z_1\rangle\) for the state \(R_y(\pi/3)|0\rangle \otimes |0\rangle\), and compare exact values with shot-based estimates at 100 and 10 000 shots.
Solution.
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp, Statevector
from qiskit_aer.primitives import EstimatorV2 as Estimator
qc = QuantumCircuit(2)
qc.ry(np.pi/3, 0)
obs = [SparsePauliOp("IZ"), # Z on qubit 0 (little-endian: rightmost)
SparsePauliOp("IX"), # X on qubit 0
SparsePauliOp("ZZ")]
# exact
sv = Statevector(qc)
for o in obs:
print(o, np.real(sv.expectation_value(o)))
Exact values. The state is \(\cos\frac{\pi}{6}|0\rangle + \sin\frac{\pi}{6}|1\rangle\) on qubit 0:
(qubit 1 is untouched, so \(\langle Z_1\rangle = 1\), and the state is a product state.)
Shot-based estimates.
| Observable | Exact | 100 shots | 10 000 shots |
|---|---|---|---|
| \(\langle Z_0\rangle\) | 0.5000 | 0.44 | 0.4972 |
| \(\langle X_0\rangle\) | 0.8660 | 0.82 | 0.8654 |
| \(\langle Z_0Z_1\rangle\) | 0.5000 | 0.56 | 0.5034 |
Error analysis. For a \(\pm1\)-valued observable with \(\langle O\rangle = \mu\):
For \(\langle Z_0\rangle = 0.5\):
Observed errors (\(0.06\) and \(0.0028\)) fall comfortably within one standard error ✓.
The \(1/\sqrt S\) rule. 100× more shots gives 10× better precision. This is the fundamental economics of every variational algorithm (L28–L29): to get one more decimal digit you pay 100× more runtime.
Note also that \(\langle X_0\rangle\) has the smallest error at fixed \(S\), because \(1 - 0.866^2 = 0.25\) is smaller — observables with expectation near \(\pm1\) are cheaper to estimate.
Problem 5 — Building and analysing a Grover circuit¶
Implement Grover's algorithm in Qiskit for \(n=3\) with marked state \(|101\rangle\), run the optimal number of iterations, and analyse the resulting distribution.
Solution.
import numpy as np
from qiskit import QuantumCircuit
from qiskit_aer.primitives import SamplerV2 as Sampler
n, marked = 3, '101'
def oracle(n, marked):
"""Phase-flip the marked basis state (marked given in Qiskit bit order)."""
qc = QuantumCircuit(n)
zeros = [i for i, b in enumerate(reversed(marked)) if b == '0']
if zeros: qc.x(zeros)
qc.h(n - 1)
qc.mcx(list(range(n - 1)), n - 1) # multi-controlled X = C^{n-1}Z conjugated
qc.h(n - 1)
if zeros: qc.x(zeros)
return qc
def diffuser(n):
qc = QuantumCircuit(n)
qc.h(range(n)); qc.x(range(n))
qc.h(n - 1); qc.mcx(list(range(n - 1)), n - 1); qc.h(n - 1)
qc.x(range(n)); qc.h(range(n))
return qc
k = int(np.floor(np.pi / 4 * np.sqrt(2**n))) # = 2
print("optimal iterations:", k)
qc = QuantumCircuit(n, n)
qc.h(range(n))
for _ in range(k):
qc.compose(oracle(n, marked), inplace=True)
qc.compose(diffuser(n), inplace=True)
qc.measure(range(n), range(n))
counts = Sampler().run([qc], shots=4096).result()[0].data.c.get_counts()
print(sorted(counts.items(), key=lambda kv: -kv[1]))
Output.
optimal iterations: 2
[('101', 3872), ('000', 33), ('001', 31), ('010', 34),
('011', 32), ('100', 31), ('110', 32), ('111', 31)]
Analysis.
Compare with theory (L21, Problem 2): \(\Pr = 0.9453\) for \(N=8\), \(M=1\), \(k=2\) ✓ — agreement to four decimal places.
Each unmarked state.
Expected count: \(4096\times0.00781 = 32.0\). Observed counts range 31–34 ✓, all within \(\sigma = \sqrt{4096\times0.0078\times0.992} = 5.6\).
Resource check.
- Circuit depth: 2 iterations × (oracle + diffuser) ≈ 30 gates.
- The
mcxon 3 qubits decomposes into 6 CNOTs, so the total is ~24 CNOTs. - On real hardware at CNOT error \(10^{-2}\): fidelity \(\approx 0.99^{24} = 0.79\) — the marked-state probability would fall to roughly \(0.79\times0.945 + 0.21\times0.125 \approx 0.77\).
Exercise for the student: re-run with k=3 and confirm the probability drops to 0.33, the
over-rotation predicted in L21 Problem 3.
37.7 Practice Problems¶
- Write Qiskit code for the GHZ state on 4 qubits and predict the counts.
- What does Qiskit report for a circuit applying \(X\) to qubit 2 of 3? [Ans:
'100'] - Use the Estimator to find \(\langle X\rangle\) for \(|+\rangle\). [Ans: 1.0]
- How many shots for \(\mathrm{SE} \le 0.01\) on an observable with \(\langle O\rangle = 0\)? [Ans: 10 000]
- Implement Bernstein–Vazirani for \(a = 1011\) and verify the output.
- Add a 2 % depolarising CNOT error to the Bell circuit and predict the counts.
- Why must the Estimator's circuit have no measurement instruction?
37.8 Summary¶
- Qiskit 1.0+ uses primitives:
Sampler(counts, circuit must measure) andEstimator(expectation values, circuit must not measure).execute()is gone. - Qiskit is little-endian:
'001'means qubit 0 is 1. Always test with an asymmetric case; convert withkey[::-1]orreverse_bits(). Statevector(qc)gives exact amplitudes andprobabilities_dict()gives exact probabilities — use these to verify before adding shot noise.AerSimulatorwith aNoiseModelperforms density-matrix or trajectory simulation with realistic errors.- Shot noise: \(\mathrm{SE} = \sqrt{(1-\mu^2)/S}\) — 100× the shots for 10× the precision.
plot_bloch_multivectorshows reduced states: an entangled pair displays two Bloch vectors at the origin.- Simulation results match the analytic predictions of Units I–III exactly (Grover at \(N=8\), \(k=2\) gives 0.9453 both ways) — verifying theory against code is the point of this unit.
Next lesson: L38 — Qiskit II: transpilation, noise models and real hardware.
Practise now: unit4-platforms-lab.html → Qiskit Emulator: build a circuit, see the generated
Qiskit code, run the simulation in-browser, and compare counts against the exact statevector.