In [50]:
Copied!
# 导入 DeepQuantum 和相关库
import deepquantum as dq
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# 配置 matplotlib 支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号'-'显示为方块的问题
# 设置随机种子以保证结果可复现
torch.manual_seed(42)
np.random.seed(42)
print(f"DeepQuantum version: {dq.__version__ if hasattr(dq, '__version__') else 'dev'}")
print(f"PyTorch version: {torch.__version__}")
# 导入 DeepQuantum 和相关库
import deepquantum as dq
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# 配置 matplotlib 支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号'-'显示为方块的问题
# 设置随机种子以保证结果可复现
torch.manual_seed(42)
np.random.seed(42)
print(f"DeepQuantum version: {dq.__version__ if hasattr(dq, '__version__') else 'dev'}")
print(f"PyTorch version: {torch.__version__}")
DeepQuantum version: 4.4.0 PyTorch version: 2.9.1+cpu
In [2]:
Copied!
# 创建一个单量子比特态,初始化为 |1⟩ 态
# state=[0,1] 表示振幅为 [0, 1],对应 |1⟩ 态
qstate = dq.QubitState(nqubit=1, state=[0, 1])
print("单量子比特态 |1⟩:")
print(qstate.state)
print(f"形状: {qstate.state.shape}")
# 创建一个单量子比特态,初始化为 |1⟩ 态
# state=[0,1] 表示振幅为 [0, 1],对应 |1⟩ 态
qstate = dq.QubitState(nqubit=1, state=[0, 1])
print("单量子比特态 |1⟩:")
print(qstate.state)
print(f"形状: {qstate.state.shape}")
单量子比特态 |1⟩:
tensor([[0.+0.j],
[1.+0.j]])
形状: torch.Size([2, 1])
In [3]:
Copied!
# 创建一个两量子比特态,初始化为 |00⟩ 态
qstate2 = dq.QubitState(nqubit=2, state='zeros')
print("\n两量子比特态 |00⟩:")
print(qstate2.state)
print(f"形状: {qstate2.state.shape}")
# 创建一个两量子比特态,初始化为 |00⟩ 态
qstate2 = dq.QubitState(nqubit=2, state='zeros')
print("\n两量子比特态 |00⟩:")
print(qstate2.state)
print(f"形状: {qstate2.state.shape}")
两量子比特态 |00⟩:
tensor([[1.+0.j],
[0.+0.j],
[0.+0.j],
[0.+0.j]])
形状: torch.Size([4, 1])
In [4]:
Copied!
# 创建等权叠加态(所有基态等概率叠加)
equal_state = dq.QubitState(nqubit=2, state='equal')
print("\n等权叠加态:")
print(equal_state.state)
# 创建等权叠加态(所有基态等概率叠加)
equal_state = dq.QubitState(nqubit=2, state='equal')
print("\n等权叠加态:")
print(equal_state.state)
等权叠加态:
tensor([[0.5000+0.j],
[0.5000+0.j],
[0.5000+0.j],
[0.5000+0.j]])
In [5]:
Copied!
# 创建 GHZ 态(Greenberger-Horne-Zeilinger 态)
ghz_state = dq.QubitState(nqubit=3, state='ghz')
print("\nGHZ 态:")
print(ghz_state.state)
# 创建 GHZ 态(Greenberger-Horne-Zeilinger 态)
ghz_state = dq.QubitState(nqubit=3, state='ghz')
print("\nGHZ 态:")
print(ghz_state.state)
GHZ 态:
tensor([[0.7071+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.7071+0.j]])
2.2 量子线路(QubitCircuit)¶
量子线路是 DeepQuantum 的核心对象,用于构建和执行量子算法。
In [6]:
Copied!
# 创建一个 3 量子比特的线路
cir = dq.QubitCircuit(3)
print(f"量子比特数: {cir.nqubit}")
print(f"初始状态: {cir.init_state}")
# 创建一个 3 量子比特的线路
cir = dq.QubitCircuit(3)
print(f"量子比特数: {cir.nqubit}")
print(f"初始状态: {cir.init_state}")
量子比特数: 3 初始状态: QubitState()
In [7]:
Copied!
# 创建单比特量子门
x_gate = dq.PauliX()
h_gate = dq.Hadamard()
rx_gate = dq.Rx(torch.tensor(np.pi/2))
print("Pauli X 门矩阵:")
print(x_gate.matrix)
print("\nHadamard 门矩阵:")
print(h_gate.matrix)
print("\n Rx(π/2) 门矩阵:")
print(rx_gate.matrix)
# 创建单比特量子门
x_gate = dq.PauliX()
h_gate = dq.Hadamard()
rx_gate = dq.Rx(torch.tensor(np.pi/2))
print("Pauli X 门矩阵:")
print(x_gate.matrix)
print("\nHadamard 门矩阵:")
print(h_gate.matrix)
print("\n Rx(π/2) 门矩阵:")
print(rx_gate.matrix)
Pauli X 门矩阵:
tensor([[0.+0.j, 1.+0.j],
[1.+0.j, 0.+0.j]])
Hadamard 门矩阵:
tensor([[ 0.7071+0.j, 0.7071+0.j],
[ 0.7071+0.j, -0.7071+0.j]])
Rx(π/2) 门矩阵:
tensor([[0.7071+0.0000j, -0.0000-0.7071j],
[-0.0000-0.7071j, 0.7071+0.0000j]])
In [8]:
Copied!
# 对量子态应用量子门
state = dq.QubitState(nqubit=1, state=[0, 1])
print("初始态 |1⟩:")
print(state.state)
# 应用 X 门(将 |1⟩ 变为 |0⟩)
x_state = x_gate(state.state)
print("\n应用 X 门后的态:")
print(x_state)
# 对量子态应用量子门
state = dq.QubitState(nqubit=1, state=[0, 1])
print("初始态 |1⟩:")
print(state.state)
# 应用 X 门(将 |1⟩ 变为 |0⟩)
x_state = x_gate(state.state)
print("\n应用 X 门后的态:")
print(x_state)
初始态 |1⟩:
tensor([[0.+0.j],
[1.+0.j]])
应用 X 门后的态:
tensor([[1.+0.j],
[0.+0.j]])
In [9]:
Copied!
# 在量子线路上添加量子门
cir = dq.QubitCircuit(2)
cir.h(0) # 在第 0 个量子比特上应用 H 门
cir.x(1) # 在第 1 个量子比特上应用 X 门
# 执行线路
final_state = cir()
print("最终量子态:")
print(final_state)
# 在量子线路上添加量子门
cir = dq.QubitCircuit(2)
cir.h(0) # 在第 0 个量子比特上应用 H 门
cir.x(1) # 在第 1 个量子比特上应用 X 门
# 执行线路
final_state = cir()
print("最终量子态:")
print(final_state)
最终量子态:
tensor([[0.0000+0.j],
[0.7071+0.j],
[0.0000+0.j],
[0.7071+0.j]])
3.2 双比特量子门¶
- CNOT 门:受控非门(CX)
- SWAP 门:交换两个量子比特的状态
- 旋转门:Rxx, Ryy, Rzz 等双比特旋转门
In [10]:
Copied!
# CNOT 门示例
cir = dq.QubitCircuit(2)
cir.h(0) # 创建叠加态
cir.cnot(0, 1) # CNOT,控制位为 0,目标位为 1
final_state = cir()
print("贝尔态 (|00⟩ + |11⟩)/√2:")
print(final_state)
# CNOT 门示例
cir = dq.QubitCircuit(2)
cir.h(0) # 创建叠加态
cir.cnot(0, 1) # CNOT,控制位为 0,目标位为 1
final_state = cir()
print("贝尔态 (|00⟩ + |11⟩)/√2:")
print(final_state)
贝尔态 (|00⟩ + |11⟩)/√2:
tensor([[0.7071+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.7071+0.j]])
In [17]:
Copied!
# 旋转门示例
cir = dq.QubitCircuit(2)
cir.rxx([0, 1], torch.tensor(np.pi/4)) # XX 旋转
cir.rzz([0, 1], torch.tensor(np.pi/4)) # ZZ 旋转
print("Rzz(π/4) 门的酉矩阵:")
print(cir.operators[1].get_unitary())
# 旋转门示例
cir = dq.QubitCircuit(2)
cir.rxx([0, 1], torch.tensor(np.pi/4)) # XX 旋转
cir.rzz([0, 1], torch.tensor(np.pi/4)) # ZZ 旋转
print("Rzz(π/4) 门的酉矩阵:")
print(cir.operators[1].get_unitary())
Rzz(π/4) 门的酉矩阵:
tensor([[0.9239-0.3827j, 0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j],
[0.0000+0.0000j, 0.9239+0.3827j, 0.0000+0.0000j, 0.0000+0.0000j],
[0.0000+0.0000j, 0.0000+0.0000j, 0.9239+0.3827j, 0.0000+0.0000j],
[0.0000+0.0000j, 0.0000+0.0000j, 0.0000+0.0000j, 0.9239-0.3827j]])
In [12]:
Copied!
# Toffoli 门(CCX)示例
cir = dq.QubitCircuit(3)
cir.x(0)
cir.x(1)
cir.toffoli(0, 1, 2) # 控制位为 0 和 1,目标位为 2
final_state = cir()
print("应用 Toffoli 门后的状态:")
print(final_state)
# Toffoli 门(CCX)示例
cir = dq.QubitCircuit(3)
cir.x(0)
cir.x(1)
cir.toffoli(0, 1, 2) # 控制位为 0 和 1,目标位为 2
final_state = cir()
print("应用 Toffoli 门后的状态:")
print(final_state)
应用 Toffoli 门后的状态:
tensor([[0.+0.j],
[0.+0.j],
[0.+0.j],
[0.+0.j],
[0.+0.j],
[0.+0.j],
[0.+0.j],
[1.+0.j]])
In [13]:
Copied!
# 创建参数化电路
cir = dq.QubitCircuit(4)
# 添加参数化旋转门(不指定参数,会自动初始化)
cir.rx(0) # 在第 0 个量子比特上添加 Rx 门
cir.ry(1) # 在第 1 个量子比特上添加 Ry 门
cir.rz(2) # 在第 2 个量子比特上添加 Rz 门
# 添加参数化双比特门
cir.rxx([1, 2]) # 在量子比特 1 和 2 上添加 Rxx 门
# 打印电路参数
print("参数化电路结构:")
print(cir)
# 创建参数化电路
cir = dq.QubitCircuit(4)
# 添加参数化旋转门(不指定参数,会自动初始化)
cir.rx(0) # 在第 0 个量子比特上添加 Rx 门
cir.ry(1) # 在第 1 个量子比特上添加 Ry 门
cir.rz(2) # 在第 2 个量子比特上添加 Rz 门
# 添加参数化双比特门
cir.rxx([1, 2]) # 在量子比特 1 和 2 上添加 Rxx 门
# 打印电路参数
print("参数化电路结构:")
print(cir)
参数化电路结构:
QubitCircuit(
(init_state): QubitState()
(operators): Sequential(
(0): Rx(wires=[0], theta=11.086922645568848)
(1): Ry(wires=[1], theta=11.498279571533203)
(2): Rz(wires=[2], theta=4.811208248138428)
(3): Rxx(wires=[1, 2], theta=12.054990768432617)
)
(observables): ModuleList()
)
In [14]:
Copied!
# 查看参数值
for name, param in cir.named_parameters():
if 'theta' in name or 'phi' in name:
print(f"{name}: {param.item():.4f}")
# 查看参数值
for name, param in cir.named_parameters():
if 'theta' in name or 'phi' in name:
print(f"{name}: {param.item():.4f}")
operators.0.theta: 11.0869 operators.1.theta: 11.4983 operators.2.theta: 4.8112 operators.3.theta: 12.0550
4.1 参数化层¶
DeepQuantum 提供了便捷的方法来添加一层量子门。
In [15]:
Copied!
# 使用层操作
cir = dq.QubitCircuit(4)
# Hadamard 层(在所有量子比特上应用 H 门)
cir.hlayer()
# Rx 层(在所有量子比特上添加 Rx 门)
cir.rxlayer()
# CNOT 环(将量子比特连接成环状)
cir.cnot_ring()
cir.draw()
# 使用层操作
cir = dq.QubitCircuit(4)
# Hadamard 层(在所有量子比特上应用 H 门)
cir.hlayer()
# Rx 层(在所有量子比特上添加 Rx 门)
cir.rxlayer()
# CNOT 环(将量子比特连接成环状)
cir.cnot_ring()
cir.draw()
4.2 自定义参数¶
你可以为参数化门指定具体的参数值。
In [18]:
Copied!
# 指定参数值
theta = torch.tensor(np.pi/3, requires_grad=True)
phi = torch.tensor(np.pi/4, requires_grad=True)
cir = dq.QubitCircuit(2)
cir.rx(0, theta) # 指定参数 theta
cir.ry(1, phi) # 指定参数 phi
cir.cnot(0, 1)
print(f"Rx 参数 theta: {theta.item():.4f}")
print(f"Ry 参数 phi: {phi.item():.4f}")
# 执行线路
state = cir()
print("\n最终量子态:")
print(state)
# 指定参数值
theta = torch.tensor(np.pi/3, requires_grad=True)
phi = torch.tensor(np.pi/4, requires_grad=True)
cir = dq.QubitCircuit(2)
cir.rx(0, theta) # 指定参数 theta
cir.ry(1, phi) # 指定参数 phi
cir.cnot(0, 1)
print(f"Rx 参数 theta: {theta.item():.4f}")
print(f"Ry 参数 phi: {phi.item():.4f}")
# 执行线路
state = cir()
print("\n最终量子态:")
print(state)
Rx 参数 theta: 1.0472
Ry 参数 phi: 0.7854
最终量子态:
tensor([[0.8001+0.0000j],
[0.3314+0.0000j],
[0.0000-0.1913j],
[0.0000-0.4619j]], grad_fn=<SqueezeBackward1>)
In [19]:
Copied!
# 自定义量子态
amplitudes = torch.tensor([0.6, 0.8], dtype=torch.complex128)
custom_state = dq.QubitState(nqubit=1, state=amplitudes)
print("自定义量子态:")
print(custom_state.state)
print(f"归一化系数: {torch.norm(custom_state.state):.4f}")
# 自定义量子态
amplitudes = torch.tensor([0.6, 0.8], dtype=torch.complex128)
custom_state = dq.QubitState(nqubit=1, state=amplitudes)
print("自定义量子态:")
print(custom_state.state)
print(f"归一化系数: {torch.norm(custom_state.state):.4f}")
自定义量子态:
tensor([[0.6000+0.j],
[0.8000+0.j]], dtype=torch.complex128)
归一化系数: 1.0000
5.2 量子测量¶
测量是量子计算中获取信息的关键步骤。
In [26]:
Copied!
# 制备贝尔态并测量
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
# 先执行线路生成量子态
state = cir()
# 然后执行测量(默认 1024 次)
measurement_results = cir.measure(shots=1000)
print(measurement_results)
print("测量结果(1000 次采样):")
for bitstring, count in sorted(measurement_results.items()):
print(f" |{bitstring}⟩: {count} 次 ({count/10:.1f}%)")
# 制备贝尔态并测量
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
# 先执行线路生成量子态
state = cir()
# 然后执行测量(默认 1024 次)
measurement_results = cir.measure(shots=1000)
print(measurement_results)
print("测量结果(1000 次采样):")
for bitstring, count in sorted(measurement_results.items()):
print(f" |{bitstring}⟩: {count} 次 ({count/10:.1f}%)")
{'11': 501, '00': 499}
测量结果(1000 次采样):
|00⟩: 499 次 (49.9%)
|11⟩: 501 次 (50.1%)
In [27]:
Copied!
# 部分测量和概率显示
cir = dq.QubitCircuit(3)
cir.h(0)
cir.cnot(0, 1)
cir.cnot(0, 2)
# 先执行线路
state = cir()
# 只测量前两个量子比特,显示理论概率
results = cir.measure(shots=500, wires=[0, 1], with_prob=True)
print("部分测量结果(量子比特 0 和 1):")
for bitstring, (count, prob) in sorted(results.items()):
print(f" |{bitstring}⟩: {count} 次 (理论概率: {prob:.4f})")
# 部分测量和概率显示
cir = dq.QubitCircuit(3)
cir.h(0)
cir.cnot(0, 1)
cir.cnot(0, 2)
# 先执行线路
state = cir()
# 只测量前两个量子比特,显示理论概率
results = cir.measure(shots=500, wires=[0, 1], with_prob=True)
print("部分测量结果(量子比特 0 和 1):")
for bitstring, (count, prob) in sorted(results.items()):
print(f" |{bitstring}⟩: {count} 次 (理论概率: {prob:.4f})")
部分测量结果(量子比特 0 和 1): |00⟩: 257 次 (理论概率: 0.5000) |11⟩: 243 次 (理论概率: 0.5000)
In [29]:
Copied!
# 创建电路并添加观测器
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
# 添加观测器(在第 0 个量子比特上测量 Z 算符)
cir.observable(wires=0, basis='z')
# 计算期望值
state = cir()
print(f"末态: {state}")
expectation = cir.expectation()
print(f"Z_0 的期望值: {expectation.item():.4f}")
# 创建电路并添加观测器
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
# 添加观测器(在第 0 个量子比特上测量 Z 算符)
cir.observable(wires=0, basis='z')
# 计算期望值
state = cir()
print(f"末态: {state}")
expectation = cir.expectation()
print(f"Z_0 的期望值: {expectation.item():.4f}")
末态: tensor([[0.7071+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.7071+0.j]])
Z_0 的期望值: 0.0000
In [ ]:
Copied!
# 多个观测器
cir = dq.QubitCircuit(3)
cir.hlayer()
cir.cnot_ring()
# 在每个量子比特上添加观测器
for i in range(3):
cir.observable(wires=i, basis='z')
# 计算期望值
state = cir()
print(f"末态: {state}")
expectations = cir.expectation()
print("所有量子比特的 Z 期望值:")
#print(expectations[2])
for i, exp in enumerate(expectations):
print(f" Z_{i}: {exp.item():.4f}")
# 多个观测器
cir = dq.QubitCircuit(3)
cir.hlayer()
cir.cnot_ring()
# 在每个量子比特上添加观测器
for i in range(3):
cir.observable(wires=i, basis='z')
# 计算期望值
state = cir()
print(f"末态: {state}")
expectations = cir.expectation()
print("所有量子比特的 Z 期望值:")
#print(expectations[2])
for i, exp in enumerate(expectations):
print(f" Z_{i}: {exp.item():.4f}")
末态: tensor([[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j],
[0.3536+0.j]])
所有量子比特的 Z 期望值:
Z_0: 0.0000
Z_1: 0.0000
Z_2: 0.0000
In [36]:
Copied!
# 不同基的测量
cir = dq.QubitCircuit(2)
cir.h(0)
cir.rx(1, torch.tensor(np.pi/4))
# X, Y, Z 基测量
cir.observable(wires=0, basis='x')
cir.observable(wires=0, basis='y')
cir.observable(wires=0, basis='z')
state = cir()
expectations = cir.expectation()
print("不同基的期望值:")
print(f" X: {expectations[0].item():.4f}")
print(f" Y: {expectations[1].item():.4f}")
print(f" Z: {expectations[2].item():.4f}")
# 不同基的测量
cir = dq.QubitCircuit(2)
cir.h(0)
cir.rx(1, torch.tensor(np.pi/4))
# X, Y, Z 基测量
cir.observable(wires=0, basis='x')
cir.observable(wires=0, basis='y')
cir.observable(wires=0, basis='z')
state = cir()
expectations = cir.expectation()
print("不同基的期望值:")
print(f" X: {expectations[0].item():.4f}")
print(f" Y: {expectations[1].item():.4f}")
print(f" Z: {expectations[2].item():.4f}")
不同基的期望值: X: 1.0000 Y: 0.0000 Z: -0.0000
7. 简单示例:贝尔态制备¶
贝尔态是最大的两量子比特纠缠态。我们将制备四种贝尔态:
- |Φ⁺⟩ = (|00⟩ + |11⟩)/√2
- |Φ⁻⟩ = (|00⟩ - |11⟩)/√2
- |Ψ⁺⟩ = (|01⟩ + |10⟩)/√2
- |Ψ⁻⟩ = (|01⟩ - |10⟩)/√2
In [38]:
Copied!
# 制备 |Φ⁺⟩ = (|00⟩ + |11⟩)/√2
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
state = cir()
print("|Φ⁺⟩ 态:")
print(state)
# 验证纠缠特性
cir.observable(wires=0, basis='z')
cir.observable(wires=1, basis='z')
expectations = cir.expectation()
print(f"\nZ₀Z₁ 的期望值(纠缠度量): {expectations[0].item() * expectations[1].item():.4f}")
# 制备 |Φ⁺⟩ = (|00⟩ + |11⟩)/√2
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
state = cir()
print("|Φ⁺⟩ 态:")
print(state)
# 验证纠缠特性
cir.observable(wires=0, basis='z')
cir.observable(wires=1, basis='z')
expectations = cir.expectation()
print(f"\nZ₀Z₁ 的期望值(纠缠度量): {expectations[0].item() * expectations[1].item():.4f}")
|Φ⁺⟩ 态:
tensor([[0.7071+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.7071+0.j]])
Z₀Z₁ 的期望值(纠缠度量): 0.0000
In [39]:
Copied!
# 制备所有四种贝尔态
def create_bell_state(state_type):
"""创建贝尔态
Args:
state_type: 'phi_plus', 'phi_minus', 'psi_plus', 'psi_minus'
"""
cir = dq.QubitCircuit(2)
if state_type == 'phi_plus':
cir.h(0)
cir.cnot(0, 1)
elif state_type == 'phi_minus':
cir.h(0)
cir.cnot(0, 1)
cir.z(1)
elif state_type == 'psi_plus':
cir.h(0)
cir.x(1)
cir.cnot(0, 1)
elif state_type == 'psi_minus':
cir.h(0)
cir.x(1)
cir.cnot(0, 1)
cir.z(1)
return cir
# 测试所有贝尔态
bell_states = ['phi_plus', 'phi_minus', 'psi_plus', 'psi_minus']
bell_names = ['|Φ⁺⟩', '|Φ⁻⟩', '|Ψ⁺⟩', '|Ψ⁻⟩']
for name, state_type in zip(bell_names, bell_states):
cir = create_bell_state(state_type)
_ = cir() # 先执行线路生成量子态
results = cir.measure(shots=1000)
print(f"\n{name} 测量结果:")
for bitstring, count in sorted(results.items()):
if count > 0:
print(f" |{bitstring}⟩: {count} 次")
# 制备所有四种贝尔态
def create_bell_state(state_type):
"""创建贝尔态
Args:
state_type: 'phi_plus', 'phi_minus', 'psi_plus', 'psi_minus'
"""
cir = dq.QubitCircuit(2)
if state_type == 'phi_plus':
cir.h(0)
cir.cnot(0, 1)
elif state_type == 'phi_minus':
cir.h(0)
cir.cnot(0, 1)
cir.z(1)
elif state_type == 'psi_plus':
cir.h(0)
cir.x(1)
cir.cnot(0, 1)
elif state_type == 'psi_minus':
cir.h(0)
cir.x(1)
cir.cnot(0, 1)
cir.z(1)
return cir
# 测试所有贝尔态
bell_states = ['phi_plus', 'phi_minus', 'psi_plus', 'psi_minus']
bell_names = ['|Φ⁺⟩', '|Φ⁻⟩', '|Ψ⁺⟩', '|Ψ⁻⟩']
for name, state_type in zip(bell_names, bell_states):
cir = create_bell_state(state_type)
_ = cir() # 先执行线路生成量子态
results = cir.measure(shots=1000)
print(f"\n{name} 测量结果:")
for bitstring, count in sorted(results.items()):
if count > 0:
print(f" |{bitstring}⟩: {count} 次")
|Φ⁺⟩ 测量结果: |00⟩: 483 次 |11⟩: 517 次 |Φ⁻⟩ 测量结果: |00⟩: 503 次 |11⟩: 497 次 |Ψ⁺⟩ 测量结果: |01⟩: 488 次 |10⟩: 512 次 |Ψ⁻⟩ 测量结果: |01⟩: 487 次 |10⟩: 513 次
In [44]:
Copied!
# 更复杂的线路可视化
cir = dq.QubitCircuit(4)
# 第一层
cir.hlayer()
cir.barrier()
# 第二层:参数化旋转
cir.rx(0, torch.tensor(np.pi/4))
cir.ry(1, torch.tensor(np.pi/3))
cir.rz(2, torch.tensor(np.pi/6))
cir.barrier()
# 第三层:纠缠层
cir.cnot_ring()
cir.barrier()
# 第四层:再次旋转
cir.rxlayer()
cir.barrier()
# 观测
for i in range(4):
cir.observable(wires=i, basis='z')
cir.draw()
# 更复杂的线路可视化
cir = dq.QubitCircuit(4)
# 第一层
cir.hlayer()
cir.barrier()
# 第二层:参数化旋转
cir.rx(0, torch.tensor(np.pi/4))
cir.ry(1, torch.tensor(np.pi/3))
cir.rz(2, torch.tensor(np.pi/6))
cir.barrier()
# 第三层:纠缠层
cir.cnot_ring()
cir.barrier()
# 第四层:再次旋转
cir.rxlayer()
cir.barrier()
# 观测
for i in range(4):
cir.observable(wires=i, basis='z')
cir.draw()
In [45]:
Copied!
# GHZ 态制备和可视化
cir = dq.QubitCircuit(3)
cir.h(0)
cir.cnot(0, 1)
cir.cnot(0, 2)
cir.barrier()
state = cir()
print("GHZ 态:")
print(state)
# 可视化
cir.draw()
# GHZ 态制备和可视化
cir = dq.QubitCircuit(3)
cir.h(0)
cir.cnot(0, 1)
cir.cnot(0, 2)
cir.barrier()
state = cir()
print("GHZ 态:")
print(state)
# 可视化
cir.draw()
In [46]:
Copied!
# 目标:制备一个特定的目标态 |ψ_target⟩
target_state = torch.tensor([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=torch.complex128).reshape(-1, 1)
print("目标态:")
print(target_state)
# 目标:制备一个特定的目标态 |ψ_target⟩
target_state = torch.tensor([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=torch.complex128).reshape(-1, 1)
print("目标态:")
print(target_state)
目标态:
tensor([[0.7071+0.j],
[0.0000+0.j],
[0.0000+0.j],
[0.7071+0.j]], dtype=torch.complex128)
In [48]:
Copied!
# 创建参数化电路
cir = dq.QubitCircuit(2)
cir.ry(0) # 参数 θ₀
cir.ry(1) # 参数 θ₁
cir.cnot(0, 1)
# 定义损失函数(保真度)
def fidelity(circuit, target):
"""计算当前态与目标态的保真度"""
current_state = circuit()
# 统一数据类型以避免 dtype 不匹配
target = target.to(current_state.dtype)
overlap = torch.abs(torch.dot(current_state.flatten().conj(), target.flatten()))**2
return overlap
# 优化参数
optimizer = torch.optim.Adam(cir.parameters(), lr=0.1)
n_iterations = 50
fidelities = []
for i in range(n_iterations):
optimizer.zero_grad()
# 计算负保真度作为损失
f = fidelity(cir, target_state)
loss = -f
loss.backward()
optimizer.step()
fidelities.append(f.item())
if (i + 1) % 10 == 0:
print(f"迭代 {i+1}/{n_iterations}, 保真度: {f.item():.6f}")
print(f"\n最终保真度: {fidelities[-1]:.6f}")
# 创建参数化电路
cir = dq.QubitCircuit(2)
cir.ry(0) # 参数 θ₀
cir.ry(1) # 参数 θ₁
cir.cnot(0, 1)
# 定义损失函数(保真度)
def fidelity(circuit, target):
"""计算当前态与目标态的保真度"""
current_state = circuit()
# 统一数据类型以避免 dtype 不匹配
target = target.to(current_state.dtype)
overlap = torch.abs(torch.dot(current_state.flatten().conj(), target.flatten()))**2
return overlap
# 优化参数
optimizer = torch.optim.Adam(cir.parameters(), lr=0.1)
n_iterations = 50
fidelities = []
for i in range(n_iterations):
optimizer.zero_grad()
# 计算负保真度作为损失
f = fidelity(cir, target_state)
loss = -f
loss.backward()
optimizer.step()
fidelities.append(f.item())
if (i + 1) % 10 == 0:
print(f"迭代 {i+1}/{n_iterations}, 保真度: {f.item():.6f}")
print(f"\n最终保真度: {fidelities[-1]:.6f}")
迭代 10/50, 保真度: 0.938472 迭代 20/50, 保真度: 0.974652 迭代 30/50, 保真度: 0.986285 迭代 40/50, 保真度: 0.998904 迭代 50/50, 保真度: 0.997760 最终保真度: 0.997760
In [51]:
Copied!
# 可视化优化过程
plt.figure(figsize=(10, 5))
plt.plot(fidelities, linewidth=2)
plt.xlabel('迭代次数', fontsize=12)
plt.ylabel('保真度', fontsize=12)
plt.title('参数优化过程', fontsize=14)
plt.grid(True, alpha=0.3)
plt.show()
# 打印优化后的参数
print("\n优化后的参数:")
for name, param in cir.named_parameters():
if 'theta' in name:
print(f" {name}: {param.item():.4f} rad")
# 可视化优化过程
plt.figure(figsize=(10, 5))
plt.plot(fidelities, linewidth=2)
plt.xlabel('迭代次数', fontsize=12)
plt.ylabel('保真度', fontsize=12)
plt.title('参数优化过程', fontsize=14)
plt.grid(True, alpha=0.3)
plt.show()
# 打印优化后的参数
print("\n优化后的参数:")
for name, param in cir.named_parameters():
if 'theta' in name:
print(f" {name}: {param.item():.4f} rad")
In [52]:
Copied!
# 验证最终结果
final_state = cir()
print("优化后的量子态:")
print(final_state)
print("\n目标态:")
# 转换数据类型以匹配
target_for_display = target_state.to(final_state.dtype)
print(target_for_display)
# 计算最终保真度
final_fidelity = torch.abs(torch.dot(final_state.flatten().conj(), target_for_display.flatten()))**2
print(f"\n最终保真度: {final_fidelity.item():.6f}")
# 可视化最终线路
print("\n优化的量子线路:")
cir.draw()
# 验证最终结果
final_state = cir()
print("优化后的量子态:")
print(final_state)
print("\n目标态:")
# 转换数据类型以匹配
target_for_display = target_state.to(final_state.dtype)
print(target_for_display)
# 计算最终保真度
final_fidelity = torch.abs(torch.dot(final_state.flatten().conj(), target_for_display.flatten()))**2
print(f"\n最终保真度: {final_fidelity.item():.6f}")
# 可视化最终线路
print("\n优化的量子线路:")
cir.draw()
总结¶
本教程介绍了 DeepQuantum 框架的核心功能:
- 量子比特和量子线路:使用
QubitState和QubitCircuit创建和管理量子系统 - 基本量子门:单比特门(X, Y, Z, H, Rx, Ry, Rz)、双比特门(CNOT, SWAP, Rxx 等)
- 参数化电路:创建变分量子电路,支持自动微分和优化
- 量子态初始化和测量:多种初始化方式,灵活的测量选项
- Observable 和期望值:计算可观测量期望值,支持多种测量基
- 可视化工具:直观展示量子线路结构
下一步学习¶
- 查看 VQE 高级教程,学习如何求解真实的物理问题
- 探索量子机器学习应用
- 学习 QAOA 组合优化算法
相关资源¶
- DeepQuantum 文档:https://deepquantum.readthedocs.io
- 更多示例代码:
E:\02_Projects\turingQ\deepquantum\examples
祝你在量子计算的旅程中收获满满!