PySparQ 快速入门¶
本教程介绍 PySparQ 的基本使用方法。
安装¶
pip install pysparq
基本概念¶
PySparQ 基于 Register Level Programming 范式,直接操作命名寄存器而非单个量子门。
[ ]:
import pysparq as ps
# Clear the static state (must be called for every new program!)
ps.System.clear()
# Create registers
ps.System.add_register("counter", ps.UnsignedInteger, 4) # 4-bit unsigned integer
ps.System.add_register("flag", ps.Boolean, 1) # single qubit
# Create a sparse state
state = ps.SparseState()
print(f"Initial number of basis states: {state.size()}")
初始化寄存器¶
[ ]:
# Initialize register values with Init_Unsafe
ps.Init_Unsafe("counter", 5)(state)
ps.Init_Unsafe("flag", 0)(state)
# Print the state
ps.pprint(state)
创建叠加态¶
[ ]:
# Hadamard creates a uniform superposition
ps.Hadamard_Bool("flag")(state)
print("After Hadamard:")
ps.pprint(state)
算术操作¶
[ ]:
# Create the result register
ps.System.add_register_synchronous("result", ps.UnsignedInteger, 4, state)
# Addition: result ^= counter + 3
ps.Add_UInt_ConstUInt("counter", 3, "result")(state)
print("After addition:")
ps.pprint(state)
查询寄存器信息¶
[ ]:
# Get register metadata
print(f"counter size: {ps.System.size_of('counter')} bits")
print(f"counter type: {ps.System.type_of('counter')}")
print(f"counter ID: {ps.System.get_id('counter')}")
print(f"Total number of qubits: {ps.System.get_qubit_count()}")
条件操作¶
[ ]:
# Create a conditional addition (executed when flag is non-zero)
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)
ps.System.add_register("ctrl", ps.Boolean, 1)
state = ps.SparseState()
ps.Init_Unsafe("a", 3)(state)
ps.Init_Unsafe("b", 5)(state)
ps.Init_Unsafe("ctrl", 1)(state) # ctrl = 1, condition is active
# Conditional addition
ps.Add_UInt_UInt("a", "b", "result").conditioned_by_nonzeros("ctrl")(state)
print("Conditional addition result:")
ps.pprint(state)
总结¶
PySparQ 的核心概念:
System.clear() - 每次新程序开始时调用
add_register - 创建命名寄存器
SparseState - 稀疏量子态
Operators - 算子对状态进行变换
StatePrint - 打印状态查看结果