CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-qutip

Comprehensive Python library for simulating quantum systems dynamics and quantum information processing.

Pending
Overview
Eval results
Files

visualization.mddocs/

Visualization and Graphics

Comprehensive visualization tools for quantum states, processes, and dynamics including Bloch sphere, Wigner functions, and matrix representations.

Capabilities

Bloch Sphere Visualization

Three-dimensional visualization of qubit states on the Bloch sphere.

class Bloch:
    """
    Bloch sphere visualization for qubit states and operations.
    """
    def __init__(self, fig=None, axes=None, view=None, figsize=None, background=False):
        """
        Initialize Bloch sphere.
        
        Parameters:
        - fig: Matplotlib figure object
        - axes: Matplotlib 3D axes object
        - view: Viewing angle [azimuth, elevation]
        - figsize: Figure size tuple
        - background: Use dark background
        """
    
    def add_states(self, state, kind='vector'):
        """
        Add quantum states to Bloch sphere.
        
        Parameters:
        - state: Qobj state or list of states
        - kind: 'vector' for pure states, 'point' for density matrices
        """
    
    def add_vectors(self, list_of_vectors):
        """
        Add vectors to Bloch sphere.
        
        Parameters:
        - list_of_vectors: List of [x,y,z] coordinate vectors
        """
    
    def add_points(self, list_of_points, meth='s'):
        """
        Add points to Bloch sphere.
        
        Parameters:
        - list_of_points: List of [x,y,z] coordinates
        - meth: Point style ('s' for scatter, 'l' for line)
        """
    
    def render(self, title=''):
        """
        Render the Bloch sphere.
        
        Parameters:
        - title: Plot title
        """
    
    def show(self):
        """Display the Bloch sphere plot."""
    
    def clear(self):
        """Clear all vectors and points from sphere."""
    
    def save(self, name=None, format='png', dirc=None):
        """
        Save Bloch sphere to file.
        
        Parameters:
        - name: Filename
        - format: File format ('png', 'svg', 'pdf')
        - dirc: Directory path
        """

Matrix Visualization

Various methods for visualizing quantum operators and density matrices.

def hinton(rho: Qobj, xlabels=None, ylabels=None, title=None, ax=None, cmap=None, label_top=True) -> None:
    """
    Create Hinton diagram for visualizing matrix elements.
    
    Parameters:
    - rho: Quantum object to visualize
    - xlabels: Labels for x-axis
    - ylabels: Labels for y-axis  
    - title: Plot title
    - ax: Matplotlib axes object
    - cmap: Colormap
    - label_top: Place labels on top
    """

def matrix_histogram(M: Qobj, xlabels=None, ylabels=None, title=None, limits=None, ax=None) -> None:
    """
    Create 3D histogram of matrix elements.
    
    Parameters:
    - M: Matrix to visualize (Qobj)
    - xlabels: X-axis labels
    - ylabels: Y-axis labels
    - title: Plot title
    - limits: Color scale limits [min, max]
    - ax: Matplotlib axes object
    """

def matrix_histogram_complex(M: Qobj, xlabels=None, ylabels=None, title=None, limits=None, ax=None, threshold=0.01) -> None:
    """
    Create 3D histogram for complex matrix elements.
    
    Parameters:
    - M: Complex matrix to visualize
    - xlabels: X-axis labels
    - ylabels: Y-axis labels
    - title: Plot title
    - limits: Color scale limits
    - ax: Matplotlib axes
    - threshold: Minimum value to display
    """

Phase Space Visualization

Wigner functions and Q-functions for continuous variable systems.

def plot_wigner(rho: Qobj, xvec=None, yvec=None, method='clenshaw', projection='2d', 
                g=np.sqrt(2), sparse=False, parfor=False) -> tuple:
    """
    Plot Wigner function in phase space.
    
    Parameters:
    - rho: Density matrix or state vector
    - xvec: X-coordinate array for phase space
    - yvec: Y-coordinate array for phase space
    - method: 'clenshaw', 'iterative', or 'laguerre'
    - projection: '2d' for contour, '3d' for surface plot
    - g: Scaling factor (default √2)
    - sparse: Use sparse matrices
    - parfor: Use parallel computation
    
    Returns:
    - tuple: (figure, axes) matplotlib objects
    """

def plot_qfunc(rho: Qobj, xvec=None, yvec=None, projection='2d', g=np.sqrt(2)) -> tuple:
    """
    Plot Q-function (Husimi distribution) in phase space.
    
    Parameters:
    - rho: Density matrix or state vector
    - xvec: X-coordinate array
    - yvec: Y-coordinate array
    - projection: '2d' for contour, '3d' for surface
    - g: Scaling factor
    
    Returns:
    - tuple: (figure, axes) matplotlib objects
    """

