算子使用示例

本教程展示各类算子的使用方法。

[ ]:
import pysparq as ps
import numpy as np

算术算子

[ ]:
ps.System.clear()

ps.System.add_register("a", ps.UnsignedInteger, 4)
ps.System.add_register("b", ps.UnsignedInteger, 4)
ps.System.add_register("result", ps.UnsignedInteger, 4)

state = ps.SparseState()
ps.Init_Unsafe("a", 7)(state)
ps.Init_Unsafe("b", 10)(state)

加法

[ ]:
# 外置加法: result ^= a + b
ps.Add_UInt_UInt("a", "b", "result")(state)
print("Add_UInt_UInt:")
ps.pprint(state)
[ ]:
# 内置加法: b += a
ps.System.clear()
ps.System.add_register("a", ps.UnsignedInteger, 4)
ps.System.add_register("b", ps.UnsignedInteger, 4)
state = ps.SparseState()
ps.Init_Unsafe("a", 7)(state)
ps.Init_Unsafe("b", 10)(state)

op = ps.Add_UInt_UInt_InPlace("a", "b")
op(state)
print("Add_UInt_UInt_InPlace:")
ps.pprint(state)
# b = (10 + 7) % 16 = 1
[ ]:
# 撤销
op.dag(state)
print("dagger 后:")
ps.pprint(state)

乘法

[ ]:
ps.System.clear()
ps.System.add_register("x", ps.UnsignedInteger, 4)
ps.System.add_register("triple", ps.UnsignedInteger, 4)

state = ps.SparseState()
ps.Init_Unsafe("x", 5)(state)

# 乘以奇数常量(保证双射)
ps.Mult_UInt_ConstUInt("x", 3, "triple")(state)
print("Mult_UInt_ConstUInt(x, 3):")
ps.pprint(state)

比较与标志

[ ]:
ps.System.clear()
ps.System.add_register("a", ps.UnsignedInteger, 4)
ps.System.add_register("b", ps.UnsignedInteger, 4)
ps.System.add_register("less", ps.Boolean, 1)
ps.System.add_register("equal", ps.Boolean, 1)

state = ps.SparseState()
ps.Init_Unsafe("a", 3)(state)
ps.Init_Unsafe("b", 5)(state)

ps.Compare_UInt_UInt("a", "b", "less", "equal")(state)
print("Compare_UInt_UInt:")
ps.pprint(state)

量子门

[ ]:
ps.System.clear()
ps.System.add_register("q", ps.Boolean, 1)

state = ps.SparseState()
print("初始:")
ps.pprint(state)
[ ]:
# X 门(NOT)
ps.Xgate_Bool("q", 0)(state)
print("X 门后:")
ps.pprint(state)
[ ]:
# Hadamard
ps.Hadamard_Bool("q")(state)
print("Hadamard 后:")
ps.pprint(state)
[ ]:
# 相位门
ps.Phase_Bool("q", 0, np.pi/4)(state)
print("Phase(π/4) 后:")
ps.pprint(state)

QFT

[ ]:
ps.System.clear()
ps.System.add_register("q", ps.UnsignedInteger, 3)

state = ps.SparseState()
ps.Init_Unsafe("q", 1)(state)

print("初始:")
ps.pprint(state)
[ ]:
# QFT
ps.QFT("q")(state)
print("QFT 后:")
ps.pprint(state)
[ ]:
# inverseQFT
ps.inverseQFT("q")(state)
print("inverseQFT 后:")
ps.pprint(state)

条件操作

[ ]:
ps.System.clear()
ps.System.add_register("x", ps.UnsignedInteger, 2)
ps.System.add_register("result", ps.UnsignedInteger, 2)
ps.System.add_register("ctrl", ps.Boolean, 1)

state = ps.SparseState()
ps.Init_Unsafe("x", 3)(state)
ps.Init_Unsafe("ctrl", 1)(state)

# 当 ctrl = 1 时执行加法
ps.Add_UInt_ConstUInt("x", 5, "result").conditioned_by_nonzeros("ctrl")(state)

print("条件加法 (ctrl=1):")
ps.pprint(state)
[ ]:
# ctrl = 0 时条件不触发
ps.System.clear()
ps.System.add_register("x", ps.UnsignedInteger, 2)
ps.System.add_register("result", ps.UnsignedInteger, 2)
ps.System.add_register("ctrl", ps.Boolean, 1)

