可视化
使用 pyqpanda3 内置的绘图和可视化工具来展示量子线路、量子态和模拟结果。
前置条件: 线路构建 -- 在学习本教程之前,您应该已经熟悉如何构建 QProg 和 QCircuit 对象。
目录
概述
pyqpanda3 提供了两个层次的可视化工具:
核心模块(
pyqpanda3.core)-- 线路绘图函数(draw_qprog、PIC_TYPE、set_print_options),可直接生成文本或 LaTeX 表示,无需额外依赖。可视化模块(
pyqpanda3.visualization)-- 丰富的绘图函数(Bloch 球、态城市图、密度矩阵、概率柱状图),依赖 matplotlib 进行图形渲染。
下图展示了这两个层次与您创建的量子对象之间的关系:
graph TD
subgraph "Quantum Objects"
QProg["QProg"]
QCircuit["QCircuit"]
SimResult["Simulator Result"]
StateVec["State Vector"]
end
subgraph "Core Drawing"
DrawQprog["core.draw_qprog()"]
PrintStr["print() / __str__"]
SetPrint["core.set_print_options()"]
PIC_TEXT["PIC_TYPE.TEXT"]
PIC_LATEX["PIC_TYPE.LATEX"]
end
subgraph "visualization Module"
PlotBloch["plot_bloch()"]
PlotState["plot_state()"]
PlotProb["plot_probabilities()"]
CircuitSum["circuit_summary()"]
DrawMember[".draw() method"]
end
QProg --> DrawQprog
QProg --> PrintStr
QProg --> DrawMember
QCircuit --> DrawQprog
QCircuit --> PrintStr
QCircuit --> DrawMember
StateVec --> PlotBloch
StateVec --> PlotState
SimResult --> PlotProb
QProg --> CircuitSum
QCircuit --> CircuitSum
DrawQprog --> PIC_TEXT
DrawQprog --> PIC_LATEX
SetPrint -.-> PrintStr
style QProg fill:#4a90d9,color:#fff
style QCircuit fill:#50b86c,color:#fff
style SimResult fill:#e8913a,color:#fff
style StateVec fill:#7b68ee,color:#fff1. 线路绘图
线路绘图是最常见的可视化任务。它将量子线路渲染为人类可读的图形,展示量子比特线、门、测量操作及其连接关系。pyqpanda3 支持三种输出格式:文本(ASCII 艺术)、图片(matplotlib)和 LaTeX 源代码。
1.1 使用 print() 快速文本输出
可视化线路最快的方式是使用内置的 print() 函数。QProg 和 QCircuit 都实现了 __repr__,因此 print() 会自动渲染文本线路图。
from pyqpanda3 import core
# Build a Bell state circuit
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])
# Quick text rendering
print(prog)运行结果:
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ─┤M├────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ──╫──┤M├
└────┘ ║ └╥┘
c : / ══════════════╩═══╩═
0 1这会生成一个文本线路图,显示量子比特线上的门序列:
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ─┤M├────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ──╫──┤M├
└────┘ ║ └╥┘
c : / ══════════════╩═══╩═
0 1您也可以用同样的方式打印 QCircuit 对象:
circuit = core.QCircuit()
circuit << core.H(0) << core.RY(1, 1.57) << core.CNOT(0, 1)
print(circuit)运行结果:
┌─┐
q_0: |0>─┤H├───────────── ───*──
├─┴────────────┐ ┌──┴─┐
q_1: |0>─┤RY(1.57000000)├ ┤CNOT├
└──────────────┘ └────┘
c : / ════════════════════════输出会在对应的量子比特线上显示每个门,双量子比特门会显示控制和目标标记。
1.2 使用 core.draw_qprog() 绘图
core.draw_qprog() 函数可以更精细地控制输出格式和参数。它接受 QProg 或 QCircuit 作为第一个参数,并通过 PIC_TYPE 枚举来选择输出格式。
可用的图片类型有两种:
| 常量 | 描述 |
|---|---|
core.PIC_TYPE.TEXT | ASCII 文本图(大多数情况下的默认选项) |
core.PIC_TYPE.LATEX | 用于出版级别渲染的 LaTeX 源代码 |
文本输出
from pyqpanda3 import core
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])
# Draw as text with gate parameters shown
result = core.draw_qprog(
prog,
p=core.PIC_TYPE.TEXT,
param_show=True,
line_length=100
)
print(result)运行结果:
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ─┤M├────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ──╫──┤M├
└────┘ ║ └╥┘
c : / ══════════════╩═══╩═
0 1param_show=True 标志会在旋转门上显示数值参数(例如,在 RX 门上显示角度)。
LaTeX 输出
# Draw as LaTeX source code
latex_result = core.draw_qprog(
prog,
p=core.PIC_TYPE.LATEX,
with_logo=False
)
print(latex_result)运行结果:
Latex format is temporarily not supported目前 core.draw_qprog() 的 LaTeX 输出为占位文本。若要获取实际 LaTeX 源代码,请使用下文介绍的 .draw('latex') 成员方法。
保存到文件
文本和 LaTeX 输出都可以直接保存到文件:
# Save text diagram to file
core.draw_qprog(
prog,
p=core.PIC_TYPE.TEXT,
output_file="bell_circuit.txt"
)
# Save LaTeX source to file (via .draw() method)
prog.draw('latex', filename="bell_circuit.tex")output_file 参数将结果写入指定路径。当 output_file 为空(默认)时,函数以字符串形式返回结果。
1.3 draw() 成员方法
QProg 和 QCircuit 都有一个由 visualization 模块注入的 draw() 方法。这为线路绘图提供了便捷的面向对象接口。导入 pyqpanda3 后即可使用该方法。
from pyqpanda3 import core
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1)
# Text output (default)
text = prog.draw()
print(text)
# Explicit text output
text = prog.draw('text')
print(text)运行结果:
┌─┐
q_0: |0>─┤H├ ───*──
└─┘ ┌──┴─┐
q_1: |0>──── ┤CNOT├
└────┘
c : / ═══════════
┌─┐
q_0: |0>─┤H├ ───*──
└─┘ ┌──┴─┐
q_1: |0>──── ┤CNOT├
└────┘
c : / ═══════════draw() 方法接受以下关键字参数:
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
output | str | 'text' | 输出格式:'text'、'pic' 或 'latex' |
filename | str | None | 将输出保存到该文件路径 |
scale | float | 0.7 | 图片缩放因子(仅 'pic' 模式) |
fold | int | 30 | 图片最大宽度(以门数计,仅 'pic' 模式) |
with_logo | bool | False | 在 LaTeX 输出中包含 logo |
with_gate_params | bool | False | 显示门参数 |
line_length | int | 100 | 文本输出的最大行长度 |
console_encode_type | str | 'utf8' | 字符编码:'utf8' 或 'gbk' |
1.4 绘制为图片 (PIC)
'pic' 输出格式使用 matplotlib 渲染彩色线路图并保存为图片文件(JPEG 或 PNG)。这适用于报告、演示文稿和 Jupyter 笔记本。
from pyqpanda3 import core
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])
# Save as JPEG with default filename
prog.draw('pic')
# Save to a custom path with custom scale
prog.draw('pic', filename='my_circuit.png', scale=0.5)
# Show gate parameters in the image
prog.draw('pic', filename='circuit_with_params.jpg', with_gate_params=True)使用 'pic' 输出且不指定文件名时,图片将保存到当前工作目录下的 QCircuit_pic.jpg。
flowchart LR
A["QProg / QCircuit"] --> B[".draw('pic')"]
B --> C["MatplotlibDrawer"]
C --> D["JPEG / PNG file"]
C --> E["Jupyter inline display"]
style A fill:#4a90d9,color:#fff
style D fill:#50b86c,color:#fff
style E fill:#e8913a,color:#fff1.5 LaTeX 输出
LaTeX 输出生成的源代码可以嵌入到学术论文、学位论文或任何 LaTeX 文档中。输出使用 qcircuit 宏包来排版线路图。
from pyqpanda3 import core
prog = core.QProg()
prog << core.H(0) << core.T(1) << core.CNOT(0, 1)
prog << core.measure([0, 1], [0, 1])
# Get LaTeX source code
latex = prog.draw('latex')
print(latex)
# Save to .tex file with logo
prog.draw('latex', filename='paper_circuit.tex', with_logo=True)
# Also accessible via core.draw_qprog (returns placeholder text)
# Use prog.draw('latex') for working LaTeX output运行结果:
\documentclass[border=2px]{standalone}
\usepackage[braket, qm]{qcircuit}
\usepackage{graphicx}
\begin{document}
\scalebox{1.0}{
\Qcircuit @C = 1.0em @R = 0.5em @!R { \\
\nghost{} & \lstick{\ket{q_0}} & \gate{\mathrm{H}} & \qw & \ctrl{1} & \meter & \qw & \rstick{}\qw & \nghost{} \\
...
}}
\end{document}若使用 core.draw_qprog(prog, p=core.PIC_TYPE.LATEX),则目前返回占位文本 Latex format is temporarily not supported。
要将 LaTeX 输出编译为 PDF,您需要安装包含 qcircuit 宏包的 LaTeX 发行版。最简编译命令为:
pdflatex circuit.tex1.6 绘图参数详解
param_show / with_gate_params
默认情况下,参数化门(如 RX、RY、RZ、U3)在绘图时不显示其数值参数。设置 param_show=True(用于 core.draw_qprog)或 with_gate_params=True(用于 .draw())即可显示:
from pyqpanda3 import core
prog = core.QProg()
prog << core.RX(0, 1.5708) << core.RY(1, 0.7854) << core.CNOT(0, 1)
# Without parameters (default)
print(prog.draw())
# With parameters
print(prog.draw(with_gate_params=True))运行结果:
┌──┐
q_0: |0>─┤RX├ ───*──
├──┤ ┌──┴─┐
q_1: |0>─┤RY├ ┤CNOT├
└──┘ └────┘
c : / ════════════
┌──────────────┐
q_0: |0>─┤RX(1.57080000)├ ───*──
├──────────────┤ ┌──┴─┐
q_1: |0>─┤RY(0.78540000)├ ┤CNOT├
└──────────────┘ └────┘
c : / ════════════════════════with_logo
使用 LaTeX 输出时,设置 with_logo=True 会在线路图头部包含 pyqpanda3 的 logo。这主要用于演示和展示。
line_length
控制文本输出中每行的最大字符数。超过此长度的线路会折行显示:
# Short lines for narrow terminals
result = prog.draw('text', line_length=60)expend_map
expend_map 参数控制嵌套线路的展开。传入 {"all": 1} 会将所有嵌套子线路展开为单个门:
# Expand all nested circuits
result = core.draw_qprog(
prog,
p=core.PIC_TYPE.TEXT,
expend_map={"all": 1}
)encode
控制文本输出的字符编码。默认为 "utf-8"。使用 "gbk" 可兼容使用 GBK 编码的终端(在某些中文语言环境中常见)。
2. 打印选项
core.set_print_options() 函数用于配置使用 print() 或 core.draw_qprog() 时显示线路信息的全局默认设置。这会影响当前会话中的所有后续打印操作。
from pyqpanda3 import core
# Configure print options
core.set_print_options(
precision=8, # Decimal places for gate parameters
param_show=True, # Show gate parameters by default
linewidth=100 # Maximum line width
)参数
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
precision | int | 8 | 浮点参数的小数位数 |
param_show | bool | True | 是否显示门参数 |
linewidth | int | 100 | 文本输出的最大行宽 |
使用示例
from pyqpanda3 import core
# Build a circuit with parameterized gates
prog = core.QProg()
prog << core.RX(0, 3.14159265) << core.RY(1, 1.57079633) << core.CNOT(0, 1)
# Default print options
print("Default:")
print(prog)
# Set high precision with parameters visible
core.set_print_options(precision=4, param_show=True, linewidth=80)
print("\nWith options (precision=4, param_show=True):")
print(prog)
# Reset to defaults
core.set_print_options(precision=8, param_show=False, linewidth=100)运行结果:
Default:
┌──────────────┐
q_0: |0>─┤RX(3.14159265)├ ───*──
├──────────────┤ ┌──┴─┐
q_1: |0>─┤RY(1.57079633)├ ┤CNOT├
└──────────────┘ └────┘
c : / ════════════════════════
With options (precision=4, param_show=True):
┌──────────┐
q_0: |0>─┤RX(3.1416)├ ───*──
├──────────┤ ┌──┴─┐
q_1: |0>─┤RY(1.5708)├ ┤CNOT├
└──────────┘ └────┘
c : / ════════════════════精度设置在处理变分线路时特别有用,因为在优化过程中您需要检查参数值。
3. visualization 模块
pyqpanda3.visualization 模块提供了超越基于文本的线路绘制的丰富图形可视化工具。它依赖 matplotlib 进行渲染,提供 Bloch 球图、态城市图可视化、密度矩阵热力图和概率柱状图等功能。
已知兼容性问题(pyqpanda3 0.3.5):本节部分函数存在上游库兼容性问题,包括 numpy 2.x 的
bitwise_xor不兼容和 matplotlib 的w_xaxisAPI 变更。具体异常信息在各小节中标注。函数plot_bloch_vector(),plot_probabilities()和circuit_summary()可正常运行。
3.1 导入模块
# Import specific functions
from pyqpanda3.visualization import (
plot_bloch,
plot_state,
plot_probabilities,
circuit_summary
)
# Or import the module as a whole
import pyqpanda3.visualization as viz该模块还提供了用于特殊场景的底层函数:
from pyqpanda3.visualization import (
plot_bloch_vector,
plot_bloch_multivector,
plot_bloch_circuit,
plot_state_city,
plot_density_matrix,
draw_probability,
draw_probability_dict
)3.2 Bloch 球可视化
Bloch 球是单量子比特量子态的几何表示。任意纯单量子比特态可以写成:
并表示为单位球面上坐标为
可视化模块提供了三个用于 Bloch 球渲染的函数:
plot_bloch_vector(bloch, title, axis_obj, fig_size)
在 3D 球面上绘制单个 Bloch 向量。输入为三个浮点数的列表 [x, y, z],表示 Bloch 向量的笛卡尔坐标。
from pyqpanda3.visualization import plot_bloch_vector
# Plot the |0> state (north pole, z-axis)
plot_bloch_vector([0, 0, 1], title="|0> state")
# Plot the |1> state (south pole)
plot_bloch_vector([0, 0, -1], title="|1> state")
# Plot the |+> state (x-axis)
plot_bloch_vector([1, 0, 0], title="|+> state")
# Plot the |-i> state (-y-axis)
plot_bloch_vector([0, -1, 0], title="|-i> state")
常见的单量子比特态及其 Bloch 向量:
| 量子态 | Bloch 向量 | 描述 |
|---|---|---|
[0, 0, 1] | 北极 | |
[0, 0, -1] | 南极 | |
[1, 0, 0] | +X 方向 | |
[-1, 0, 0] | -X 方向 | |
[0, 1, 0] | +Y 方向 | |
[0, -1, 0] | -Y 方向 |
plot_bloch_multivector(state, title, fig_size)
在各自的 Bloch 球上绘制多量子比特态的每个量子比特。该函数接受一个态矢量(列表或 numpy 数组),并计算每个量子比特的约化密度矩阵以确定其 Bloch 向量。
import numpy as np
from pyqpanda3.visualization import plot_bloch_multivector
# Bell state: (|00> + |11>) / sqrt(2)
# Each qubit is maximally mixed -> Bloch vector at origin
bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2)
plot_bloch_multivector(bell_state, title="Bell State Qubits")
# Product state: |+>|0>
# Qubit 0 at +X, qubit 1 at +Z
product_state = np.array([1, 1, 0, 0]) / np.sqrt(2)
plot_bloch_multivector(product_state, title="|+>|0> State")
对于像 Bell 态这样的纠缠态,每个单独量子比特的约化态是最大混合态,因此 Bloch 向量位于原点。这是纠缠的直观标志。
已知问题:在 pyqpanda3 0.3.5 中,
plot_bloch_multivector()因 numpy 2.x 的bitwise_xor兼容性问题会引发TypeError。该问题待上游修复。
plot_bloch_circuit(circuit, trace, saveas, fps, secs_per_gate)
在 Bloch 球上动画展示单量子比特线路的演化过程。该函数逐门遍历线路,展示每个门如何在球面上旋转态矢量。它支持常见的单量子比特门:H、X、Y、Z、RX、RY、RZ、S、T 及其共轭变体。
from pyqpanda3 import core
from pyqpanda3.visualization import plot_bloch_circuit
# Build a single-qubit circuit
circuit = core.QCircuit()
circuit << core.H(0)
circuit << core.RY(0, 1.5708) # pi/2 rotation
circuit << core.Z(0)
# Animate the circuit on the Bloch sphere
plot_bloch_circuit(
circuit,
trace=True, # Show the path of the state vector
saveas='bloch_animation.gif', # Save as animated GIF
fps=20, # Frames per second
secs_per_gate=1 # Duration per gate in seconds
)
当 trace=True 时,动画会绘制彩色轨迹,显示态矢量在每个门施加后的路径。每个门使用不同的颜色,便于追踪演化过程。
已知问题:在 pyqpanda3 0.3.5 中,
plot_bloch_circuit()因线路节点遍历的AttributeError: 'int' object has no attribute 'get_phy_addr'问题会引发异常。该问题待上游修复。
sequenceDiagram
participant C as Circuit
participant B as Bloch Sphere
Note over B: Initial state: |0> (north pole)
C->>B: H(0)
Note over B: State rotates to |+> (equator, +X)
C->>B: RY(0, pi/2)
Note over B: State rotates around Y axis
C->>B: Z(0)
Note over B: Phase flip around Z axis统一的 plot_bloch() 接口
plot_bloch() 函数提供了统一的接口,能自动检测输入类型并调用相应的函数:
from pyqpanda3 import core
from pyqpanda3.visualization import plot_bloch
# Single Bloch vector (list/tuple of 3 numbers)
plot_bloch([1, 0, 0], title="X State")
# State vector (array-like)
import numpy as np
state = np.array([1, 0, 0, 1]) / np.sqrt(2)
plot_bloch(state, title="Bell State")
# Circuit (single-qubit only)
circuit = core.QCircuit()
circuit << core.H(0) << core.T(0)
plot_bloch(circuit)
已知问题:当
plot_bloch()接收到态矢量或QCircuit类型输入时,会分别委托给plot_bloch_multivector()和plot_bloch_circuit(),因此同样存在上述兼容性问题。仅 Bloch 向量([x, y, z])输入可正常工作。
3.3 态城市图
态城市图提供了量子态密度矩阵的 3D 可视化。它将密度矩阵的实部和虚部分别以并排的柱状图展示,让您直观地了解态的结构。
纯态
plot_state_city(state, title, figsize, color)
import numpy as np
from pyqpanda3.visualization import plot_state_city
# Bell state density matrix
bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2)
plot_state_city(bell_state, title="Bell State Density Matrix")
# Custom colors and figure size
plot_state_city(
bell_state,
title="Bell State",
figsize=(12, 4),
color=["#1f77b4", "#ff7f0e"] # [real color, imaginary color]
)
已知问题:在 pyqpanda3 0.3.5 中,
plot_state_city()因 matplotlib API 变更(w_xaxis属性移除)会引发AttributeError。该问题待上游修复。
该函数接受态矢量(1D 数组)或密度矩阵(2D 数组)。当传入态矢量时,它会自动计算密度矩阵。
左边的子图显示
所有元素都是实数,因此虚部为零,右边的子图显示为平坦表面。
统一的 plot_state() 接口
from pyqpanda3.visualization import plot_state
import numpy as np
state = np.array([1, 0, 0, 1]) / np.sqrt(2)
# City plot (default)
plot_state(state, kind='city', title="Bell State")
# Density matrix heatmap
rho = np.outer(state, np.conj(state))
plot_state(rho, kind='density', title="Bell State")
已知问题:在 pyqpanda3 0.3.5 中,
plot_state(state, kind='density')因 numpy 2.x 兼容性问题会引发TypeError。kind='city'模式则因 matplotlib API 变更存在与plot_state_city()相同的AttributeError。该问题待上游修复。
kind 参数选择可视化类型:'city' 表示 3D 柱状图,'density' 表示带相位着色的热力图。
3.4 密度矩阵可视化
plot_density_matrix() 函数将密度矩阵渲染为 3D 柱状图,其中柱高表示绝对值
import numpy as np
from pyqpanda3.visualization import plot_density_matrix
# Create a mixed state density matrix
rho = np.array([
[0.5, 0.0, 0.0, 0.5],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.5, 0.0, 0.0, 0.5]
])
fig, ax = plot_density_matrix(
rho,
title="Bell State Density Matrix",
xlabels=['00', '01', '10', '11'],
ylabels=['00', '01', '10', '11']
)
已知问题:在 pyqpanda3 0.3.5 中,
plot_density_matrix()因与plot_state_city()相同的 matplotlib API 变更会引发AttributeError。该问题待上游修复。
颜色条映射了从
3.5 概率柱状图
概率柱状图可视化测量结果的分布。它们适用于检查模拟器结果和理解量子线路的输出分布。
plot_probabilities(data, title, figsize, top_k, save)
统一的 plot_probabilities() 函数接受从态标签到概率的字典,或概率的列表/数组:
from pyqpanda3.visualization import plot_probabilities
# From a dictionary
plot_probabilities(
{'00': 0.5, '11': 0.5},
title="Bell State Probabilities"
)
# From a raw array (auto-generates labels)
probs = [0.5, 0, 0, 0.5]
plot_probabilities(probs, title="Bell State")
# Show only top-K most probable outcomes
noisy_results = {
'000': 0.485, '111': 0.492,
'001': 0.008, '010': 0.006,
'100': 0.005, '011': 0.004
}
plot_probabilities(noisy_results, top_k=3, title="Noisy GHZ (top 3)")
当指定 top_k 时,只显示概率最高的 k 个结果。这对于多量子比特线路很有用,因为大部分基态的概率接近零。
draw_probability() 和 draw_probability_dict()
用于向后兼容的底层函数:
from pyqpanda3.visualization import draw_probability, draw_probability_dict
# From a dictionary of counts or probabilities
data = {'00': 497, '11': 503}
draw_probability(data)
# From a probability dictionary (filters zero entries)
draw_probability_dict({'|00>': 0.5, '|11>': 0.5})从模拟结果计算概率
典型的工作流程将模拟与概率可视化结合使用:
from pyqpanda3 import core
from pyqpanda3.visualization import plot_probabilities
# Build and run a circuit
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])
machine = core.CPUQVM()
machine.run(prog, shots=10000)
counts = machine.result().get_counts()
# Convert counts to probabilities
total = sum(counts.values())
probs = {state: count / total for state, count in counts.items()}
# Visualize
plot_probabilities(probs, title="Bell State Measurement (10000 shots)")3.6 线路概要
circuit_summary() 函数提供线路组成的统计概览:包含多少单量子比特门、双量子比特门和多控制门,以及层信息。
from pyqpanda3 import core
from pyqpanda3.visualization import circuit_summary
prog = core.QProg()
prog << core.H(0) << core.H(1)
prog << core.CNOT(0, 1) << core.SWAP(1, 2)
prog << core.measure([0, 1, 2], [0, 1, 2])
# Get summary (optionally display pie chart)
summary = circuit_summary(prog, show=False)
# Print textual summary
print(summary)
# Access statistics programmatically
info = summary.info
print(f"Total nodes: {info.node_num}")
print(f"Single gates: {info.single_gate_num}")
print(f"Two-qubit gates: {info.double_gate_num}")
print(f"Total layers: {info.layer_num}")
print(f"Single layers: {info.single_gate_layer_num}")
print(f"Double layers: {info.double_gate_layer_num}")运行结果:
ProgInfo(single_gate_num=2, double_gate_num=2, multi_control_gate_num=0, node_num=4, single_gate_layer_num=1, double_gate_layer_num=2, layer_num=3)
Total nodes: 4
Single gates: 2
Two-qubit gates: 2
Total layers: 3
Single layers: 1
Double layers: 2当 show=True(默认值)时,circuit_summary() 会显示一对饼图,展示门类型和层类型的分布。这对于快速评估线路复杂度和估算硬件上的执行成本非常有用。
3.7 时序调度图
从 pyqpanda3 0.4.0 开始,visualization 模块可以渲染时序调度图——以时间轴视图展示每个门在每个物理量子比特上的执行时机。这对于理解转译后的线路在真实超导硬件上的行为至关重要,因为门的时长和并行性会影响整体性能。
该工作流程包含三个阶段:
- 转译并导出——分解为原生门,为目标硬件进行转译,然后调用
QProg.to_instruction(backend, is_scheduling=True)生成包含时序数据的指令 JSON 流。 - 解析——使用
parse_instruction_schedule()将 JSON 转换为规范化的InstructionScheduleItem对象。 - 绘制——使用
draw_time_scheduling()渲染 Matplotlib 或 Plotly 时间轴图。
flowchart LR
A["QProg"] --> B["decompose + transpile"]
B --> C["to_instruction()"]
C --> D["parse_instruction_schedule()"]
D --> E["draw_time_scheduling()"]
E --> F["Matplotlib / Plotly figure"]
style A fill:#4a90d9,color:#fff
style F fill:#50b86c,color:#fff构建并导出调度
首先,创建一个线路并为其导出指令做好准备:
from pyqpanda3 import core
from pyqpanda3.transpilation import ChipBackend, decompose
# Build a circuit
qc = core.QCircuit()
qc.append(core.X(core.Qubit(0)))
qc.append(core.H(core.Qubit(1)))
qc.append(core.CNOT(core.Qubit(0), core.Qubit(1)))
q = core.QProg()
q.append(qc)
# Decompose to native gates and transpile
decomposed = decompose(q, ["X1", "RZ", "CZ", "RPhi"])
cb = ChipBackend()
cb.chip_topology_edges = [[0, 1]]
cb.single_gate_timing = 40
cb.double_gate_timing = 80
# Export instruction JSON with timing
instruction = decomposed.to_instruction(cb, offset=1, is_scheduling=True)
print(instruction)运行结果:
[{"RPhi":[1,0.0,90.0,0]},{"RPhi":[2,270.0,90.0,0]},{"RPhi":[1,0.0,90.0,0]},{"RPhi":[2,90.0,90.0,0]},{"CZ":[1,2,0]},{"RPhi":[2,270.0,90.0,0]}]每条指令都是一个单键对象:RPhi 携带 [qubit, angle, phi, start_time],CZ 携带 [q0, q1, start_time],Measure 携带 [[q0, q1, ...], start_time]。
解析并检查调度
from pyqpanda3.visualization import parse_instruction_schedule
items = parse_instruction_schedule(
instruction,
durations={"RPhi": 40, "CZ": 80},
)
for item in items:
print(f"{item.name:8s} q{item.qubits} t={item.start_time:3d} dur={item.duration}")运行结果:
RPhi q(1,) t= 0 dur=40.0
RPhi q(2,) t= 0 dur=40.0
RPhi q(1,) t= 0 dur=40.0
RPhi q(2,) t= 0 dur=40.0
CZ q(1, 2) t= 0 dur=80.0
RPhi q(2,) t= 0 dur=40.0每个 InstructionScheduleItem 都有以下字段:name、qubits(元组)、start_time、duration、params(元组)、order 和 is_marker。end_time 属性返回 start_time + duration。
绘制时间轴
from pyqpanda3.visualization import draw_time_scheduling
fig = draw_time_scheduling(
instruction,
durations={"RPhi": 40, "CZ": 80},
title="Two-Qubit Schedule",
qubit_offset=-1,
)
fig.savefig("schedule.png", dpi=150)
output 参数控制渲染后端:
output="mpl"(默认)——返回 MatplotlibFigure。output="plotly"——返回 PlotlyFigure。
关键绘图参数:
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
output | str | "mpl" | 渲染后端:"mpl" 为 Matplotlib,"plotly" 为 Plotly。 |
durations | dict | None | 门名称到时长的覆盖映射。 |
backend | ChipBackend | None | 时序来源(single_gate_timing、double_gate_timing)。 |
qubit_offset | int | -1 | 显示偏移:-1 将物理 q[1] 映射为显示的 q[0]。 |
title | str | "QProg Instruction Schedule" | 图表标题。 |
merge_common_instructions | bool | False | 合并时间上相邻的相同类型指令。 |
gate_filter | list[str] | None | 仅绘制指定的门名称。 |
filter_measure | bool | False | 从图中移除 Measure 标记。 |
time_range | (float, float) | None | 将绘制限制在指定周期范围内。 |
max_qubits_per_panel | int | None | 垂直分割为每个面板最多 N 个量子比特。 |
当使用 output="plotly" 时,应使用 fig.write_html("schedule.html") 保存交互式图表,而非 fig.savefig()。
完整端到端示例
from pyqpanda3 import core
from pyqpanda3.transpilation import ChipBackend, Transpiler, decompose
from pyqpanda3.visualization import draw_time_scheduling, parse_instruction_schedule
# Build and transpile
qc = core.QCircuit()
qc.append(core.X(core.Qubit(0)))
qc.append(core.H(core.Qubit(1)))
qc.append(core.CNOT(core.Qubit(0), core.Qubit(1)))
q = core.QProg()
q.append(qc)
backend = ChipBackend()
backend.chip_topology_edges = [[0, 1]]
backend.basic_gates = ["RPhi", "CZ"]
backend.single_gate_timing = 40
backend.double_gate_timing = 80
transpiler = Transpiler()
transpiled = transpiler.transpile(q, backend, {}, 2)
# 分解到 X1/RZ/CZ — to_instruction 内部会调用 virtual_z
decomposed = decompose(transpiled, ["X1", "RZ", "CZ"])
instruction = decomposed.to_instruction(backend, offset=1, is_scheduling=True)
# Parse and draw
schedule = parse_instruction_schedule(instruction, backend=backend)
print(f"Total instructions: {len(schedule)}")
print(f"Qubits used: {sorted(set(q for item in schedule for q in item.qubits))}")
fig = draw_time_scheduling(
instruction,
backend=backend,
title="Transpiled Circuit Schedule",
merge_common_instructions=True,
)
fig.savefig("transpiled_schedule.png", dpi=150)运行结果:
Total instructions: 5
Qubits used: [1, 2]时长按优先级顺序解析:(1) 显式的 durations 字典,(2) 后端时序属性,(3) 门负载时长(用于 IDLE),(4) 缺失的时长变为零时长标记。
4. 实用示例
4.1 绘制 Bell 态线路
这个完整示例构建一个 Bell 态线路,并演示所有三种输出格式:
from pyqpanda3 import core
# Build the Bell state circuit
prog = core.QProg()
prog << core.H(0)
prog << core.CNOT(0, 1)
prog << core.measure([0, 1], [0, 1])
# 1. Quick text print
print("=== Text via print() ===")
print(prog)
# 2. Text with parameters via core.draw_qprog
print("\n=== Text via draw_qprog ===")
text = core.draw_qprog(prog, p=core.PIC_TYPE.TEXT, param_show=True)
print(text)
# 3. LaTeX output
print("\n=== LaTeX ===")
latex = core.draw_qprog(prog, p=core.PIC_TYPE.LATEX)
print(latex)
# 4. Save as image
prog.draw('pic', filename='bell_state.jpg')
print("\nImage saved to bell_state.jpg")运行结果:
=== Text via print() ===
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ─┤M├────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ──╫──┤M├
└────┘ ║ └╥┘
c : / ══════════════╩═══╩═
0 1
=== Text via draw_qprog ===
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ─┤M├────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ──╫──┤M├
└────┘ ║ └╥┘
c : / ══════════════╩═══╩═
0 1
=== LaTeX ===
Latex format is temporarily not supported
Image saved to bell_state.jpg4.2 绘制参数化线路
参数化线路在变分算法中很常见。使用 param_show=True 或 with_gate_params=True 可以在线路图中查看参数值:
import math
from pyqpanda3 import core
# Build a parameterized circuit
prog = core.QProg()
prog << core.H(0)
prog << core.RY(0, math.pi / 4)
prog << core.RX(1, math.pi / 3)
prog << core.CNOT(0, 1)
prog << core.RZ(0, 0.7854)
prog << core.U3(1, 0.1, 0.2, 0.3)
prog << core.measure([0, 1], [0, 1])
# Draw without parameters
print("Without parameters:")
print(prog.draw())
# Draw with parameters
print("\nWith parameters:")
print(prog.draw(with_gate_params=True))
# Save image with parameters visible
prog.draw('pic', filename='param_circuit.jpg', with_gate_params=True)
# Set global print options so parameters always show
core.set_print_options(precision=4, param_show=True)
print("\nAfter set_print_options:")
print(prog)运行结果:
Without parameters:
┌─┐ ┌──┐ ┌──┐ ┌─┐
q_0: |0>─┤H├─ ┤RY├ ───*── ┤RZ├ ─┤M├────
├─┴┐ └──┘ ┌──┴─┐ ├──┤ └╥┘ ┌─┐
q_1: |0>─┤RX├ ──── ┤CNOT├ ┤U3├ ──╫──┤M├
└──┘ └────┘ └──┘ ║ └╥┘
c : / ═════════════════════════╩═══╩═
0 1
With parameters:
┌─┐ ┌──────────────┐ ┌──────────────┐ ┌─┐
q_0: |0>─┤H├───────────── ┤RY(0.78539816)├ ───*── ┤RZ(0.78540000)├──────────────────────── ─┤M├────
├─┴────────────┐ └──────────────┘ ┌──┴─┐ ├──────────────┴───────────────────────┐ └╥┘ ┌─┐
q_1: |0>─┤RX(1.04719755)├ ──────────────── ┤CNOT├ ┤U3(0.10000000, 0.20000000, 0.30000000)├ ──╫──┤M├
└──────────────┘ └────┘ └──────────────────────────────────────┘ ║ └╥┘
c : / ═════════════════════════════════════════════════════════════════════════════════════╩═══╩═
0 1
After set_print_options:
┌─┐ ┌──────────┐ ┌──────────┐ ┌─┐
q_0: |0>─┤H├───────── ┤RY(0.7854)├ ───*── ┤RZ(0.7854)├──────────────── ─┤M├────
├─┴────────┐ └──────────┘ ┌──┴─┐ ├──────────┴───────────────┐ └╥┘ ┌─┐
q_1: |0>─┤RX(1.0472)├ ──────────── ┤CNOT├ ┤U3(0.1000, 0.2000, 0.3000)├ ──╫──┤M├
└──────────┘ └────┘ └──────────────────────────┘ ║ └╥┘
c : / ═════════════════════════════════════════════════════════════════╩═══╩═
0 14.3 绘制大规模线路
大规模线路需要仔细管理行长度和图片尺寸。以下是处理多量子比特或多门线路的技巧:
from pyqpanda3 import core
# Build a 6-qubit GHZ-like circuit
prog = core.QProg()
prog << core.H(0)
for i in range(1, 6):
prog << core.CNOT(i - 1, i)
prog << core.measure(list(range(6)), list(range(6)))
# Use longer line length for wide circuits
text = core.draw_qprog(prog, p=core.PIC_TYPE.TEXT, line_length=150)
print(text)
# For image output, use a larger fold value to fit more gates per row
prog.draw('pic', filename='large_circuit.jpg', fold=50, scale=0.5)运行结果:
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ───────┤M├ ────────── ────────── ────────── ────────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ───*────╫─ ───────┤M├ ────────── ────────── ────────
└────┘ ┌──┴─┐ ║ └╥┘ ┌─┐
q_2: |0>──── ────── ┤CNOT├──╫─ ───*────╫─ ───────┤M├ ────────── ────────
└────┘ ║ ┌──┴─┐ ║ └╥┘ ┌─┐
q_3: |0>──── ────── ────────╫─ ┤CNOT├──╫─ ───*────╫─ ───────┤M├ ────────
║ └────┘ ║ ┌──┴─┐ ║ └╥┘ ┌─┐
q_4: |0>──── ────── ────────╫─ ────────╫─ ┤CNOT├──╫─ ───*────╫─ ─┤M├────
║ ║ └────┘ ║ ┌──┴─┐ ║ └╥┘ ┌─┐
q_5: |0>──── ────── ────────╫─ ────────╫─ ────────╫─ ┤CNOT├──╫─ ──╫──┤M├
║ ║ ║ └────┘ ║ ║ └╥┘
c : / ════════════════════╩══════════╩══════════╩══════════╩════╩═══╩═
0 1 2 3 4 5对于非常大的线路(20+ 量子比特),文本输出可能变得难以管理。在这些情况下,请使用 LaTeX 输出并编译为 PDF,或使用 circuit_summary() 查看统计数据而非完整图形:
from pyqpanda3.visualization import circuit_summary
# Get statistics instead of full diagram
summary = circuit_summary(prog, show=True)
print(f"\nCircuit has {summary.info.node_num} gates across {summary.info.layer_num} layers")运行结果:
Circuit has 6 gates across 6 layers4.4 导出到文件
pyqpanda3 支持以多种文件格式导出线路图,以适应不同的使用场景:
from pyqpanda3 import core
prog = core.QProg()
prog << core.H(0) << core.CNOT(0, 1) << core.measure([0, 1], [0, 1])
# Text file (useful for version control and diffs)
core.draw_qprog(prog, p=core.PIC_TYPE.TEXT, output_file="circuit.txt")
# LaTeX file (for papers and presentations)
prog.draw('latex', filename="circuit.tex", with_logo=True)
# Image file (for reports and quick sharing)
prog.draw('pic', filename='circuit_diagram.png', scale=0.7)
# Alternative: use the draw() method with filename
prog.draw('text', filename='circuit_text.txt')
prog.draw('latex', filename='circuit_latex.tex')下表总结了输出格式及其典型使用场景:
| 格式 | 文件扩展名 | 最佳用途 |
|---|---|---|
| 文本 | .txt | 调试、终端输出、版本控制 |
| LaTeX | .tex | 学术论文、演示文稿、文档 |
| 图片 | .jpg、.png | 报告、幻灯片、快速分享、Jupyter |
flowchart TD
A["QProg / QCircuit"] --> B{Choose Format}
B -->|Terminal / Debug| C["Text (.txt)"]
B -->|Paper / Presentation| D["LaTeX (.tex)"]
B -->|Report / Quick View| E["Image (.jpg/.png)"]
C --> F["print() or .draw('text')"]
D --> G[".draw('latex')"]
E --> H[".draw('pic')"]
F --> I["Console output or text file"]
G --> J["pdflatex -> PDF"]
H --> K["JPEG/PNG image file"]
style A fill:#4a90d9,color:#fff
style I fill:#50b86c,color:#fff
style J fill:#7b68ee,color:#fff
style K fill:#e8913a,color:#fff4.5 GHZ 态端到端可视化
本示例演示了一个完整的工作流程:构建线路、进行模拟、绘制线路图以及可视化结果。
from pyqpanda3 import core
from pyqpanda3.visualization import plot_probabilities, plot_bloch_multivector, circuit_summary
# Build a 3-qubit GHZ state circuit
prog = core.QProg()
prog << core.H(0)
prog << core.CNOT(0, 1)
prog << core.CNOT(1, 2)
prog << core.measure([0, 1, 2], [0, 1, 2])
# Step 1: Draw the circuit
print("=== Circuit Diagram ===")
print(prog.draw())
# Step 2: Get circuit statistics
print("\n=== Circuit Summary ===")
summary = circuit_summary(prog, show=False)
print(f"Gates: {summary.info.node_num}, Layers: {summary.info.layer_num}")
print(f"Single-qubit gates: {summary.info.single_gate_num}")
print(f"Two-qubit gates: {summary.info.double_gate_num}")
# Step 3: Simulate
machine = core.CPUQVM()
machine.run(prog, shots=10000)
# Step 4: Visualize probabilities
counts = machine.result().get_counts()
total = sum(counts.values())
probs = {state: count / total for state, count in counts.items()}
plot_probabilities(probs, title="GHZ State Probabilities (10000 shots)")
# Step 5: Visualize the GHZ state on Bloch spheres
# (requires the state vector before measurement)
ghz_circuit = core.QCircuit()
ghz_circuit << core.H(0) << core.CNOT(0, 1) << core.CNOT(1, 2)
state = ghz_circuit.matrix()[:, 0] # first column = |000> input
plot_bloch_multivector(state, title="GHZ State (Per-Qubit Bloch)")运行结果:
=== Circuit Diagram ===
┌─┐ ┌─┐
q_0: |0>─┤H├ ───*── ───────┤M├ ────────
└─┘ ┌──┴─┐ └╥┘ ┌─┐
q_1: |0>──── ┤CNOT├ ───*────╫─ ─┤M├────
└────┘ ┌──┴─┐ ║ └╥┘ ┌─┐
q_2: |0>──── ────── ┤CNOT├──╫─ ──╫──┤M├
└────┘ ║ ║ └╥┘
c : / ════════════════════╩════╩═══╩═
0 1 2
=== Circuit Summary ===
Gates: 3, Layers: 3
Single-qubit gates: 1
Two-qubit gates: 2已知问题:在 pyqpanda3 0.3.5 中,
plot_bloch_multivector()因 numpy 2.x 兼容性问题会引发TypeError。此步骤在上述问题修复前无法正常执行。
对于 GHZ 态
4.6 单量子比特线路的 Bloch 球动画
本示例创建一个动画 Bloch 球可视化,展示一系列门如何变换单个量子比特:
import math
from pyqpanda3 import core
from pyqpanda3.visualization import plot_bloch_circuit, plot_bloch_vector
# Build a single-qubit circuit with several gates
circuit = core.QCircuit()
circuit << core.H(0) # Move to equator (+X)
circuit << core.T(0) # Rotate pi/4 around Z
circuit << core.RY(0, math.pi/4) # Tilt toward +Z
circuit << core.Z(0) # Flip phase
# Animate the circuit on the Bloch sphere
plot_bloch_circuit(
circuit,
trace=True,
saveas='single_qubit_evolution.gif',
fps=20,
secs_per_gate=1
)
# Static visualization of specific states
from pyqpanda3.visualization import plot_bloch
# Show the |0> starting state
plot_bloch([0, 0, 1], title="Initial |0> state")
# Show the state after Hadamard (|+>)
plot_bloch([1, 0, 0], title="After H: |+> state")
# Show the state after H then T
plot_bloch([1/math.sqrt(2), 1/math.sqrt(2), 0], title="After H+T")已知问题:在 pyqpanda3 0.3.5 中,
plot_bloch_circuit()因线路节点遍历问题会引发AttributeError,该功能暂时无法正常使用。单独调用plot_bloch([x, y, z])或plot_bloch_vector([x, y, z])可正常工作。
动画按顺序展示每个门,显示态矢量在球面上的旋转。trace=True 参数会留下彩色轨迹,让您可以看到态矢量的完整路径。
5. 可视化工作流程
下图展示了 pyqpanda3 中从线路构建到可视输出的完整可视化工作流程:
flowchart TD
A["Build Circuit<br/>(QProg / QCircuit)"] --> B{What to visualize?}
B -->|"Circuit diagram"| C{Output format?}
C -->|"Quick view"| D["print(prog)"]
C -->|"Text file"| E["core.draw_qprog(..., TEXT)"]
C -->|"LaTeX / PDF"| F["prog.draw('latex')"]
C -->|"Image"| G["prog.draw('pic')"]
B -->|"Quantum state"| H{How many qubits?}
H -->|"1 qubit"| I["plot_bloch_vector()"]
H -->|"Multi-qubit"| J["plot_bloch_multivector()"]
H -->|"Density matrix"| K["plot_state_city() or plot_density_matrix()"]
B -->|"Measurement results"| L["plot_probabilities()"]
B -->|"Circuit statistics"| M["circuit_summary()"]
B -->|"State evolution"| N["plot_bloch_circuit()"]
B -->|"Instruction timing"| O["draw_time_scheduling()"]
style A fill:#4a90d9,color:#fff
style D fill:#50b86c,color:#fff
style E fill:#50b86c,color:#fff
style F fill:#7b68ee,color:#fff
style G fill:#e8913a,color:#fff
style I fill:#c0392b,color:#fff
style J fill:#c0392b,color:#fff
style K fill:#c0392b,color:#fff
style L fill:#2ecc71,color:#fff
style M fill:#2ecc71,color:#fff
style N fill:#c0392b,color:#fff
style O fill:#c0392b,color:#fff选择指南
| 您的目标 | 推荐函数 |
|---|---|
| 快速查看线路 | print(prog) |
| 将线路保存为文本文件 | core.draw_qprog(prog, p=core.PIC_TYPE.TEXT, output_file='out.txt') |
| 用于报告的线路图片 | prog.draw('pic', filename='circuit.jpg') |
| 用于论文的线路(LaTeX) | prog.draw('latex', filename='circuit.tex') |
| 查看门参数 | prog.draw(with_gate_params=True) 或 core.set_print_options(param_show=True) |
| 检查单量子比特态 | plot_bloch_vector([x, y, z]) |
| 检查多量子比特态 | plot_bloch_multivector(state_vector) |
| 查看密度矩阵结构 | plot_state_city(state) 或 plot_state(state, kind='density') |
| 查看测量分布 | plot_probabilities(counts_dict) |
| 动画展示单量子比特演化 | plot_bloch_circuit(circuit) |
| 获取线路门统计信息 | circuit_summary(prog) |
| 可视化指令时序 | draw_time_scheduling(instruction, backend=...) |
6. API 快速参考
核心模块 (pyqpanda3.core)
| 函数 / 常量 | 描述 |
|---|---|
core.draw_qprog(prog, p, ...) | 将线路绘制为文本或 LaTeX |
core.PIC_TYPE.TEXT | 文本输出格式 |
core.PIC_TYPE.LATEX | LaTeX 输出格式 |
core.set_print_options(precision, param_show, linewidth) | 配置全局打印设置 |
core.draw_qprog() 参数
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
prog | QProg 或 QCircuit | (必需) | 要绘制的线路 |
p | PIC_TYPE | PIC_TYPE.TEXT | 输出格式 |
expend_map | dict | None | 控制展开,如 {"all": 1} |
param_show | bool | False | 显示门参数 |
with_logo | bool | False | 包含 logo(仅 LaTeX) |
line_length | int | 100 | 最大行长度(仅文本) |
output_file | str | "" | 保存到文件(空值 = 返回字符串) |
encode | str | "utf-8" | 字符编码 |
成员方法 (.draw())
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
output | str | 'text' | 'text'、'pic' 或 'latex' |
filename | str | None | 输出文件路径 |
scale | float | 0.7 | 图片缩放(仅 pic 模式) |
fold | int | 30 | 图片最大宽度,以门数计(仅 pic 模式) |
with_logo | bool | False | 包含 logo(仅 LaTeX) |
with_gate_params | bool | False | 显示门参数 |
line_length | int | 100 | 最大行长度(仅文本) |
console_encode_type | str | 'utf8' | 'utf8' 或 'gbk' |
可视化模块 (pyqpanda3.visualization)
总结
在本教程中,您学习了:
线路绘图 -- 使用
print(prog)进行快速检查,使用core.draw_qprog()进行可控输出,使用.draw()获取面向对象的接口。提供三种输出格式:文本(ASCII)、图片(matplotlib)和 LaTeX。打印选项 --
core.set_print_options()配置所有基于文本的线路输出的精度、参数可见性和行宽。Bloch 球 -- 使用
plot_bloch_vector()可视化单量子比特态,使用plot_bloch_multivector()按量子比特可视化多量子比特态,使用plot_bloch_circuit()动画展示单量子比特线路的演化。态可视化 -- 使用
plot_state_city()绘制密度矩阵的 3D 柱状图,使用plot_density_matrix()绘制带相位着色的热力图,使用plot_state()作为统一接口。概率图 --
plot_probabilities()渲染测量结果分布,对于大状态空间可使用top_k过滤。导出 -- 使用
output_file或filename参数将图形保存为文本文件、LaTeX 源文件或 JPEG/PNG 图片。时序调度 -- 使用
parse_instruction_schedule()将QProg.to_instruction()的指令 JSON 解析为规范化的调度项,并利用draw_time_scheduling()绘制每个量子比特的时序图。
本系列的下一个教程是转译,您将在其中学习如何针对特定硬件拓扑和门集优化线路。