def plot_wigner_sphere(rho: Qobj, fig=None, ax=None, colorbar=True, 
                       cmap='RdBu', alpha=0.7) -> tuple:
    """
    Plot spin Wigner function on sphere surface.
    
    Parameters:
    - rho: Spin density matrix
    - fig: Matplotlib figure
    - ax: 3D axes object
    - colorbar: Show colorbar
    - cmap: Colormap name
    - alpha: Transparency
    
    Returns:
    - tuple: (figure, axes)
    """

Fock State and Distribution Plots

Visualization of photon number distributions and Fock state properties.

def plot_fock_distribution(rho: Qobj, offset=0, fig=None, ax=None, figsize=(8,6), 
                          title=None, unit_y_range=True) -> tuple:
    """
    Plot Fock state distribution (photon number probabilities).
    
    Parameters:
    - rho: Density matrix
    - offset: Fock state index offset
    - fig: Matplotlib figure
    - ax: Matplotlib axes
    - figsize: Figure size
    - title: Plot title
    - unit_y_range: Normalize y-axis to [0,1]
    
    Returns:
    - tuple: (figure, axes)
    """

def plot_energy_levels(H_list, N=0, labels=None, show_ylabels=False, fig=None, ax=None) -> tuple:
    """
    Plot energy level diagrams for quantum systems.
    
    Parameters:
    - H_list: List of Hamiltonian operators
    - N: Number of energy levels to plot (0 for all)
    - labels: List of system labels
    - show_ylabels: Show y-axis labels
    - fig: Matplotlib figure
    - ax: Matplotlib axes
    
    Returns:
    - tuple: (figure, axes)
    """

Expectation Value and Time Evolution Plots

Visualization of quantum dynamics and expectation values.

def plot_expectation_values(results, e_ops, show_legend=True, fig=None, axes=None, 
                           figsize=(8,6)) -> tuple:
    """
    Plot expectation values from solver results.
    
    Parameters:
    - results: Result object from solver
    - e_ops: List of expectation value operators
    - show_legend: Display legend
    - fig: Matplotlib figure
    - axes: Matplotlib axes
    - figsize: Figure size
    
    Returns:
    - tuple: (figure, axes)
    """

Spin System Visualization

Specialized visualization for spin systems and angular momentum.

def plot_spin_distribution(rho: Qobj, theta=None, phi=None, fig=None, ax=None) -> tuple:
    """
    Plot spin state distribution on sphere.
    
    Parameters:
    - rho: Spin density matrix
    - theta: Polar angle array
    - phi: Azimuthal angle array
    - fig: Matplotlib figure
    - ax: 3D axes object
    
    Returns:
    - tuple: (figure, axes)
    """

def sphereplot(theta, phi, values, fig=None, ax=None, save=False) -> tuple:
    """
    Plot values on sphere surface.
    
    Parameters:
    - theta: Polar angles
    - phi: Azimuthal angles
    - values: Values to plot on sphere
    - fig: Matplotlib figure
    - ax: 3D axes
    - save: Save plot to file
    
    Returns:
    - tuple: (figure, axes)
    """

Complex Array and Quantum State Visualization

Advanced visualization techniques for quantum states and complex data.

def complex_array_to_rgb(X, theme='light', rmax=None, phase_limits=(-np.pi, np.pi)) -> np.ndarray:
    """
    Convert complex array to RGB colors for visualization.
    
    Parameters:
    - X: Complex array
    - theme: 'light' or 'dark' color theme
    - rmax: Maximum radius for scaling
    - phase_limits: Phase range limits
    
    Returns:
    - ndarray: RGB color array
    """

def plot_qubism(ket, legend_iteration=0, fig=None, ax=None, figsize=(8,8), 
                title=True, grid=False, color_style='default') -> tuple:
    """
    Plot qubism representation of multi-qubit state.
    
    Parameters:
    - ket: Multi-qubit state vector
    - legend_iteration: Legend iteration number
    - fig: Matplotlib figure
    - ax: Matplotlib axes
    - figsize: Figure size
    - title: Show title
    - grid: Show grid
    - color_style: Color scheme
    
    Returns:
    - tuple: (figure, axes)
    """

def plot_schmidt(ket, splitting=None, labels_iteration=None, title=True, 
                 fig=None, ax=None, figsize=(8,6)) -> tuple:
    """
    Plot Schmidt decomposition of bipartite quantum state.
    
    Parameters:
    - ket: Bipartite state vector
    - splitting: Subsystem dimension splitting
    - labels_iteration: Label iteration for multi-time analysis
    - title: Show plot title
    - fig: Matplotlib figure
    - ax: Matplotlib axes
    - figsize: Figure size
    
    Returns:
    - tuple: (figure, axes)
    """

Colormap and Utility Functions

