Demo 3:Bell 态¶
可视化:4 子图柱状 —— 4 个 Bell 态联合测量直方图
对应教程:第 1 章 量子计算基础 中相关小节 · 依赖安装:pip install "unified-quantum[visualization,simulation]"
实现要点¶
制备 |Phi+> = H(0) CNOT(0,1)、|Phi-> = ... Z(1)、 |Psi+> = ... X(1)、|Psi-> = ... X(1) Z(1) 每个态 1000 shots,画 4 个子图横向并排。
完整源码¶
demos/ch01-basics/03_bell_state.py¶
1"""
2ch01-basics demo 3:四个 Bell 态制备与测量
3
4对应教程:chenzhaoyun.com/quantum-tutorial/chch01-basics/03-bell-state.html
5依赖:pip install unified-quantum[visualization]
6运行:python demos/ch01-basics/03_bell_state.py
7
8制备 |Phi+> = H(0) CNOT(0,1)、|Phi-> = ... Z(1)、
9 |Psi+> = ... X(1)、|Psi-> = ... X(1) Z(1)
10每个态 1000 shots,画 4 个子图横向并排。
11"""
12
13from uniqc import Circuit, submit_task, wait_for_result
14import matplotlib
15matplotlib.use("Agg")
16import matplotlib.pyplot as plt
17import numpy as np
18from pathlib import Path
19
20OUT = Path(__file__).parent
21
22SHOTS = 1000
23
24
25def run_bell(extra):
26 """extra: list of (gate, qubit) applied after the Bell pair."""
27 c = Circuit()
28 c.h(0)
29 c.cnot(0, 1)
30 for gate, q in extra:
31 if gate == "x":
32 c.x(q)
33 elif gate == "z":
34 c.z(q)
35 c.measure(0)
36 c.measure(1)
37 tid = submit_task(circuit=c, backend="dummy:local:simulator", shots=SHOTS)
38 return wait_for_result(tid).counts
39
40
41# === 1. Four Bell-state preparations ===
42SCENARIOS = [
43 ("|Phi+> = (|00>+|11>)/sqrt(2)", []),
44 ("|Phi-> = (|00>-|11>)/sqrt(2)", [("z", 1)]),
45 ("|Psi+> = (|01>+|10>)/sqrt(2)", [("x", 1)]),
46 ("|Psi-> = (|01>-|10>)/sqrt(2)", [("x", 1), ("z", 1)]),
47]
48
49BASIS_LABELS = ["00", "01", "10", "11"]
50all_counts = []
51for name, extra in SCENARIOS:
52 counts = run_bell(extra)
53 all_counts.append((name, counts))
54 total = sum(counts.values())
55 dom = max(counts, key=counts.get)
56 print(f" {name:38s} total={total} dominant={dom} "
57 f"({counts[dom]/total:.3f})")
58
59# === 2. 4 horizontal subplots ===
60fig, axes = plt.subplots(1, 4, figsize=(15, 4), sharey=True)
61colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"]
62
63for ax, (name, counts), color in zip(axes, all_counts, colors):
64 probs = [counts.get(k, 0) / SHOTS for k in BASIS_LABELS]
65 bars = ax.bar(BASIS_LABELS, probs, color=color, alpha=0.85)
66 for b, p in zip(bars, probs):
67 ax.text(b.get_x() + b.get_width() / 2, p + 0.01, f"{p:.2f}",
68 ha="center", va="bottom", fontsize=9)
69 # Split title: name on top, kets smaller
70 ax.set_title(name, fontsize=10)
71 ax.set_ylim(0, 1.1)
72 ax.grid(axis="y", alpha=0.3)
73 ax.set_xlabel("two-bit outcome", fontsize=9)
74
75axes[0].set_ylabel("Probability", fontsize=11)
76fig.suptitle(f"Four Bell states — measurement histograms "
77 f"(shots={SHOTS})", fontsize=13, y=1.02)
78plt.tight_layout()
79plt.savefig(OUT / "03_bell_state.png", dpi=120, bbox_inches="tight")
80plt.close()
81
82# === 3. stdout 关键统计 ===
83print("ch01-basics-demo-3: four Bell states measured in Z basis")
84print(f" shots per Bell state: {SHOTS}, total shots: {SHOTS * 4}")
85print(f" expected: each state shows exactly 2 peaks at 50% (noise-free)")
86peak_share = [
87 sum(c.values()) for _, c in all_counts
88]
89peak_purity = [
90 (max(c.values()) + sorted(c.values())[-2]) / sum(c.values())
91 for _, c in all_counts
92]
93print(f" 2-peak concentration: "
94 f"{[f'{p:.3f}' for p in peak_purity]}")
运行结果¶

运行方式¶
# 仓库根目录执行;输出 PNG 到 demos/ch01-basics/03_bell_state.png,关键统计到 stdout
.venv/bin/python3 demos/ch01-basics/03_bell_state.py