state = ps.SparseState()
ps.Init_Unsafe("x", 3)(state)
ps.Init_Unsafe("ctrl", 0)(state)  # ctrl = 0

ps.Add_UInt_ConstUInt("x", 5, "result").conditioned_by_nonzeros("ctrl")(state)

print("条件加法 (ctrl=0):")
ps.pprint(state)
# result 保持 0

Block Encoding:三对角矩阵

Block Encoding 将经典矩阵编码为酉矩阵,是量子线性代数算法的核心。下面的例子使用 pysparq.algorithms.block_encoding 中的 BlockEncodingTridiagonal 对三对角矩阵 :math:A = \alpha I + \beta T 进行块编码。

[ ]:
from pysparq.algorithms.block_encoding import (
    get_tridiagonal_matrix,
    BlockEncodingTridiagonal,
)

alpha, beta, dim = 0.5, 0.3, 4
A = get_tridiagonal_matrix(alpha, beta, dim)
print(f"三对角矩阵 A:\n{A}")

# 构建 Block Encoding 电路
ps.System.clear()
ps.System.add_register("main_reg", ps.UnsignedInteger, 2)  # dim = 2^2
ps.System.add_register("anc_UA", ps.UnsignedInteger, 4)

state = ps.SparseState()
ps.Init_Unsafe("main_reg", 0)(state)
ps.Init_Unsafe("anc_UA", 0)(state)

block_enc = BlockEncodingTridiagonal("main_reg", "anc_UA", alpha, beta)
block_enc(state)
print(f"Block Encoding 应用成功,基态数: {state.size()}")

block_enc.dag(state)  # 释放辅助寄存器
print(f"逆 Block Encoding 后,基态数: {state.size()}")

Python 侧自定义算子

当需要组合多个已有算子时,在 Python 侧直接封装:

[ ]:
class MyIncrement:
    """对寄存器值加 1(外置结果寄存器)。"""

    def __init__(self, src: str, dst: str):
        self.src = src
        self.dst = dst

    def __call__(self, state: ps.SparseState):
        ps.Add_UInt_UInt(self.src, self.dst)(state)

    def dag(self, state: ps.SparseState):
        ps.Add_UInt_UInt(self.src, self.dst)(state)  # XOR 语义,加两次恢复


ps.System.clear()
ps.System.add_register("counter", ps.UnsignedInteger, 4)
ps.System.add_register("result", ps.UnsignedInteger, 4)
state = ps.SparseState()
ps.Init_Unsafe("counter", 5)(state)
ps.Init_Unsafe("result", 0)(state)

my_inc = MyIncrement("counter", "result")
my_inc(state)          # result = 0 + 5 = 5
print(f"加法后 result = {state.basis_states[0].get(ps.System.get_id('result')).value}")
my_inc.dag(state)      # result = 5 + 5 = 0,恢复
print(f"dagger 后 result = {state.basis_states[0].get(ps.System.get_id('result')).value}")

如需新 primitives(超出已有算子表达能力),使用 compile_operator 将 C++ 代码编译为动态链接库:

[ ]:
from pysparq.dynamic_operator import compile_operator

cpp_code = '''
class FlipOp : public SelfAdjointOperator {
    size_t reg_id;
public:
    FlipOp(size_t r) : reg_id(r) {}
    void operator()(std::vector<System>& state) const override {
        for (auto& s : state) {
            s.get(reg_id).value ^= 1;
        }
    }
};
'''

FlipOp = compile_operator(
    name="FlipOp",
    cpp_code=cpp_code,
    base_class="SelfAdjointOperator",
    constructor_args=[("size_t", "reg_id")],
)

ps.System.clear()
ps.System.add_register("q", ps.UnsignedInteger, 4)
state = ps.SparseState()
ps.Init_Unsafe("q", 1)(state)
print("初始:", state.basis_states[0].get(ps.System.get_id("q")).value)
flip = FlipOp(reg_id=0)
flip(state)   # 第 0 比特翻转
print("翻转后:", state.basis_states[0].get(ps.System.get_id("q")).value)

总结

本教程展示了:

  • 算术算子:Add, Mult, Compare

  • 量子门:X, Hadamard, Phase

  • QFT / inverseQFT

  • 条件操作

  • Block Encoding:用 BlockEncodingTridiagonal 对三对角矩阵进行块编码

  • 自定义算子:Python 侧组合已有算子,或通过 compile_operator 编译 C++ 代码