Specialized colormaps and utilities for quantum visualization.

def wigner_cmap(W, levels=1024, shift=0, invert=False) -> object:
    """
    Create colormap for Wigner function visualization.
    
    Parameters:
    - W: Wigner function data
    - levels: Number of color levels
    - shift: Phase shift for colors
    - invert: Invert colormap
    
    Returns:
    - object: Matplotlib colormap
    """

Usage Examples

import qutip as qt
import numpy as np
import matplotlib.pyplot as plt

# Qubit state visualization on Bloch sphere
psi = (qt.basis(2,0) + qt.basis(2,1)).unit()  # |+⟩ state
b = qt.Bloch()
b.add_states(psi)
b.render()
b.show()

# Add multiple states and vectors
states = [qt.basis(2,0), qt.basis(2,1), (qt.basis(2,0) + qt.basis(2,1)).unit()]
b = qt.Bloch()
b.add_states(states)
b.add_vectors([[0,0,1], [1,0,0]])  # Add custom vectors
b.show()

# Hinton diagram for density matrix
rho = qt.bell_state().ptrace(0)  # Mixed state from Bell state
qt.hinton(rho, title='Reduced density matrix')
plt.show()

# Matrix histogram visualization
H = qt.rand_herm(4)  # Random Hermitian matrix
qt.matrix_histogram(H, title='Random Hamiltonian')
plt.show()

# Wigner function for coherent state
alpha = 1.5 + 0.8j
rho_coh = qt.coherent_dm(20, alpha)  
qt.plot_wigner(rho_coh, projection='2d')
plt.title('Wigner function of coherent state')
plt.show()

# 3D Wigner function plot
fig, ax = qt.plot_wigner(rho_coh, projection='3d')
plt.show()

# Q-function visualization
qt.plot_qfunc(rho_coh)
plt.title('Q-function of coherent state')
plt.show()

# Fock distribution plot
thermal_state = qt.thermal_dm(15, 2.5)  # Thermal state
qt.plot_fock_distribution(thermal_state, title='Thermal state distribution')
plt.show()

# Energy level diagram
N = 5
H1 = qt.num(N)  # Number operator
H2 = (qt.create(N) + qt.destroy(N))  # Position-like
H3 = -1j * (qt.create(N) - qt.destroy(N))  # Momentum-like
qt.plot_energy_levels([H1, H2, H3], labels=['Number', 'Position', 'Momentum'])
plt.show()

# Time evolution visualization
times = np.linspace(0, 10, 100)
H = qt.sigmaz()
result = qt.sesolve(H, qt.basis(2,0), times, e_ops=[qt.sigmax(), qt.sigmay(), qt.sigmaz()])
qt.plot_expectation_values(result, [qt.sigmax(), qt.sigmay(), qt.sigmaz()])
plt.show()

# Spin Wigner function on sphere
j = 1  # Spin-1 system
rho_spin = qt.spin_coherent(j, np.pi/3, np.pi/4, type='dm')
qt.plot_wigner_sphere(rho_spin)
plt.show()

# Multi-qubit state visualization (qubism)
ghz3 = qt.ghz_state(3)
qt.plot_qubism(ghz3, title=True)
plt.show()

# Schmidt decomposition plot
bell = qt.bell_state('00')
qt.plot_schmidt(bell, splitting=[2,2])
plt.show()

# Animation example (requires additional setup)
states = [qt.spin_coherent(0.5, theta, 0) for theta in np.linspace(0, np.pi, 20)]
# qt.anim_bloch(states) - for animated Bloch sphere

# Complex visualization
psi_complex = qt.rand_ket(10)
data = psi_complex.full().flatten()
rgb_colors = qt.complex_array_to_rgb(data)
plt.imshow(rgb_colors.reshape(10,1,3))
plt.title('Complex quantum state visualization')
plt.show()

Types

class Bloch:
    """
    Bloch sphere visualization class.
    
    Main Attributes:
        vector_color: List of colors for state vectors
        point_color: List of colors for points
        vector_width: Width of state vectors
        point_size: Size of points
        sphere_color: Color of Bloch sphere
        frame_color: Color of sphere frame
        xlabel: X-axis label (default ['$x$'])
        ylabel: Y-axis label (default ['$y$'])  
        zlabel: Z-axis label (default ['$z$'])
    """

# Visualization functions return matplotlib figure and axes objects as tuples
# or None for in-place plotting functions like hinton() and matrix_histogram()

Install with Tessl CLI

npx tessl i tessl/pypi-qutip

docs

index.md

operators.md

phase-space.md

process-tomography.md

quantum-gates.md

quantum-information.md

quantum-objects.md

random-objects.md

solvers.md

states.md

superoperators.md

tensor-operations.md

utilities.md

visualization.md

tile.json