线路执行与工具流程
概述
本页整合了线路执行、结果查看、线路分析与绘图、以及 OpenQASM 导入导出的核心用法,适合作为完整工作流的快速参考。
执行线路与查看结果
普通用户直接调用 Circuit.execute(),返回 ExecutionResult 对象:
from unitarylab.core import Circuit
qc = Circuit(2)
qc.h(0)
qc.cx(0, 1)
result = qc.execute()ExecutionResult 核心字段
result.state:最终状态向量,NumPy 数组。result.probabilities:计算基态的概率分布字典,键为二进制字符串,值为对应概率。result.classical_results_map:经典比特索引到测量值(0或1)的字典,仅在线路中添加了measure操作后才有值。
print(result.state)
# [0.70710678+0.j 0.+0.j 0.+0.j 0.70710678+0.j]
print(result.probabilities)
# {'00': 0.4999..., '11': 0.4999...}result.measure(target_indices) 执行投影测量并坍缩内部状态,返回测量字符串。
result.calculate_state(target_indices) 查看指定比特的概率分布,不坍缩状态。
后端与设备
execute() 支持 backend、device、dtype 参数:
result = qc.execute(backend='torch', device='cpu')| 参数组合 | 适用场景 |
|---|---|
backend='torch', device='cpu' | 默认,适合大多数情况 |
backend='torch', device='gpu' | 有 NVIDIA GPU 时加速 |
backend='numpy', device='cpu' | 纯 NumPy 环境 |
通常直接调用 qc.execute() 无需指定参数;模拟大线路(> 20 量子比特)且有 GPU 时可指定 device='gpu'。
线路分析与绘图
draw()
qc.draw() # 弹出图窗
qc.draw(filename='circuit.png') # 保存为文件
qc.draw(filename='circuit.png', title='Bell State') # 添加标题在 Jupyter Notebook 中图形会内联显示,在普通脚本中会弹出独立窗口。
CircuitInfo
CircuitInfo 提供线路静态分析,可通过 qc.analyze() 快捷调用:
from unitarylab.circuit_analysis.circuit_info import CircuitInfo
info = CircuitInfo(qc) # 等价于 info = qc.analyze()
info.show() # 打印概览、指令列表、层结构常用方法:
| 方法 | 说明 |
|---|---|
size() | 门总数 |
depth() | 线路深度(最长串行路径) |
count_ops() | 各门类型出现次数,返回 dict |
get_qubit_usage() | 各量子比特的操作次数 |
get_coupling_map() | 量子比特耦合关系(双比特门连接) |
get_qubit_history(qubit) | 指定比特的完整操作历史 |
show(sections=[...]) | 按章节打印分析结果 |
show() 支持的 sections 值:'overview'、'instructions'、'layers'、'qubit_usage'、'coupling_map'、'qubit_history'(需同时指定 qubit= 参数)。
info.show(sections=['overview', 'coupling_map'])
info.show(sections='qubit_history', qubit=0)depth() 计算的是串行最长路径(考虑门间数据依赖),不是门总数。get_coupling_map() 返回双比特门连接对,例如 [(0, 1), (1, 2)]。
OpenQASM 导入导出
OpenQASM 3.0 适合保存、交换线路,或与 Qiskit 等工具互操作。
导出
导出函数接受门字典列表(list[dict]),不直接接受 Circuit 对象:
from unitarylab.backend.qasm.qasm_exporter import gate_sequence_to_openqasm3
gates = qc.gate_sequence.data()
gate_dicts = [
{'id': g.id, 'target': list(g.target), 'control': list(g.control)}
for g in gates
]
qasm_str = gate_sequence_to_openqasm3(gate_dicts, qreg_name='q')
print(qasm_str)
# OPENQASM 3.0;
# qubit[2] q;
# h q[0];
# cx q[0], q[1];导入
from unitarylab.backend.qasm.qasm_importer import openqasm3_to_gate_sequence
qasm_code = """
OPENQASM 3.0;
qubit[2] q;
h q[0];
cx q[0], q[1];
"""
gates = openqasm3_to_gate_sequence(qasm_code)
# [{'id': 'h', 'target': 0, ...}, {'id': 'cx', 'target': 1, 'control': 0, ...}]返回的门字典列表可直接传给 gate_sequence_to_openqasm3 进行往返转换;若要重建 Circuit 对象,需手动将字典逐一添加到 GateSequence。
支持范围与限制
支持的门包括:x、y、z、h、s、sdg、t、tdg、rx、ry、rz、p、U、cx、swap,以及受控门修饰符(ctrl @、negctrl @)和自定义 gate 定义。
主要限制:
- 仅支持 OpenQASM 3.0,不兼容 2.0 格式。
- 门参数必须是数值,不支持符号表达式(如
pi/2会被数值化)。 - 不支持经典控制流(
if、while等)。 - 并非所有自定义门都能完整往返导出;非连续块门会内联展开。
综合示例
以下是一个包含执行、查看结果、分析、绘图和导出 OpenQASM 的最小完整示例:
from unitarylab.core import Circuit
from unitarylab.backend.qasm import gate_sequence_to_qasm3
# 1. 创建 Bell 线路
qc = Circuit(2)
qc.h(0)
qc.cx(0, 1)
# 2. 执行线路
result = qc.execute()
# 3. 查看概率
print(result.probabilities)
# {'00': 0.4999..., '11': 0.4999...}
# 4. 线路分析
qc.analyze(show=True, sections=["summary"])
# 5. 绘图
qc.draw(title="Bell State")
# 6. 导出 OpenQASM 3.0
qasm_str = gate_sequence_to_qasm3(qc.gate_sequence)
print(qasm_str)
注意事项
- Qubit 顺序:
probabilities的键为 little-endian 二进制字符串,最低有效位对应 qubit 0。 - 投影测量:
result.measure()会修改内部状态(投影坍缩)。如需多次测量不同子系统,先用result.numpy()保存原始状态向量。 - OpenQASM 自定义门:并非所有自定义门都能完整往返导出;导入后若要重建
Circuit,需手动处理门字典。 - GPU 与后端:默认设置适用于大多数场景,仅在性能调优时需要调整
backend、device、dtype。 - MDX 特殊字符:在 MDX 文件中,表格单元格内容中的
|应写为|;{}、\等特殊字符应放入代码块或行内代码。