Skip to content

Quantum State Visualization

Functions for visualizing quantum state vectors and density matrices as 3D bar plots.

plot_state

Unified interface for plotting quantum state vectors or density matrices. Dispatches to the appropriate visualization based on the kind parameter.

Signature

python
plot_state(state, kind: str = 'city', title: str = '', figsize: Optional[tuple] = None)

Parameters

ParameterTypeDescription
statearray_likeQuantum state vector or density matrix
kindstrVisualization type: 'city' or 'density' (default 'city')
titlestrPlot title (default '')
figsizetuple or NoneFigure size in inches, e.g. (15, 5) (default None)

Description

When kind='city', delegates to plot_state_city which renders side-by-side 3D bar charts of the real and imaginary parts of the density matrix. When kind='density', delegates to plot_density_matrix which renders a 3D bar chart with phase-based coloring.

Examples

python
import numpy as np
from pyqpanda3.visualization import plot_state

# Create a Bell state density matrix
state = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=complex)

# Plot as cityscape (real/imaginary 3D bars)
plot_state(state, kind='city', title='Bell State')

# Plot as density matrix (phase-colored 3D bars)
plot_state(state, kind='density', title='Bell State')

plot_state_city

Plots the real and imaginary parts of a quantum state density matrix as side-by-side 3D bar plots.

Signature

python
plot_state_city(state, title="", figsize=None, color=None, ax_real=None, ax_imag=None)

Parameters

ParameterTypeDescription
statelist[complex]Quantum state vector or density matrix
titlestrPlot title (default "")
figsizetuple or NoneFigure size in inches (default (15, 5) when creating a new figure)
colorlist or NoneA list of two colors for the real and imaginary parts, e.g. ["#648fff", "#648fff"] (default None)
ax_realmatplotlib.axes.Axes or NoneExisting 3D axes for the real part plot (default None)
ax_imagmatplotlib.axes.Axes or NoneExisting 3D axes for the imaginary part plot (default None)

Returns

matplotlib.figure.Figure -- The figure object containing the plots.

Description

Converts the input state to a density matrix via state_to_density_matrix, then renders two 3D bar charts: the left chart shows the real part of ρ and the right chart shows the imaginary part of ρ. Each bar corresponds to an element of the density matrix, with x/y axes labeled using binary state strings.

When ax_real and ax_imag are both None, a new figure is created. Pass existing axes to embed the plot into a custom figure layout.

Examples

python
import numpy as np
from pyqpanda3.visualization import plot_state_city

# Bell state vector
state = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=complex)

# Basic plot
plot_state_city(state, title="Bell State (City Plot)")

# Custom colors and figure size
plot_state_city(state, title="Custom Colors", figsize=(12, 4), color=["#e76f51", "#2a9d8f"])

# Plot onto existing axes
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
ax2 = fig.add_subplot(1, 2, 2, projection='3d')
plot_state_city(state, ax_real=ax1, ax_imag=ax2, title="Embedded Plot")

plot_density_matrix

Plots a density matrix as a 3D bar chart where bar height represents the absolute value and color represents the complex phase.

Signature

python
plot_density_matrix(M, xlabels=None, ylabels=None,
                    title=None, limits=None, phase_limits=None, fig=None, axis_vals=None,
                    threshold=None)

Parameters

ParameterTypeDescription
Mlist[complex] or numpy.ndarrayDensity matrix (2D array of complex numbers)
xlabelslist[str] or NoneLabels for the x-axis ticks (default None)
ylabelslist[str] or NoneLabels for the y-axis ticks (default None)
titlestr or NonePlot title (default None)
limitslist or NoneZ-axis limits as [z_min, z_max] (default None, auto-scaled)
phase_limitslist or NonePhase angle range as [phase_min, phase_max] in radians (default [-pi, pi])
figmatplotlib.figure.Figure or NoneExisting figure object to plot on (default None)
axis_valsmatplotlib.axes.Axes or NoneExisting 3D axis object to plot on (default None)
thresholdfloat or NoneOnly show bars with absolute value above this threshold (default None)

Returns

tuple -- A tuple of (fig, axis_vals) containing the figure and 3D axes objects.

Description

Renders a 3D bar chart of the density matrix where each bar's height is the absolute value |ρij| and its color encodes the complex phase arg(ρij) using a cyclic colormap. A colorbar maps the phase from π to π. Bars with very small absolute values (below 0.001) are treated as real to avoid random coloring from noise.

Examples

python
import numpy as np
from pyqpanda3.visualization import plot_density_matrix

# Construct a Bell state density matrix
psi = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=complex)
rho = np.outer(psi, np.conj(psi))

# Basic plot
plot_density_matrix(rho, title="Bell State Density Matrix")

# With custom labels and z-axis limits
labels = ["00", "01", "10", "11"]
plot_density_matrix(rho, xlabels=labels, ylabels=labels,
                    title="Bell State", limits=[0, 0.6])

# With phase threshold to filter small elements
plot_density_matrix(rho, title="Threshold Filtered", threshold=0.01)

state_to_density_matrix

Converts a quantum state vector to its density matrix representation. If the input is already a density matrix, it is validated and returned.

Signature

python
state_to_density_matrix(quantum_state)

Parameters

ParameterTypeDescription
quantum_statelist[complex] or numpy.ndarrayQuantum state vector (1D array) or density matrix (2D square array)

Returns

numpy.ndarray -- The density matrix as a 2D complex array.

Description

For a state vector |ψ, computes ρ=|ψψ|. If the input is already a density matrix, validates that it is a square matrix with dimension 2n for some integer n.

Raises RuntimeError if the input is not a valid quantum state (not a 2^n-dimensional state vector or not a valid square density matrix).

Examples

python
import numpy as np
from pyqpanda3.visualization import state_to_density_matrix

# Convert a state vector to density matrix
psi = np.array([1/np.sqrt(2), 0, 0, 1/np.sqrt(2)], dtype=complex)
rho = state_to_density_matrix(psi)
print(rho)
# [[0.5+0.j 0. +0.j 0. +0.j 0.5+0.j]
#  [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
#  [0. +0.j 0. +0.j 0. +0.j 0. +0.j]
#  [0.5+0.j 0. +0.j 0. +0.j 0.5+0.j]]

# Passing a density matrix directly returns it (after validation)
rho2 = state_to_density_matrix(rho)

See Also

Released under the MIT License.