Bloch Sphere Visualization
API reference for Bloch sphere visualization functions in pyqpanda3. These functions render single-qubit states and circuits as interactive or static plots on the Bloch sphere.
plot_bloch
Unified entry point that automatically dispatches to the appropriate Bloch visualization function based on the input type.
Signature
plot_bloch(
state,
title: str = '',
figsize: Optional[tuple] = None,
save: Optional[str] = None
)Parameters
| Parameter | Type | Description |
|---|---|---|
| state | array_like or QCircuit | Input to visualize. A 3-element list/tuple dispatches to plot_bloch_vector; a longer iterable dispatches to plot_bloch_multivector; a QCircuit or QProg dispatches to plot_bloch_circuit. |
| title | str | Plot title (default ''). |
| figsize | tuple, optional | Figure size in inches (default (5, 5) for vector/state inputs; ignored for circuit inputs). |
| save | str, optional | File path to save the output image (only effective for circuit inputs; for vector/state inputs, save the returned figure manually via fig.savefig()). |
Returns
matplotlib.figure.Figurewhen visualizing a vector or state.Nonewhen visualizing aQCircuitorQProg(animation is displayed or saved to file).
Dispatch Behavior
| Input Type | Dispatches To |
|---|---|
list / tuple of length 3 | plot_bloch_vector |
| Any iterable (e.g., state vector) | plot_bloch_multivector |
QCircuit / QProg | plot_bloch_circuit |
Examples
from pyqpanda3.visualization import plot_bloch
# Single Bloch vector (|+> state on X axis)
plot_bloch([1, 0, 0], title="X State")
# Multi-qubit state vector
plot_bloch([1, 0, 0, 0], title="Bell-like State")
# Save to file
fig = plot_bloch([0, 0, 1], title="Z State")
fig.savefig("bloch.png")
plot_bloch_vector
Plot a single 3-element Bloch vector on a Bloch sphere.
Signature
plot_bloch_vector(
bloch,
title="bloch",
axis_obj=None,
fig_size=None
)Parameters
| Parameter | Type | Description |
|---|---|---|
| bloch | array_like | A 3-element sequence [x, y, z] representing the Bloch vector. |
| title | str | Plot title (default "bloch"). |
| axis_obj | matplotlib.axes.Axes, optional | An existing 3D axes to draw on. If None, a new figure is created. |
| fig_size | tuple, optional | Figure size in inches (default (5, 5)). |
Returns
Examples
from pyqpanda3.visualization import plot_bloch_vector
# |0> state (north pole)
plot_bloch_vector([0, 0, 1], title="|0> State")
# |+> state (positive X axis)
plot_bloch_vector([1, 0, 0], title="|+> State")
# |+i> state (positive Y axis)
plot_bloch_vector([0, 1, 0], title="|+i> State")
plot_bloch_multivector
Plot one Bloch sphere per qubit for a multi-qubit quantum state. Each sphere shows the reduced Bloch vector for that qubit computed via the partial trace.
Signature
plot_bloch_multivector(
state,
title='',
fig_size=None
)Parameters
| Parameter | Type | Description |
|---|---|---|
| state | array_like | Quantum state vector. Length must be a power of 2 (e.g., 4 for 2 qubits, 8 for 3 qubits). |
| title | str | Overall figure title (default ''). |
| fig_size | tuple, optional | Figure size in inches. |
Returns
matplotlib.figure.Figure -- the figure containing all Bloch sphere subplots.
Examples
import numpy as np
from pyqpanda3.visualization import plot_bloch_multivector
# Two-qubit state: both qubits in |+> (equal superposition)
plot_bloch_multivector([0.5, 0.5, 0.5, 0.5], title="Two Qubits in |+>")
# Single qubit in |0> state
plot_bloch_multivector([1, 0], title="Single Qubit |0>")
# Bell state |00> + |11> (each qubit reduced state is maximally mixed)
plot_bloch_multivector(np.array([1, 0, 0, 1]) / np.sqrt(2), title="Bell State")
plot_bloch_circuit
Animate a single-qubit quantum circuit on a Bloch sphere. The state vector is updated frame-by-frame as each gate is applied, producing a smooth rotation animation.
Signature
plot_bloch_circuit(
circuit,
trace=True,
saveas=None,
fps=20,
secs_per_gate=1
)Parameters
| Parameter | Type | Description |
|---|---|---|
| circuit | QCircuit or QProg | Single-qubit quantum circuit to animate. Only supports gates: H, X, Y, Z, RX, RY, RZ, S, S†, T, T†, U1. |
| trace | bool | Whether to display the path traced by the state vector (default True). |
| saveas | str, optional | File path to save the animation (e.g., 'bloch.gif'). If None, the animation is displayed interactively. |
| fps | int | Frames per gate, controlling animation smoothness (default 20). |
| secs_per_gate | float | Duration in seconds for each gate's animation segment (default 1). |
Returns
None. The animation is displayed interactively or saved to a file specified by saveas.
Supported Gates
| Gate | Notes |
|---|---|
H | Hadamard |
X, Y, Z | Pauli gates |
RX, RY, RZ | Parameterized rotations (angle in radians) |
S, S† | Phase and inverse phase |
T, T† | T gate and inverse T gate |
U1 | Single-parameter phase gate |
Raises
ImportError-- if Matplotlib is not installed.RuntimeError-- if the circuit is empty, contains unsupported gates, or acts on more than one qubit.
Examples
from pyqpanda3.core import QProg, H, RX, Qubit
from pyqpanda3.visualization import plot_bloch_circuit
# Simple Hadamard circuit
q = Qubit(0)
prog = QProg()
prog << H(q)
# Display interactive animation
plot_bloch_circuit(prog)
# Save animation to file
plot_bloch_circuit(prog, saveas="hadamard.gif", fps=30)
# Rotation circuit with trace
prog2 = QProg()
prog2 << RX(q, 3.14159) << H(q)
plot_bloch_circuit(prog2, trace=True, secs_per_gate=2)
Bloch (class)
Low-level class for building a Bloch sphere plot incrementally. Accessible via pyqpanda3.visualization.bloch.Bloch. Use this when you need finer control than the plot_bloch_* helpers provide -- e.g., adding multiple vectors, points, or annotations onto the same sphere with custom styling.
Constructor
Bloch(
fig=None,
axes=None,
view=None,
figsize=None,
background=False
)Constructor Parameters
| Parameter | Type | Description |
|---|---|---|
| fig | matplotlib.figure.Figure, optional | User-supplied Matplotlib figure for the Bloch sphere. If None, one is created on render. |
| axes | matplotlib.axes.Axes, optional | User-supplied 3D axes for Bloch sphere animation. If None, axes are created on render. |
| view | list, optional | Azimuthal and elevation viewing angles [azim, elev] (default [-60, 30]). |
| figsize | list, optional | Figure size in inches [w, h] (default [5, 5]). |
| background | bool | If True, render the default 3D axes background instead of the bare sphere (default False). |
Selected Attributes (configurable after construction)
| Attribute | Default | Description |
|---|---|---|
sphere_color | "#FFDDDD" | Color of the Bloch sphere surface. |
sphere_alpha | 0.2 | Transparency of the sphere surface. |
frame_color | "gray" | Color of the wireframe. |
frame_width | 1 | Width of the wireframe lines. |
frame_alpha | 0.2 | Transparency of the wireframe. |
font_color | matplotlib default | Color used for axis labels. |
font_size | 20 | Font size used for axis labels. |
xlabel / ylabel / zlabel | ["$x$", ""] / ["$y$", ""] / [r"$|0\rangle$", r"$|1\rangle$"] | Axis label pairs (+axis, -axis). |
xlpos / ylpos / zlpos | [1.2, -1.2] | Label positions for each axis. |
vector_color | ["#dc267f", "#648fff", "#fe6100", "#785ef0", "#ffb000"] | Cycle of colors used for plotted vectors. |
vector_width | 5 | Width of plotted vectors. |
vector_style | `"- | >"` |
vector_mutation | 20 | Arrowhead size. |
point_color | ["b", "r", "g", "#CC6600"] | Cycle of colors used for plotted points. |
point_size | [25, 32, 35, 45] | Cycle of marker sizes. |
point_marker | ["o", "s", "d", "^"] | Cycle of marker shapes. |
Methods
| Method | Signature | Description |
|---|---|---|
add_vectors | add_vectors(vectors) | Append one vector (3 elements) or a list of vectors. |
add_points | add_points(points, meth="s") | Append points; meth is "s" (single color), "m" (multicolored), or "l" (connected by line). |
add_annotation | add_annotation(state_or_vector, text, **kwargs) | Add a text/LaTeX annotation at a 3D position. Extra kwargs are forwarded to mpl_toolkits.mplot3d.axes3d.Axes3D.text (e.g., fontsize, color, horizontalalignment). |
set_label_convention | set_label_convention(convention) | Apply a preset label set. Valid values: "original", "xyz", "sx sy sz", "01", "polarization jones", "polarization jones letters", "polarization stokes". |
clear | clear() | Reset all stored points, vectors, and annotations. |
render | render(title="") | Render the sphere and all data onto the current figure and axes. |
make_sphere | make_sphere() | Alias for render() with no title. |
show | show(title="") | Render the sphere and call pyplot.show(). |
save | save(name=None, output="png", dirc=None) | Render and save to file. If name is given, it overrides output and dirc. Defaults to bloch_<n>.png in the current working directory. |
Examples
from pyqpanda3.visualization.bloch import Bloch
# Build a custom Bloch sphere with two vectors and an annotation
sphere = Bloch()
sphere.add_vectors([1, 0, 0])
sphere.add_vectors([0, 0, 1])
sphere.add_annotation([0, 0, 1.2], r"$|0\rangle$")
sphere.set_label_convention("01")
sphere.save(name="two_states.png")
# Save to file
sphere2 = Bloch(view=[-30, 20], figsize=[6, 6])
sphere2.add_vectors([0, 1, 0])
sphere2.save(name="my_bloch.png")