1概述
QuantumSim 是一款纯 Rust 实现的量子电路仿真库,通过 C ABI (FFI) 对外提供服务。本发布包是 V0.78 最小化交付版,仅包含运行所需的二进制文件、Python 绑定和测试脚本,无源码、无构建工具链依赖。
2发布包文件清单 (9 个文件)
| 文件 | 类型 | 用途 | 必需 |
|---|---|---|---|
quantum_sim.dll | 二进制 | 核心仿真引擎,所有功能通过此 DLL 提供 | 是 |
quantum_sim.dll.lib | 导入库 | 供 C/C++ 编译期链接 (Python 端用 ctypes 动态加载,不需要) | 否 |
quantum_sim.py | Python | Python FFI 绑定,封装核心类 QuantumSim / QuantumCircuit / VQEChemistry | 是 (Python 用户) |
benchmark.py | Python | 性能基准测试,9 节测试套件 | 否 |
circuit_test.py | Python | 30 个电路正确性测试,支持 JSON 导入 | 否 |
example_*.json | JSON | 示例电路文件,演示 JSON 导入格式 | 否 |
使用教程.html | 文档 | 本教程 | 否 |
3快速开始 (3 步)
- 放置 DLL:将
quantum_sim.dll放在与 Python 脚本同一目录,或设置环境变量QSIM_DLL_PATH指向 DLL 所在目录。 - 编写 Python 代码:
from quantum_sim import QuantumSim,创建QuantumSim(n_qubits)实例,应用门,测量。 - 运行:
python your_script.py。DLL 加载顺序:环境变量 → 脚本同目录 → target/release → 系统 PATH。
# 最小示例: Bell 态
from quantum_sim import QuantumSim
with QuantumSim(2) as sim: # 2 量子比特
sim.apply_h(0) # H 门到 qubit 0
sim.apply_cnot(0, 1) # CNOT(0→1)
result = sim.measure() # 确定性测量
print(f"结果: {result:#b}") # 0b00 或 0b11
print(f"P(q0=1) = {sim.prob_one(0):.4f}") # 0.5000
4FFI 接口总览 (100 个导出函数)
DLL 导出 100 个 #[no_mangle] extern "C" 函数,按功能分为以下类别:
§3 StateVector 生命周期 (4 函数)
| 函数 | 签名 | 说明 |
|---|---|---|
qsim_state_new | (n: u32) -> *mut | 创建 n 量子比特态向量 (1-32),返回不透明句柄 |
qsim_state_free | (*mut) -> () | 释放句柄 (必须调用,否则内存泄漏) |
qsim_state_n_qubits | (*mut) -> i32 | 查询量子比特数 (null 返回 -1) |
qsim_state_dim | (*mut) -> u64 | 查询态维度 2^n (null 返回 0) |
§4 StateVector 量子门 (17 函数)
| 函数 | 参数 | 说明 |
|---|---|---|
qsim_state_apply_h | (handle, q) | Hadamard 门 |
qsim_state_apply_x / y / z | (handle, q) | Pauli-X/Y/Z 门 |
qsim_state_apply_s / t | (handle, q) | S 门 (π/2) / T 门 (π/4) |
qsim_state_apply_cz | (handle, c, t) | Controlled-Z 门 |
qsim_state_apply_cnot | (handle, c, t) | CNOT 门 (c≠t) |
qsim_state_apply_toffoli | (handle, c1, c2, t) | Toffoli 门 (CCNOT) |
qsim_state_apply_swap | (handle, q1, q2) | SWAP 门 |
qsim_state_apply_rx / ry / rz | (handle, q, θ) | 旋转门 (VQE 必需) |
qsim_state_apply_u | (handle, q, θ, φ, λ) | IBM Qiskit 标准 U3 门 |
c_int 错误码:0=成功,1=空指针,3=索引越界,4=参数无效。§5 StateVector 测量 (6 函数)
| 函数 | 签名 | 说明 |
|---|---|---|
qsim_state_measure | (*mut) -> u64 | 确定性测量 (返回最大概率态),u64::MAX 表示错误 |
qsim_state_measure_safe | (*mut, *mut u64) -> i32 | 安全测量 (out 参数,无歧义错误码) |
qsim_state_prob_one | (*mut, q) -> f64 | qubit q 测量为 |1⟩ 的概率 |
qsim_state_prob_zero | (*mut, q) -> f64 | qubit q 测量为 |0⟩ 的概率 |
qsim_state_normalize | (*mut) -> i32 | 归一化态向量 |
qsim_state_amplitude | (*mut, idx, *re, *im) -> i32 | 获取第 idx 个振幅 (实部+虚部) |
§6 SparseStateVector (8 函数) — 1-64 量子比特
稀疏态向量后端,适用于稀疏电路 (大部分振幅为 0)。
| 函数 | 说明 |
|---|---|
qsim_sparse_new / free / n_qubits / dim | 生命周期 |
qsim_sparse_apply_h / x / z / cnot | 基本门 |
§7 Matrix Product State (12 函数) — 1-100000 量子比特
MPS 后端,支持超大量子比特数 (10 万级),按需分解。
| 函数 | 说明 |
|---|---|
qsim_mps_new / free / n_qubits | 生命周期 |
qsim_mps_apply_h / x / z / s / t / cnot / swap | 基本门 (SWAP 支持非相邻) |
qsim_mps_run_circuit | 批量门执行 (一次 FFI 调用) |
qsim_mps_compression_ratio | 查询压缩比 |
qsim_mps_entanglement_entropy | 查询纠缠熵 |
§8 数论加速 (3 函数)
| 函数 | 签名 | 说明 |
|---|---|---|
qsim_fibonacci_fast | (n: u32) -> u64 | O(1) 查表 Fibonacci(n) |
qsim_tanh_sq_ln_phi | (n: u32) -> f64 | O(1) 查表 tanh²(n·lnφ) |
qsim_ramsey_r55_speedup | () -> f64 | Ramsey R(5,5) 数论加速比 |
§9 批量接口 + QASM 互通 (10 函数)
核心实战接口:一次 FFI 调用执行整个电路,消除逐门 FFI 开销。
| 函数 | 说明 |
|---|---|
qsim_state_run_circuit | 批量门执行 (QsimGate 数组,上限 65536 门) |
qsim_state_copy_amplitudes | 零拷贝批量振幅导出 (numpy complex128 兼容) |
qsim_state_sample_top_k | 确定性采样:返回前 K 个最可能结果 |
qsim_state_to_qasm | 导出 OpenQASM 2.0 字符串 |
qsim_circuit_to_qasm | 电路转 QASM |
qsim_state_from_qasm | 从 QASM 字符串构建态 |
qsim_run_openqasm | 直接执行 QASM 字符串 (沙箱,8KB 上限) |
qsim_string_free | 释放动态字符串 (to_qasm 等返回的) |
qsim_error_string | 错误码转字符串 (静态,无需释放) |
#[repr(C)]
pub struct QsimGate {
pub gate_type: c_int, // QSIM_GATE_H=0, X=1, Y=2, Z=3, S=4, T=5, CNOT=6, CZ=7, Toffoli=8, SWAP=9, Rx=10, Ry=11, Rz=12, U3=13, iSWAP=14, XX=15, YY=16, CRx=17, CRy=18, CRz=19, Fredkin=20
pub q: c_uint, // 目标量子比特
pub q2: c_uint, // 控制量子比特 (CNOT/CZ/Toffoli/SWAP)
pub q3: c_uint, // 第二控制 (Toffoli)
pub theta: c_double, // 旋转角 (Rx/Ry/Rz/U3)
pub phi: c_double, // 相位 φ (U3)
pub lambda: c_double, // 相位 λ (U3)
}
支持 21 种门类型。§11 硬件感知 (12 函数)
| 函数 | 说明 |
|---|---|
qsim_system_ram_bytes | 系统总物理内存 |
qsim_available_ram_bytes | 当前可用内存 (动态) |
qsim_memory_load_percent | 内存负载百分比 (0-100) |
qsim_cpu_cores | CPU 逻辑核心数 |
qsim_cpu_physical_cores | CPU 物理核心数 |
qsim_gpu_vram_bytes | GPU 可用显存 |
qsim_gpu_name / vendor / device_type | GPU 信息 (返回字符串,需 qsim_string_free) |
qsim_hardware_max_qubits | 基于真实硬件计算最大量子比特数 |
qsim_hardware_max_qubits_f64 | f64 模式最大量子比特数 |
qsim_recommended_parallel_threshold | 推荐并行阈值 |
qsim_recommended_batch_size | 推荐批量子门数 |
qsim_hardware_info_json | 完整硬件信息 JSON 字符串 |
§11.5 安全接口 (6 函数)
| 函数 | 说明 |
|---|---|
qsim_security_init | 初始化安全上下文 (绑定 HWID) |
qsim_security_tick | 周期性安全检测 (建议每 60s 调用) |
qsim_security_scan_now | 立即扫描 (调试器/完整性/canary) |
qsim_security_finalize | 关闭安全上下文 |
qsim_security_threat_score | 当前威胁评分 (0-100) |
qsim_version | 版本字符串 (静态) |
§13 Stabilizer 电路 (8 函数) — Clifford 电路,256 量子比特
Clifford 电路高效模拟器,多项式时间复杂度。
| 函数 | 说明 |
|---|---|
qsim_stabilizer_new / free / n_qubits | 生命周期 |
qsim_stabilizer_apply_h / s / cnot | Clifford 门 |
qsim_stabilizer_measure | 测量 |
§V12.773 HybridAccelerator (6 函数) — GPU/CPU 自动切换
| 函数 | 说明 |
|---|---|
qsim_hybrid_new / free | 生命周期 |
qsim_hybrid_apply_gate | 应用门 (自动选择 GPU/CPU) |
qsim_hybrid_measure | 测量 |
qsim_hybrid_to_qasm | 导出 QASM |
§V12.729 水印接口 (2 函数)
| 函数 | 说明 |
|---|---|
qsim_shor_factorize_watermarked | Shor 因子分解 (带拓扑水印) |
qsim_hhl_solve_watermarked | HHL 线性方程求解 (带拓扑水印) |
§14 License 远程验证 (4 函数)
| 函数 | 说明 |
|---|---|
qsim_license_verify_online | 在线验证许可证 (Cloudflare Workers) |
qsim_license_activate | 激活许可证 |
qsim_license_check_feature | 检查功能权限 |
qsim_license_auto_verify_start | 启动后台自动验证 |
§11.2 数论量子接口 (5 函数)
| 函数 | 说明 |
|---|---|
qsim_mobius_mu | Möbius 函数 μ(n) |
qsim_mertens_function | Mertens 函数 M(n) |
qsim_j_invariant | 椭圆曲线 j-不变量 |
qsim_crt_solve_pair | 中国剩余定理 (二元) |
qsim_precision_mode / digits / decomposition_method | 精度信息 |
5内存释放规则 (重要)
| 资源类型 | 创建函数 | 释放函数 | 备注 |
|---|---|---|---|
| QsimStateHandle | qsim_state_new | qsim_state_free | 必须释放 |
| QsimSparseHandle | qsim_sparse_new | qsim_sparse_free | 必须释放 |
| QsimMpsHandle | qsim_mps_new | qsim_mps_free | 必须释放 |
| QsimHybridHandle | qsim_hybrid_new | qsim_hybrid_free | 必须释放 |
| *mut StabilizerState | qsim_stabilizer_new | qsim_stabilizer_free | 必须释放 |
| *mut c_char (动态) | to_qasm / gpu_name / hardware_info_json 等 | qsim_string_free | 必须释放 |
| *const c_char (静态) | qsim_version / qsim_error_string | 无需释放 | 静态存储 |
6错误码 (16 个)
| 码 | 常量 | 含义 |
|---|---|---|
| 0 | QSIM_OK | 成功 |
| 1 | QSIM_ERR_NULL_PTR | 空指针 |
| 2 | QSIM_ERR_INVALID_QUBITS | 无效量子比特数 |
| 3 | QSIM_ERR_INVALID_INDEX | 无效索引 |
| 4 | QSIM_ERR_INVALID_PARAM | 无效参数 |
| 5 | QSIM_ERR_OUT_OF_MEMORY | 内存不足 |
| 6 | QSIM_ERR_CANCELLED | 操作取消 |
| 7 | QSIM_ERR_PANIC | FFI 内部 panic (catch_unwind 捕获) |
| 8 | QSIM_ERR_TIMEOUT | 执行超时 |
| 9 | QSIM_ERR_INPUT_TOO_LARGE | 输入过大 |
| 10 | QSIM_ERR_SECURITY_NOT_INIT | 安全上下文未初始化 |
| 11 | QSIM_ERR_SECURITY_DEBUGGER | 检测到调试器 |
| 12 | QSIM_ERR_SECURITY_INTEGRITY | 完整性校验失败 |
| 13 | QSIM_ERR_SECURITY_CANARY | 反 dump canary 失败 |
| 14 | QSIM_ERR_SECURITY_TIMELOCK | 时间锁过期 |
| 15 | QSIM_ERR_SECURITY_THREAT | 威胁评分超阈值 |
7Python 绑定用法
quantum_sim.py 是零依赖 Python 绑定 (仅用标准库 ctypes),无需 pip install 任何包。
7.1 QuantumSim 类 — 核心仿真器
from quantum_sim import QuantumSim, QuantumSimError
# 创建 4 量子比特态向量
sim = QuantumSim(4)
try:
# 应用门
sim.apply_h(0) # Hadamard
sim.apply_x(1) # Pauli-X
sim.apply_cnot(0, 2) # CNOT(0→2)
sim.apply_toffoli(0, 1, 3) # Toffoli(0,1→3)
# 查询
print(f"qubits = {sim.n_qubits}") # 4
print(f"dim = {sim.dim}") # 16
# 测量
result = sim.measure() # 确定性测量 (最大概率态)
p0 = sim.prob_one(0) # qubit 0 为 |1⟩ 的概率
# 振幅
amp = sim.amplitude(0) # Cplx(re, im)
print(f"|00...0⟩ = {amp.re} + {amp.im}i")
print(f"|amp|² = {amp.abs_squared}")
# 归一化
sim.normalize()
except QuantumSimError as e:
print(f"错误 [{e.code}]: {e.msg}")
finally:
sim.close() # 必须释放
# 推荐用 with 语句 (自动释放)
with QuantumSim(2) as sim:
result = sim.bell_state() # 便捷: Bell 态
# sim 自动释放
with QuantumSim(5) as sim:
result = sim.ghz_state() # 便捷: GHZ 态
7.2 QuantumCircuit 类 — 链式电路构建器
from quantum_sim import QuantumSim, QuantumCircuit
# 链式 API 构建电路
circuit = (QuantumCircuit(3)
.h(0) # H(0)
.cnot(0, 1) # CNOT(0→1)
.cnot(1, 2) # CNOT(1→2)
.x(2) # X(2)
)
# 在 QuantumSim 上执行
with QuantumSim(3) as sim:
result = circuit.run(sim)
print(f"结果: {result:#b}")
7.3 VQEChemistry 类 — 量子化学 (Python 侧实现)
from quantum_sim import VQEChemistry
# 支持的分子: H2, LiH, H2O, N2
vqe = VQEChemistry(molecule="H2")
bench = vqe.benchmark()
print(f"H2 基态能量: {bench['estimated_energy_Ha']:.4f} Ha")
print(f"精确能量: {bench['exact_energy_Ha']:.4f} Ha")
print(f"误差: {bench['error_mHa']:.2f} mHa")
print(f"耗时: {bench['runtime_ms']:.1f} ms")
7.4 Cplx 结构
from quantum_sim import Cplx
amp = sim.amplitude(3)
print(amp) # Cplx(0.707107 + 0.000000i)
print(amp.re, amp.im) # 0.707107 0.0
print(amp.abs_squared) # 0.5
8benchmark.py — 基准测试套件
9 节性能基准测试,覆盖单/双比特门、电路吞吐、Bell 态、Grover 算法、测量、振幅、算法验证。
8.1 命令行用法
# 全部测试 (默认 200 次重复)
python benchmark.py
# 快速模式 (50 次重复)
python benchmark.py --quick
# 指定测试 (逗号分隔)
python benchmark.py --only 1,3,5
# 导出 JSON 报告
python benchmark.py --json report.json
# 跳过算法验证 (只测性能)
python benchmark.py --no-verify
8.2 测试节列表
| 编号 | 测试 | 说明 |
|---|---|---|
| 1 | 单比特门吞吐 | H/X/Z/S/T 门每秒操作数 |
| 2 | 双比特门吞吐 | CNOT/CZ 每秒操作数 |
| 3 | 电路吞吐 | 完整电路 (10 门) 每秒执行数 |
| 4 | Bell 态 | Bell 态生成 + 测量延迟 |
| 5 | Grover 算法 | 2-6 qubit Grover 搜索 |
| 6 | 测量延迟 | measure() 单次延迟 |
| 7 | 振幅查询 | amplitude(i) 单次延迟 |
| 8 | 算法验证 | Bell/GHZ/Grover 正确性 |
| 9 | 同类对比 | 与参考实现对比 |
9circuit_test.py — 电路测试套件
30 个内置电路测试 + JSON 外部导入,覆盖 10 个类别。
9.1 命令行用法
# 全部测试 (30 个)
python circuit_test.py
# 列出所有测试用例
python circuit_test.py --list
# 按类别过滤 (逗号分隔)
python circuit_test.py --only bell,ghz
# 导入外部 JSON 电路
python circuit_test.py --import my_circuit.json
# 导出 JSON 报告
python circuit_test.py --json report.json
# 安静模式 (只打印失败)
python circuit_test.py --quiet
9.2 测试类别 (10 类, 30 个用例)
| 类别 | 数量 | 说明 |
|---|---|---|
| basic | 9 | 基本门测试 (H/X/Y/Z/S/T/CNOT/Toffoli/SWAP) |
| bell | 4 | Bell 态变体 |
| ghz | 3 | GHZ 态 (3/4/5 qubit) |
| teleportation | 1 | 量子隐形传态 |
| deutsch_jozsa | 2 | Deutsch-Jozsa 算法 |
| bernstein_vazirani | 1 | Bernstein-Vazirani 算法 |
| qft | 1 | 量子傅里叶变换 |
| grover | 1 | Grover 搜索算法 |
| reversible | 4 | 可逆电路 |
| synthesis | 4 | 电路合成 |
9.3 JSON 电路导入格式
支持两种顶层结构:数组或对象。门类型支持 7 种:H/X/Z/S/T/CNOT/Toffoli。
// 格式 1: 数组 (直接是门列表)
[
{"gate": "H", "q": 0},
{"gate": "CNOT", "q": 0, "q2": 1},
{"gate": "X", "q": 2}
]
// 格式 2: 对象 (含元数据)
{
"name": "Bell 态",
"n_qubits": 2,
"gates": [
{"gate": "H", "q": 0},
{"gate": "CNOT", "q": 0, "q2": 1}
],
"expected": "00|11"
}
| gate | 必填字段 | 可选字段 | 说明 |
|---|---|---|---|
| H | q | - | Hadamard |
| X | q | - | Pauli-X |
| Z | q | - | Pauli-Z |
| S | q | - | S 门 |
| T | q | - | T 门 |
| CNOT | q, q2 | - | q=控制, q2=目标 |
| Toffoli | q, q2, q3 | - | q,q2=控制, q3=目标 |
10C/C++ 对接示例
C/C++ 用户通过 quantum_sim.dll.lib 导入库链接,或用 LoadLibrary 动态加载。
// C 示例: Bell 态
#include <windows.h>
#include <stdio.h>
typedef void* QsimHandle;
typedef int (*qsim_state_new_t)(unsigned int);
typedef int (*qsim_state_apply_h_t)(void*, unsigned int);
typedef int (*qsim_state_apply_cnot_t)(void*, unsigned int, unsigned int);
typedef unsigned long long (*qsim_state_measure_t)(void*);
typedef void (*qsim_state_free_t)(void*);
int main() {
HMODULE dll = LoadLibraryA("quantum_sim.dll");
qsim_state_new_t state_new = (qsim_state_new_t)GetProcAddress(dll, "qsim_state_new");
qsim_state_apply_h_t apply_h = (qsim_state_apply_h_t)GetProcAddress(dll, "qsim_state_apply_h");
qsim_state_apply_cnot_t cnot = (qsim_state_apply_cnot_t)GetProcAddress(dll, "qsim_state_apply_cnot");
qsim_state_measure_t meas = (qsim_state_measure_t)GetProcAddress(dll, "qsim_state_measure");
qsim_state_free_t free_fn = (qsim_state_free_t)GetProcAddress(dll, "qsim_state_free");
QsimHandle h = state_new(2);
apply_h(h, 0);
cnot(h, 0, 1);
unsigned long long result = meas(h);
printf("结果: %llu\n", result);
free_fn(h);
FreeLibrary(dll);
return 0;
}
# 编译 (MSVC)
cl /Fe:bell.exe bell.c /link quantum_sim.dll.lib
# 编译 (MinGW)
gcc -o bell.exe bell.c -L. -lquantum_sim
11支持的功能
4 种后端
StateVector (1-32 qubit) / Sparse (1-64) / MPS (1-100000) / Stabilizer (Clifford, 256)
21 种量子门
H/X/Y/Z/S/T/CZ/CNOT/Toffoli/SWAP/Rx/Ry/Rz/U3/iSWAP/XX/YY/CRx/CRy/CRz/Fredkin
量子算法
Bell/GHZ 态、隐形传态、Deutsch-Jozsa、Bernstein-Vazirani、QFT、Grover、Shor、HHL
量子化学
VQE 教学:H2/LiH/H2O/N2 分子,Jordan-Wigner 变换
QASM 互通
OpenQASM 2.0 导入/导出/执行,沙箱限制 8KB
批量接口
一次 FFI 调用执行整个电路 (上限 65536 门),零拷贝振幅导出
硬件感知
动态查询 CPU/GPU/内存,推荐参数,最大量子比特数计算
数论加速
Fibonacci 查表、Möbius/Mertens 函数、j-不变量、CRT、Ramsey R(5,5)
混合精度
GPU f32 + CPU f64 Kahan 校正 (15 位有效数字),f128 规划中
安全防护
HWID 绑定、调试器检测、完整性校验、反 dump canary、时间锁、威胁评分
拓扑水印
Shor/HHL 算法带 Yang-Baxter 拓扑水印,防篡改
许可证验证
Cloudflare Workers 远程验证,HMAC 分隔符防拼接攻击
12注意事项
- 环境变量
QSIM_DLL_PATH指向的目录 - Python 脚本所在目录
target/release目录 (开发环境)- 系统 PATH
quantum_sim.dll,Linux 用 libquantum_sim.so,macOS 用 libquantum_sim.dylib。本发布包仅含 Windows DLL。
13FAQ
quantum_sim.dll 放在 Python 脚本同目录。或设置 set QSIM_DLL_PATH=C:\path\to\dll。错误码 1 (QSIM_ERR_NULL_PTR) 通常表示加载失败。qsim_hardware_max_qubits 查询基于真实硬件的极限。measure() 返回概率最大的态 (argmax |amplitude|²)。本库不含任何随机源,遵循三非原则。多次运行同电路结果完全一致。qsim_state_copy_amplitudes (FFI) 一次性导出,内存布局与 numpy complex128 兼容。Python 端可用 np.frombuffer(buf, dtype=complex128) 零拷贝。gui feature (cdylib 不链接),LTO 启用。当前 7.11MB 包含 wgpu (GPU 后端) + rayon (并行) + ring (TLS) + ureq (HTTP) 等必要依赖。quantum_sim.dll.lib 导入库,声明 extern "C" 函数原型,调用约定为 C ABI。详见第 10 节示例。cargo build --release -p quantum-sim --lib。circuit_test.py --import circuit.json。JSON 格式见第 9.3 节。支持 7 种门:H/X/Z/S/T/CNOT/Toffoli。qsim_license_activate(license_key) FFI 函数,绑定 HWID,通过 Cloudflare Workers 远程验证。详见 §14 接口。14声明
QuantumSim V0.78.0 — HappyFace Quantum Simulator — 学习教学版