Demo 3:不可克隆¶
可视化:双图:保真度+Bob Bloch 长度 —— CNOT 克隆机对 9 态保真度 vs B-H 上界
对应教程:第 7 章 量子信息 中相关小节 · 依赖安装:pip install "unified-quantum[visualization,simulation]"
实现要点¶
核心:用 CNOT 作为"克隆机"对输入态 |ψ(θ)> = RY(θ)|0> 做 1→2 克隆。 Alice 的纯态保持完整 Bloch 矢量;Bob 在 CNOT 之后是 Z-对角混合态:
Bob 的约化态 = cos²(θ/2)|0⟩⟨0| + sin²(θ/2)|1⟩⟨1| → Bob 的 ⟨Z⟩ = cos θ,⟨X⟩ = ⟨Y⟩ = 0 → Bloch 矢量长度 = |cos θ|
当 θ = π/2(|+⟩)时 Bob 彻底失相干(Bob Bloch 长度 = 0), 保真度 F = ⟨ψ_in | ρ_Bob | ψ_in⟩ = cos⁴(θ/2) + sin⁴(θ/2) 在 |+⟩ 处取 1/2。 Bužek-Hillary 最优通用克隆机上限为恒定 5/6 ≈ 0.833。
注:本后端单独测量 q1 时 key 格式不一致,所以这里通过同时测量两比特 并取 Bob (q1) 的 Z 期望 ⟨Z⟩_B = P(Bob=0) − P(Bob=1) 验证。
完整源码¶
demos/ch07-quantum-info/03_no_cloning.py¶
1"""
2ch07-quantum-info demo 3: no-cloning theorem demonstration
3
4对应教程:chenzhaoyun.com/quantum-tutorial/chch07-quantum-info/03-no-cloning.html
5依赖:pip install unified-quantum[visualization]
6运行:python demos/ch07-quantum-info/03_no_cloning.py
7
8核心:用 CNOT 作为"克隆机"对输入态 |ψ(θ)> = RY(θ)|0> 做 1→2 克隆。
9Alice 的纯态保持完整 Bloch 矢量;Bob 在 CNOT 之后是 Z-对角混合态:
10
11 Bob 的约化态 = cos²(θ/2)|0⟩⟨0| + sin²(θ/2)|1⟩⟨1|
12 → Bob 的 ⟨Z⟩ = cos θ,⟨X⟩ = ⟨Y⟩ = 0
13 → Bloch 矢量长度 = |cos θ|
14
15当 θ = π/2(|+⟩)时 Bob 彻底失相干(Bob Bloch 长度 = 0),
16保真度 F = ⟨ψ_in | ρ_Bob | ψ_in⟩ = cos⁴(θ/2) + sin⁴(θ/2) 在 |+⟩ 处取 1/2。
17Bužek-Hillary 最优通用克隆机上限为恒定 5/6 ≈ 0.833。
18
19注:本后端单独测量 q1 时 key 格式不一致,所以这里通过同时测量两比特
20 并取 Bob (q1) 的 Z 期望 ⟨Z⟩_B = P(Bob=0) − P(Bob=1) 验证。
21"""
22
23from __future__ import annotations
24
25from pathlib import Path
26
27import matplotlib
28matplotlib.use("Agg")
29import matplotlib.pyplot as plt
30import numpy as np
31
32from uniqc import Circuit, submit_task, wait_for_result
33
34OUT = Path(__file__).parent
35SHOTS = 2000
36
37
38# === 1. 单 qubit 制备 + 三基期望(Alice 用,对比基线) ===
39def measure_alice(prep_fn, basis: str, shots: int = SHOTS) -> float:
40 c = Circuit()
41 prep_fn(c)
42 if basis == "X":
43 c.h(0)
44 elif basis == "Y":
45 c.sdg(0)
46 c.h(0)
47 c.measure(0)
48 r = wait_for_result(submit_task(c, backend="dummy:local:simulator", shots=shots))
49 p0 = r.probabilities.get("0", 0.0)
50 return 2.0 * p0 - 1.0
51
52
53def prep_ry(theta: float):
54 def f(c: Circuit) -> None:
55 c.ry(0, theta)
56 return f
57
58
59# === 2. Bob 的 ⟨Z⟩ 同时测两比特,按 bitstring 反向约定取 q1 位 ===
60def bob_z_expectation(theta: float, shots: int = SHOTS) -> float:
61 """CNOT(q0,q1)|ψ⟩|0⟩ 后同时测两比特,从联合分布里拿 ⟨Z⟩_Bob。"""
62 c = Circuit()
63 c.ry(0, theta)
64 c.cnot(0, 1)
65 c.measure(0)
66 c.measure(1)
67 r = wait_for_result(submit_task(c, backend="dummy:local:simulator", shots=shots))
68 p1_zero = sum(v for k, v in r.counts.items() if k[0] == "0") / shots
69 # bitstring[0] = q[1] = Bob → k[0] == '0' 即 Bob=0
70 return 2.0 * p1_zero - 1.0
71
72
73# === 3. 扫描 9 个 θ ===
74thetas = np.linspace(0.0, np.pi, 9)
75alice_bloch = np.zeros((len(thetas), 3))
76bob_z = np.zeros(len(thetas))
77
78print("ch07-quantum-info demo 3: no-cloning via CNOT cloner")
79print(f" scanning {len(thetas)} input states; "
80 "per state: 3 Alice-basis circuits + 1 joint-meas Bob circuit")
81
82for i, theta in enumerate(thetas):
83 prep = prep_ry(theta)
84 alice_bloch[i] = np.array([measure_alice(prep, b) for b in ("X", "Y", "Z")])
85 bob_z[i] = bob_z_expectation(theta)
86 fid = 0.5 * (1.0 + alice_bloch[i, 0] * 0.0
87 + alice_bloch[i, 1] * 0.0
88 + alice_bloch[i, 2] * bob_z[i])
89 print(f" θ={theta:5.2f} rad ({np.degrees(theta):5.1f}°): "
90 f"Alice Bloch=({alice_bloch[i, 0]:+.3f}, {alice_bloch[i, 1]:+.3f}, "
91 f"{alice_bloch[i, 2]:+.3f}) "
92 f"Bob ⟨Z⟩={bob_z[i]:+.3f} F={fid:.3f}")
93
94
95# === 4. 理论曲线 ===
96thetas_fine = np.linspace(0.0, np.pi, 200)
97# Alice(输入)Bloch = (sin θ, 0, cos θ)
98alice_theory = np.column_stack([np.sin(thetas_fine),
99 np.zeros_like(thetas_fine),
100 np.cos(thetas_fine)])
101alice_length = np.linalg.norm(alice_theory, axis=1) # = 1
102# Bob:⟨Z⟩ = cos θ,⟨X⟩ = ⟨Y⟩ = 0
103bob_z_theory = np.cos(thetas_fine)
104bob_length = np.abs(bob_z_theory)
105# CNOT 克隆保真度(纯输入态与 Bob 约化态的内积)
106cnot_fidelity = 0.5 * (1.0 + bob_z_theory * np.cos(thetas_fine)) # = (1+cos²θ)/2
107# 恒等 cloner (Bob 始终 |0>):F = cos²(θ/2)
108identity_fidelity = np.cos(thetas_fine / 2.0) ** 2
109# Bužek-Hillary 上界
110bh_fidelity = 5.0 / 6.0
111
112
113# === 5. 画 2 子图 ===
114fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13.0, 5.2))
115
116# 左图:保真度 vs 输入角度
117ax1.plot(np.degrees(thetas_fine), cnot_fidelity,
118 color="#1f77b4", lw=2.4, label=r"CNOT cloner $F = (1+\cos^2\theta)/2$")
119ax1.plot(np.degrees(thetas_fine), identity_fidelity,
120 color="#888888", lw=2.0, ls="--", label=r"identity $F = \cos^2(\theta/2)$")
121ax1.axhline(bh_fidelity, color="#d62728", lw=2.0, ls=":",
122 label=r"B$\check{\rm u}$zek-Hillary bound $F_\max = 5/6$")
123# 经验点
124fid_emp = 0.5 * (1.0 + alice_bloch[:, 2] * bob_z)
125ax1.scatter(np.degrees(thetas), fid_emp, color="#1f77b4", s=60, zorder=10,
126 edgecolor="black", linewidth=0.7)
127mid = len(thetas_fine) // 2
128ax1.annotate("|+\u27e9 input\nBob = I/2, F = 1/2",
129 xy=(90.0, cnot_fidelity[mid]),
130 xytext=(40, 0.62),
131 arrowprops=dict(arrowstyle="->", color="#444"),
132 fontsize=10)
133ax1.annotate("perfect Z-eigenstate\nclone, F = 1",
134 xy=(0.0, 1.0), xytext=(22, 0.78),
135 arrowprops=dict(arrowstyle="->", color="#444"),
136 fontsize=10)
137ax1.set_xlabel("input state parameter θ (deg)")
138ax1.set_ylabel("cloning fidelity F = ⟨ψ_in | ρ_Bob | ψ_in⟩")
139ax1.set_title("CNOT cloner fidelity vs input angle")
140ax1.set_ylim(0.35, 1.05)
141ax1.set_xlim(0, 180)
142ax1.grid(alpha=0.3)
143ax1.legend(loc="upper right", fontsize=9)
144
145# 右图:Bob 与 Alice 的 Bloch 矢量长度
146ax2.plot(np.degrees(thetas_fine), alice_length,
147 color="#2ca02c", lw=2.4, label="Alice |ψ_in⟩ (pure, |n| = 1 always)")
148ax2.plot(np.degrees(thetas_fine), bob_length,
149 color="#ff7f0e", lw=2.4, label=r"Bob (CNOT → dephased, |n| = |cos θ|)")
150ax2.fill_between(np.degrees(thetas_fine), bob_length, alice_length,
151 color="#ffe6cc", alpha=0.45,
152 label="fidelity gap (mixedness penalty)")
153# 经验 Bob 长度
154bob_len_emp = np.abs(bob_z)
155ax2.scatter(np.degrees(thetas), np.full_like(thetas, 1.0),
156 color="#2ca02c", s=40, zorder=10, edgecolor="black",
157 label="Alice (measured)")
158ax2.scatter(np.degrees(thetas), bob_len_emp,
159 color="#ff7f0e", s=40, zorder=10, edgecolor="black",
160 label="Bob ⟨Z⟩ (measured)")
161ax2.set_xlabel("input state parameter θ (deg)")
162ax2.set_ylabel("Bloch vector length |⟨σ⟩|")
163ax2.set_title("Information preserved in Bob's qubit")
164ax2.set_ylim(-0.05, 1.15)
165ax2.set_xlim(0, 180)
166ax2.grid(alpha=0.3)
167ax2.legend(loc="upper right", fontsize=8)
168
169plt.suptitle("ch07 no-cloning — CNOT as 1→2 cloner: succeeds only on computational basis",
170 fontsize=13, y=1.01)
171plt.tight_layout()
172out = OUT / "03_no_cloning.png"
173plt.savefig(out, dpi=120, bbox_inches="tight")
174plt.close()
175
176# === 6. stdout 关键统计 ===
177print()
178print(f" CNOT cloner fidelity min = {cnot_fidelity.min():.4f} "
179 f"max = {cnot_fidelity.max():.4f}")
180print(f" Buzek-Hillary optimal bound F_max = {bh_fidelity:.4f}")
181print(f" Bob Bloch length at |+>: {bob_length[mid]:.4f} (theory 0)")
182print(f" Empirical fidelity spread: "
183 f"{fid_emp.min():.3f} ~ {fid_emp.max():.3f}")
184print(f" Empirical Bob Z spread: {bob_z.min():+.3f} ~ {bob_z.max():+.3f}")
185print(f" PNG -> {out}")
运行结果¶

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