Demo 2:Gibbs 态制备

第 6 章 量子科学计算 · 本章演示 · 代码演示总索引

可视化:单子图(4 柱对比) —— 4 β 扫描的 P(|00⟩)=1/Z 反推

对应教程:第 6 章 量子科学计算 中相关小节 · 依赖安装:pip install "unified-quantum[visualization,simulation]"

实现要点

给定 H = diag(0, 1, 2, 3) 和逆温 beta,用 uniqc.rotation_prepare 直接将 Boltzmann 分布 |psi> = sum_j sqrt(e^{-beta E_j}/Z) |j> 装到 2 个 qubit 上。 扫描 beta 从低温到高温,展示不同温度下的概率分布与 H 矩阵本征结构。

完整源码

demos/ch06-scientific-computing/02_gibbs_state.py
  1"""
  2ch06 演示 2:2-qubit Gibbs 热态制备
  3
  4对应教程:chenzhaoyun.com/quantum-tutorial/ch06-scientific-computing/gibbs-state.html
  5依赖:pip install unified-quantum[visualization]
  6运行:python demos/ch06-scientific-computing/02_gibbs_state.py
  7
  8给定 H = diag(0, 1, 2, 3) 和逆温 beta,用 uniqc.rotation_prepare 直接将
  9Boltzmann 分布 |psi> = sum_j sqrt(e^{-beta E_j}/Z) |j> 装到 2 个 qubit 上。
 10扫描 beta 从低温到高温,展示不同温度下的概率分布与 H 矩阵本征结构。
 11"""
 12from __future__ import annotations
 13
 14from pathlib import Path
 15
 16import matplotlib
 17matplotlib.use("Agg")
 18import matplotlib.pyplot as plt
 19import numpy as np
 20
 21from uniqc import Circuit, rotation_prepare, submit_task, wait_for_result
 22
 23OUT = Path(__file__).parent
 24
 25# --------------------------------------------------------------------------
 26# 1) 问题设定:H = diag(0, 1, 2, 3),扫描 beta
 27# --------------------------------------------------------------------------
 28H_diag = np.array([0.0, 1.0, 2.0, 3.0])
 29betas = [0.3, 1.0, 2.0, 4.0]
 30n_shots = 4000
 31
 32# 解析理论分布
 33def gibbs_probs(beta):
 34    weights = np.exp(-beta * H_diag)
 35    return weights / weights.sum()
 36
 37
 38# --------------------------------------------------------------------------
 39# 2) 对每个 beta 跑 uniqc,统计测量结果
 40# --------------------------------------------------------------------------
 41measured = {}
 42for beta in betas:
 43    target = np.sqrt(gibbs_probs(beta)).astype(complex)
 44    c = Circuit()
 45    rotation_prepare(c, target, qubits=[0, 1])
 46    c.measure(0)
 47    c.measure(1)
 48    task_id = submit_task(circuit=c, backend="dummy:local:simulator", shots=n_shots)
 49    result = wait_for_result(task_id)
 50    counts = result.counts
 51    total = sum(counts.values())
 52    measured[beta] = np.array([counts.get(bs, 0) / total
 53                               for bs in ("00", "01", "10", "11")])
 54
 55# --------------------------------------------------------------------------
 56# 3) 可视化
 57# --------------------------------------------------------------------------
 58fig, axes = plt.subplots(1, len(betas), figsize=(4 * len(betas), 4.2),
 59                         sharey=True)
 60
 61labels = [r"$|00\rangle$", r"$|01\rangle$", r"$|10\rangle$", r"$|11\rangle$"]
 62x_pos = np.arange(4)
 63w = 0.4
 64
 65for ax, beta in zip(axes, betas):
 66    probs_th = gibbs_probs(beta)
 67    probs_emp = measured[beta]
 68    ax.bar(x_pos - w / 2, probs_th, w, label="theory e^{-beta E}/Z",
 69           color="steelblue", alpha=0.85)
 70    ax.bar(x_pos + w / 2, probs_emp, w,
 71           label=f"uniqc shots ({n_shots})", color="coral", alpha=0.85)
 72    ax.set_xticks(x_pos)
 73    ax.set_xticklabels(labels, fontsize=9)
 74    ax.set_title(f"beta = {beta}")
 75    ax.set_ylim(0, 1.05)
 76    ax.grid(True, alpha=0.3, axis="y")
 77    ax.legend(fontsize=7, loc="upper right")
 78    # annotate max
 79    j_max = int(np.argmax(probs_th))
 80    ax.text(j_max, 0.95, f"E={H_diag[j_max]:.0f}", ha="center", fontsize=8)
 81
 82axes[0].set_ylabel("probability")
 83
 84fig.suptitle("2-qubit Gibbs state: H = diag(0, 1, 2, 3)\n"
 85             "rotation_prepare loads sqrt(e^{-beta E_j}/Z) onto |00>, |01>, |10>, |11>",
 86             fontsize=11)
 87plt.tight_layout(rect=(0, 0, 1, 0.94))
 88plt.savefig(OUT / "02_gibbs_state.png", dpi=120, bbox_inches="tight")
 89plt.close()
 90
 91# --------------------------------------------------------------------------
 92# 4) stdout 关键统计
 93# --------------------------------------------------------------------------
 94print("ch06-demo-2: 2-qubit Gibbs state via rotation_prepare")
 95print(f"  H eigenvalues (computational basis): {H_diag.tolist()}")
 96print(f"  shots per beta: {n_shots}")
 97for beta in betas:
 98    probs_th = gibbs_probs(beta)
 99    probs_emp = measured[beta]
100    err = np.abs(probs_th - probs_emp).max()
101    print(f"  beta={beta}: theory p00={probs_th[0]:.3f}, p01={probs_th[1]:.3f}, "
102          f"p10={probs_th[2]:.3f}, p11={probs_th[3]:.3f}  max|err|={err:.4f}")

运行结果

Demo 2:Gibbs 态制备

运行方式

# 仓库根目录执行;输出 PNG 到 demos/ch06-scientific-computing/02_gibbs_state.png,关键统计到 stdout
.venv/bin/python3 demos/ch06-scientific-computing/02_gibbs_state.py

← 本章演示 · ↑ 代码演示总索引 · ⌂ 教程门户