基础量子算法
概述
unitarylab_algorithms.fundamental_algorithm 包提供了构成高级算法基础的核心量子原语:
| 算法 | 类 | 用途 |
|---|---|---|
| Grover 搜索 | GroverAlgorithm | 无结构搜索的二次加速 |
| 量子相位估计 | QPEAlgorithm | 提取酉算符的本征相位 |
| 振幅放大(Amplitude Amplification) | AmplitudeAmplificationAlgorithm | 提高目标态的测量概率 |
| 量子振幅估计(QAE) | AmplitudeEstimationAlgorithm | 估计目标态的振幅 |
| Hadamard 测试 | HadamardTestAlgorithm | 估计期望值和态重叠度 |
| Hadamard 变换 | HadamardTransformAlgorithm | 比特全局 Hadamard 变换 |
status 表示调用是否正常完成;估计类算法的结果精度应通过其误差、概率或估计值字段判断。振幅放大的 status 还会反映目标概率是否高于初始概率。各算法的具体判定方式见对应小节。
Grover 搜索算法
背景
Grover 算法在包含 个条目的无序数据库中以 次预言机查询找到目标,经典方法需要 次。该算法是无结构量子搜索的最优算法,也是许多其他算法的重要子程序。
算法通过迭代 Grover 扩散算符(均值反转)与翻转目标态相位的 Oracle 来实现放大,迭代次数由初始成功概率 自动计算得到。
导入
from unitarylab_algorithms import GroverAlgorithm.run() 参数
def run(self, n: int, target: str, backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
n | int | — (必填) | 数据寄存器的量子比特数 |
target | str | — (必填) | 目标态的二进制字符串(如 3 比特下的 '101') |
返回值
{
'status': 'ok', # 恒为 'ok',不反映真实搜索成败,见上方说明
'circuit_path': '/path/to/grover_algorithm_circuit.svg',
'plot': [{'format': 'txt', 'filename': 'grover_algorithm_result.txt'}],
'circuit': <Circuit>,
'Amplified target-state probability': 0.9453,
'Result': '101', # 实际测得概率最大的比特串——与 target 比较即可判断真实成败
}示例
from unitarylab_algorithms import GroverAlgorithm
algo = GroverAlgorithm()
result = algo.run(n=3, target='101')
is_really_success = (result['Result'] == '101') # 真实成败判断,不要依赖 result['status']
print(is_really_success)快速演示
from unitarylab_algorithms.fundamental_algorithm.grover.algorithm import test
test(n=3, target='101')注意事项
status='ok'表示调用完成;是否命中目标请比较result['Result']与传入的target。target的长度理论上应等于n(网页端parameters.json亦如此说明),但 Python API 层面没有做显式长度校验——长度不匹配时不会得到清晰的ValueError,而是在构建多控制 Oracle 线路(mcx)时触发底层错误或产生不符合预期的线路,请务必保证两者匹配。
量子相位估计(QPE)
背景
QPE 提取酉算符 的本征相位 ,其中 。使用 个辅助量子比特时,相位估计精度为 。
QPE 是 Shor 算法、HHL 和量子化学模拟的关键子程序。
导入
from unitarylab_algorithms import QPEAlgorithm.run() 参数
def run(self, U: Circuit, d: int,
prepare_target: Optional[Circuit] = None, backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
U | Circuit | — (必填) | 待估计本征相位的酉算符线路 |
d | int | — (必填) | 相位寄存器量子比特数(精度为 ) |
prepare_target | Circuit | None | None | 制备本征态的线路(默认为 );若提供,其比特数必须与 U 一致,否则抛出 ValueError |
直接构建 QPE 线路
QPEAlgorithm 还提供了将 QPE 嵌入更大线路的工具方法:
from unitarylab import Circuit
from unitarylab_algorithms import QPEAlgorithm
U = Circuit(1)
U.z(0)
algo = QPEAlgorithm()
qpe_circuit = algo.build_qpe_circuit(U=U, d=4)返回值
{
'status': 'ok', # 表示估计过程已完成
'circuit_path': '/path/to/quantum_phase_estimation_algorithm_circuit.svg',
'plot': [{'format': 'txt', 'filename': 'quantum_phase_estimation_algorithm_result.txt'}],
'circuit': <Circuit>,
'Estimated phase': 0.125,
'Best phase bit string': '0010',
'Best phase probability': 0.98,
'Computation time (s)': 0.0123,
'Phase probabilities': [('0010', 0.98), ('0011', 0.01), ('0001', 0.005)], # 概率最高的前 3 个候选相位
}示例
from unitarylab.core import Circuit
from unitarylab_algorithms import QPEAlgorithm
# T 门的本征相位为 π/4,以 2π 为单位即 φ = 1/8 = 0.125
U = Circuit(1)
U.t(0)
algo = QPEAlgorithm()
result = algo.run(U=U, d=4)
print(result['Estimated phase']) # 约等于 0.125快速演示
from unitarylab_algorithms.fundamental_algorithm.qpe.algorithm import test
test(p=0.25, n=3)注意事项
status='ok'表示估计过程完成;请通过Estimated phase与理论值的接近程度评估精度。- 模块级
test(p, n)的p表示本征相位(以 为单位的小数):T 门对应p=0.125,S 门对应p=0.25。也可以按上方示例直接构建酉线路U。
振幅放大(Amplitude Amplification)
背景
振幅放大是 Grover 算法的推广:给定态制备酉算符 和一个标记”好”态的预言机,通过反复应用类 Grover 反射算符来放大好态的振幅。迭代次数由初始成功概率 自动推断,也可手动指定。
导入
from unitarylab_algorithms import AmplitudeAmplificationAlgorithm.run() 参数
def run(self, U: Circuit, good_zero_qubits: List[int], p: float,
reps: Optional[int] = None, backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
U | Circuit | — (必填) | 态制备线路(不含辅助比特) |
good_zero_qubits | List[int] | — (必填) | 目标态中必须为 的比特索引 |
p | float | — (必填) | 初始成功概率;reps=None 时用于自动计算迭代次数,且此时必须满足 ,否则抛出 ValueError;无论是否显式传入 reps,都会用于日志展示和最终 status 判定(target_prob > p) |
reps | int | None | None | 手动指定迭代次数(提供时覆盖基于 的自动计算,此时 p 不再受 约束,但仍参与最终 status 判定,即 target_prob > p) |
返回值
本算法是本包 6 个算法中唯一顶层 status 真实反映成败的(is_success = target_prob > p):
{
'status': 'ok', # 真实反映:放大后的目标态概率是否确实超过初始概率 p
'circuit_path': '/path/to/amplitude_amplification_algorithm_circuit.svg',
'plot': [{'format': 'txt', 'filename': 'amplitude_amplification_algorithm_result.txt'}],
'circuit': <Circuit>,
'Amplified Target Probability': 0.98,
'Initial Success Probability': 0.1,
'Repetitions': 3,
'Computation Time (s)': 0.0234,
'Data register size': 2,
}示例
from unitarylab_algorithms import AmplitudeAmplificationAlgorithm
algo = AmplitudeAmplificationAlgorithm()
result = algo.run(U=my_circuit, good_zero_qubits=[0], p=0.1, reps=3)
print(result['status'])快速演示
from unitarylab_algorithms.fundamental_algorithm.amplitude_amplification.algorithm import test
test(p=0.1, reps=3)注意事项
p仅在reps=None时被算法用于计算迭代次数,且此时必须满足 ;一旦显式传入reps,p只作为”初始概率”参与日志展示与最终status判定(target_prob > p),不再影响迭代次数本身。- 与 Grover / QPE / Hadamard 变换等算法不同,本算法的
status可放心用于业务逻辑判断真实放大效果。
量子振幅估计(QAE)
背景
量子振幅估计(QAE)估计态制备酉算符 中目标态的振幅 。它结合振幅放大与 QPE,使用 个辅助比特时均方根误差为 。
导入
from unitarylab_algorithms import AmplitudeEstimationAlgorithm.run() 参数
def run(self, U: Circuit, good_zero_qubits: List[int], d: int = 6,
backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
U | Circuit | — (必填) | 态制备酉算符 |
good_zero_qubits | List[int] | — (必填) | 定义目标态的比特索引 |
d | int | 6 | 相位寄存器量子比特数(精度 ) |
注意:
.run()本身没有p参数——p只出现在模块级test(p=0.36, d=6)函数中,用于构造测试用的态制备线路U;直接调用 Python API 时需要自己构建U。
返回值
{
'status': 'ok', # 表示估计过程已完成
'circuit_path': '/path/to/amplitude_estimation_algorithm_circuit.svg',
'plot': [{'format': 'txt', 'filename': 'amplitude_estimation_algorithm_result.txt'}],
'circuit': <Circuit>,
'Target amplitude': 0.36,
'Most likely phase (bits)': '001001',
'Phase': 0.140625,
'Computation time (s)': 0.0456,
'Total qubits': 9,
}示例
from unitarylab_algorithms import AmplitudeEstimationAlgorithm
algo = AmplitudeEstimationAlgorithm()
result = algo.run(U=my_circuit, good_zero_qubits=[0], d=6)
print(result['Target amplitude'])快速演示
from unitarylab_algorithms.fundamental_algorithm.amplitude_estimation.algorithm import test
test(p=0.36, d=6)注意事项
status='ok'表示估计过程完成;请将Target amplitude与理论值比较以评估精度。.run()无p参数,仅test()有;调用 Python API 时必须自行构造U(态制备线路)与good_zero_qubits。
Hadamard 测试
背景
Hadamard 测试利用单个辅助量子比特估计酉算符 关于态 的期望值 。支持三种模式:
expectation——估计 (当imag=True时估计虚部)swap_test——估计两个态的重叠度phase_estimation——执行单比特相位估计
导入
from unitarylab_algorithms import HadamardTestAlgorithm.run() 参数
def run(self, mode: str = "expectation", U: Optional[Circuit] = None,
prepare_psi: Optional[Circuit] = None, prepare_phi: Optional[Circuit] = None,
imag: bool = False, shots: int = 20000,
backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
mode | str | 'expectation' | 运行模式:'expectation'、'swap_test'、'phase_estimation' 之一,其他值抛出 ValueError |
U | Circuit | None | None | 酉算符线路(expectation/phase_estimation 模式必填,否则抛出 ValueError;swap_test 模式下不使用) |
prepare_psi | Circuit | None | None | 制备 $ |
prepare_phi | Circuit | None | None | 制备 $ |
imag | bool | False | 提取虚部(仅 expectation 模式有效) |
shots | int | 20000 | 统计采样的测量次数;shots<=0 时不做二项分布采样噪声模拟,直接返回精确期望值 |
.run()自身的shots默认值为20000(引入采样噪声),而模块级test()函数与网页端parameters.json的默认值均为shots=0(精确计算,无噪声)。直接实例化HadamardTestAlgorithm().run(...)且不显式传shots时,得到的是带采样噪声的估计值,与test()/网页端默认展示的精确值不同。
返回值
与其他 5 个算法不同,circuit_path 在这里是一个路径列表而非单一字符串——expectation 模式下只有 1 个元素(main),swap_test 模式下只有 1 个元素(real),phase_estimation 模式下有 2 个元素(real、imag):
{
'status': 'ok', # 恒为 'ok';Hadamard 测试是纯估计器,本身无成败判定
'circuit_path': ['/path/to/HadamardTest_expectation_main.svg'],
'plot': [{'format': 'txt', 'filename': 'hadamard_test_algorithm_result.txt'}],
'circuit': <Circuit>, # 各模式下建立的电路之一(代表性电路)
'Estimated Value': 0.7071,
'Computation Time (s)': 0.0089,
}示例
from unitarylab_algorithms import HadamardTestAlgorithm
algo = HadamardTestAlgorithm()
result = algo.run(mode='expectation', U=my_U, prepare_psi=my_psi, shots=0) # 显式传 shots=0 以获得精确值
print(result['Estimated Value'])快速演示
from unitarylab_algorithms.fundamental_algorithm.hadamard_test.algorithm import test
test(U=[[1, 0], [0, 1]], psi=[1, 2], shots=0)注意事项
.run()与test()/网页端的shots默认值不一致(20000vs0),若追求可复现的精确结果,请显式传入shots=0。circuit_path是列表而非字符串,与本包其他算法(HadamardTransformAlgorithm等)不同,处理返回值时需要注意类型差异。- 该模块
__init__.py的__all__仅导出'HadamardTestAlgorithm',未包含'test'(尽管test函数本身已被导入),因此from ...hadamard_test import *不会带出test;如需使用快速演示函数,请直接从hadamard_test.algorithm模块导入,如上方示例所示。
Hadamard 变换
背景
比特 Hadamard 变换对每个量子比特同时施加一个 Hadamard 门,将计算基态 映射到所有基态的等权叠加(从 出发时)。该变换是自逆的(反射性)。
mode='superposition' 生成叠加态并验证各基态概率是否均匀(理论值 );mode='reflexive_test' 则先制备一个随机态,连续施加两次 Hadamard 变换,验证是否恢复到原始态。
导入
from unitarylab_algorithms import HadamardTransformAlgorithm.run() 参数
def run(self, n: int = 3, mode: str = "superposition", backend='torch', device='cpu', dtype=np.complex128) -> Dict[str, Any]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
n | int | 3 | 量子比特数,必须 ,否则抛出 ValueError |
mode | str | 'superposition' | 'superposition'(叠加态生成)或 'reflexive_test'(反射性验证),其他值抛出 ValueError |
返回值
{
'status': 'ok', # 表示变换过程已完成
'circuit_path': '/path/to/hadamard_transform_algorithm_circuit.svg',
'plot': [{'format': 'txt', 'filename': 'hadamard_transform_algorithm_result.txt'}],
'circuit': <Circuit>,
'Computation time (s)': 0.0034,
'Probability distribution': {'000': 0.125, '001': 0.125, ...}, # 仅 superposition 模式下非空;reflexive_test 模式下为空字典 {}
'State vector': array([...]),
}示例
from unitarylab_algorithms import HadamardTransformAlgorithm
algo = HadamardTransformAlgorithm()
result = algo.run(n=4, mode='superposition')
print(result['Probability distribution'])快速演示
from unitarylab_algorithms.fundamental_algorithm.hadamard_transform.algorithm import test
test(n=3)注意事项
status='ok'表示变换过程完成。需要验证均匀性或反射性时,可检查返回的Probability distribution、State vector或结果文本中的摘要。mode='reflexive_test'时Probability distribution恒为空字典{}(该字段只在superposition模式下计算),不要误以为算法出错。