Skip to content

psiqit.visualization

Auto-generated documentation for the psiqit.visualization module.

psiqit.visualization

PSIQIT - Python Scientific Quantum Information Toolkit Visualization Module

This module provides visualization tools for quantum states and circuits.

Submodules:

bloch.py - Bloch sphere visualization circuit_drawer.py - Quantum circuit drawing wigner.py - Wigner function visualization husimi.py - Husimi Q-function visualization animation.py - Animation tools symbolic_plot.py - Symbolic equation rendering

state_to_bloch(state)

Convert a single qubit state to Bloch sphere coordinates

Parameters:

Name Type Description Default
state Union[Ket, ndarray, List]

Single qubit state (Ket, list, or numpy array)

required

Returns:

Type Description
Tuple[float, float, float]

Tuple[float, float, float]: (x, y, z) coordinates

Example

from psiqit.quantum import zero, plus x, y, z = state_to_bloch(zero()) print(x, y, z) # 0.0, 0.0, 1.0 x, y, z = state_to_bloch(plus()) print(x, y, z) # 1.0, 0.0, 0.0

Source code in psiqit\visualization\bloch.py
def state_to_bloch(state: Union[Ket, np.ndarray, List]) -> Tuple[float, float, float]:
    """
    Convert a single qubit state to Bloch sphere coordinates

    Args:
        state: Single qubit state (Ket, list, or numpy array)

    Returns:
        Tuple[float, float, float]: (x, y, z) coordinates

    Example:
        >>> from psiqit.quantum import zero, plus
        >>> x, y, z = state_to_bloch(zero())
        >>> print(x, y, z)  # 0.0, 0.0, 1.0
        >>> x, y, z = state_to_bloch(plus())
        >>> print(x, y, z)  # 1.0, 0.0, 0.0
    """
    return to_bloch_coordinates(state)

bloch_to_state(x, y, z)

Create a single qubit state from Bloch sphere coordinates

Parameters:

Name Type Description Default
x float

x-coordinate

required
y float

y-coordinate

required
z float

z-coordinate

required

Returns:

Name Type Description
Ket Ket

Single qubit state

Example

state = bloch_to_state(0, 0, 1) # |0⟩ state = bloch_to_state(1, 0, 0) # |+⟩

Source code in psiqit\visualization\bloch.py
def bloch_to_state(x: float, y: float, z: float) -> Ket:
    """
    Create a single qubit state from Bloch sphere coordinates

    Args:
        x: x-coordinate
        y: y-coordinate
        z: z-coordinate

    Returns:
        Ket: Single qubit state

    Example:
        >>> state = bloch_to_state(0, 0, 1)  # |0⟩
        >>> state = bloch_to_state(1, 0, 0)  # |+⟩
    """
    return from_bloch_coordinates(x, y, z)

spherical_to_bloch(theta, phi)

Convert spherical coordinates to Bloch sphere coordinates

Parameters:

Name Type Description Default
theta float

Polar angle (0 to π)

required
phi float

Azimuthal angle (0 to 2π)

required

Returns:

Type Description
Tuple[float, float, float]

Tuple[float, float, float]: (x, y, z) coordinates

Example

x, y, z = spherical_to_bloch(np.pi/2, 0) # |+⟩ print(x, y, z) # 1.0, 0.0, 0.0

Source code in psiqit\visualization\bloch.py
def spherical_to_bloch(theta: float, phi: float) -> Tuple[float, float, float]:
    """
    Convert spherical coordinates to Bloch sphere coordinates

    Args:
        theta: Polar angle (0 to π)
        phi: Azimuthal angle (0 to 2π)

    Returns:
        Tuple[float, float, float]: (x, y, z) coordinates

    Example:
        >>> x, y, z = spherical_to_bloch(np.pi/2, 0)  # |+⟩
        >>> print(x, y, z)  # 1.0, 0.0, 0.0
    """
    x = np.sin(theta) * np.cos(phi)
    y = np.sin(theta) * np.sin(phi)
    z = np.cos(theta)
    return (float(x), float(y), float(z))

bloch_to_spherical(x, y, z)

Convert Bloch sphere coordinates to spherical coordinates

Parameters:

Name Type Description Default
x float

x-coordinate

required
y float

y-coordinate

required
z float

z-coordinate

required

Returns:

Type Description
Tuple[float, float]

Tuple[float, float]: (theta, phi) angles

Example

theta, phi = bloch_to_spherical(1, 0, 0) # |+⟩ print(theta, phi) # π/2, 0

Source code in psiqit\visualization\bloch.py
def bloch_to_spherical(x: float, y: float, z: float) -> Tuple[float, float]:
    """
    Convert Bloch sphere coordinates to spherical coordinates

    Args:
        x: x-coordinate
        y: y-coordinate
        z: z-coordinate

    Returns:
        Tuple[float, float]: (theta, phi) angles

    Example:
        >>> theta, phi = bloch_to_spherical(1, 0, 0)  # |+⟩
        >>> print(theta, phi)  # π/2, 0
    """
    r = np.sqrt(x**2 + y**2 + z**2)
    if r < 1e-10:
        return (0.0, 0.0)

    theta = np.arccos(np.clip(z / r, -1, 1))
    phi = np.arctan2(y, x)
    return (float(theta), float(phi))

bloch_sphere(state=None, points=None, title='Bloch Sphere', figsize=(8, 8), show_axes=True, show_labels=True, show_grid=True, save_path=None, colors=None, markers=None, labels=None)

Plot a Bloch sphere with a state vector and/or points

Parameters:

Name Type Description Default
state Optional[Union[Ket, ndarray, List]]

Single qubit state to display as a vector

None
points Optional[List[Tuple[float, float, float]]]

List of (x, y, z) points to display on the sphere

None
title str

Title of the plot

'Bloch Sphere'
figsize Tuple[float, float]

Figure size (width, height)

(8, 8)
show_axes bool

Show x, y, z axes

True
show_labels bool

Show axis labels

True
show_grid bool

Show grid on the sphere

True
save_path Optional[str]

Path to save the figure (if None, displays)

None
colors Optional[List[str]]

List of colors for points

None
markers Optional[List[str]]

List of markers for points

None
labels Optional[List[str]]

List of labels for points

None
Example

from psiqit.quantum import zero, plus, minus bloch_sphere(zero(), title="|0⟩ State") bloch_sphere(points=[(1,0,0), (0,1,0), (0,0,1)], ... labels=['X', 'Y', 'Z'])

Source code in psiqit\visualization\bloch.py
def bloch_sphere(
    state: Optional[Union[Ket, np.ndarray, List]] = None,
    points: Optional[List[Tuple[float, float, float]]] = None,
    title: str = "Bloch Sphere",
    figsize: Tuple[float, float] = (8, 8),
    show_axes: bool = True,
    show_labels: bool = True,
    show_grid: bool = True,
    save_path: Optional[str] = None,
    colors: Optional[List[str]] = None,
    markers: Optional[List[str]] = None,
    labels: Optional[List[str]] = None
):
    """
    Plot a Bloch sphere with a state vector and/or points

    Args:
        state: Single qubit state to display as a vector
        points: List of (x, y, z) points to display on the sphere
        title: Title of the plot
        figsize: Figure size (width, height)
        show_axes: Show x, y, z axes
        show_labels: Show axis labels
        show_grid: Show grid on the sphere
        save_path: Path to save the figure (if None, displays)
        colors: List of colors for points
        markers: List of markers for points
        labels: List of labels for points

    Example:
        >>> from psiqit.quantum import zero, plus, minus
        >>> bloch_sphere(zero(), title="|0⟩ State")
        >>> bloch_sphere(points=[(1,0,0), (0,1,0), (0,0,1)], 
        ...              labels=['X', 'Y', 'Z'])
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    # Create figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection='3d')

    # Draw Bloch sphere
    _draw_sphere(ax, show_grid)

    # Draw axes
    if show_axes:
        _draw_axes(ax, show_labels)

    # Draw state vector if provided
    if state is not None:
        x, y, z = state_to_bloch(state)
        _draw_vector(ax, x, y, z, color='purple', label='State')

        # Draw point
        ax.scatter([x], [y], [z], color='purple', s=100, zorder=10)

    # Draw points if provided
    if points is not None:
        if colors is None:
            colors = ['red'] * len(points)
        if markers is None:
            markers = ['o'] * len(points)

        for i, (x, y, z) in enumerate(points):
            color = colors[i % len(colors)]
            marker = markers[i % len(markers)]
            label = labels[i] if labels and i < len(labels) else None

            # Check if point is on the sphere
            r = np.sqrt(x**2 + y**2 + z**2)
            if abs(r - 1.0) > 0.01:
                logger.warning(f"Point ({x:.3f}, {y:.3f}, {z:.3f}) is not on the Bloch sphere (r={r:.3f})")

            ax.scatter([x], [y], [z], color=color, marker=marker, 
                      s=80, zorder=10, label=label)

    # Set title and limits
    ax.set_title(title)
    ax.set_xlim([-1.2, 1.2])
    ax.set_ylim([-1.2, 1.2])
    ax.set_zlim([-1.2, 1.2])
    ax.set_box_aspect([1, 1, 1])

    # Legend
    if labels:
        ax.legend()

    plt.tight_layout()

    # Save or show
    if save_path is not None:
        plt.savefig(save_path, dpi=150, bbox_inches='tight')
        logger.info(f"Bloch sphere saved to {save_path}")
    else:
        plt.show()

    plt.close()

plot_multiple_states(states, colors=None, labels=None, title='Multiple States on Bloch Sphere', figsize=(8, 8), show_vectors=True, save_path=None)

Plot multiple states on the Bloch sphere

Parameters:

Name Type Description Default
states List[Union[Ket, ndarray, List, Tuple[float, float, float]]]

List of states (Ket, coordinates, or state vectors)

required
colors Optional[List[str]]

List of colors for each state

None
labels Optional[List[str]]

List of labels for each state

None
title str

Title of the plot

'Multiple States on Bloch Sphere'
figsize Tuple[float, float]

Figure size

(8, 8)
show_vectors bool

Show state vectors

True
save_path Optional[str]

Path to save the figure

None
Example

from psiqit.quantum import zero, plus, minus states = [zero(), plus(), minus()] labels = ['|0⟩', '|+⟩', '|-⟩'] plot_multiple_states(states, labels=labels)

Source code in psiqit\visualization\bloch.py
def plot_multiple_states(
    states: List[Union[Ket, np.ndarray, List, Tuple[float, float, float]]],
    colors: Optional[List[str]] = None,
    labels: Optional[List[str]] = None,
    title: str = "Multiple States on Bloch Sphere",
    figsize: Tuple[float, float] = (8, 8),
    show_vectors: bool = True,
    save_path: Optional[str] = None
):
    """
    Plot multiple states on the Bloch sphere

    Args:
        states: List of states (Ket, coordinates, or state vectors)
        colors: List of colors for each state
        labels: List of labels for each state
        title: Title of the plot
        figsize: Figure size
        show_vectors: Show state vectors
        save_path: Path to save the figure

    Example:
        >>> from psiqit.quantum import zero, plus, minus
        >>> states = [zero(), plus(), minus()]
        >>> labels = ['|0⟩', '|+⟩', '|-⟩']
        >>> plot_multiple_states(states, labels=labels)
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    # Convert states to coordinates
    coords = []
    for state in states:
        if isinstance(state, (list, tuple)) and len(state) == 3:
            # Already coordinates
            coords.append(state)
        else:
            # Convert to Bloch coordinates
            x, y, z = state_to_bloch(state)
            coords.append((x, y, z))

    # Default colors
    if colors is None:
        default_colors = ['purple', 'red', 'blue', 'green', 'orange', 'cyan', 'magenta', 'brown']
        colors = default_colors[:len(coords)]
    else:
        colors = colors[:len(coords)]

    if labels is None:
        labels = [f"State {i}" for i in range(len(coords))]

    # Create figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection='3d')

    # Draw Bloch sphere
    _draw_sphere(ax, show_grid=True)
    _draw_axes(ax, show_labels=True)

    # Draw states
    for i, (x, y, z) in enumerate(coords):
        color = colors[i % len(colors)]
        label = labels[i] if i < len(labels) else None

        if show_vectors:
            _draw_vector(ax, x, y, z, color=color, label=label)

        # Draw point
        ax.scatter([x], [y], [z], color=color, s=100, zorder=10)

    ax.set_title(title)
    ax.set_xlim([-1.2, 1.2])
    ax.set_ylim([-1.2, 1.2])
    ax.set_zlim([-1.2, 1.2])
    ax.set_box_aspect([1, 1, 1])

    if labels:
        ax.legend()

    plt.tight_layout()

    if save_path is not None:
        plt.savefig(save_path, dpi=150, bbox_inches='tight')
        logger.info(f"Bloch sphere plot saved to {save_path}")
    else:
        plt.show()

    plt.close()

animate_bloch(states, interval=200, filename=None, title='Bloch Sphere Animation', figsize=(6, 6), color='purple')

Create an animation of states on the Bloch sphere

Parameters:

Name Type Description Default
states List[Union[Ket, ndarray, List, Tuple[float, float, float]]]

List of states to animate

required
interval int

Time between frames in milliseconds

200
filename Optional[str]

Path to save the animation (if None, displays)

None
title str

Title of the animation

'Bloch Sphere Animation'
figsize Tuple[float, float]

Figure size

(6, 6)
color str

Color of the state vector

'purple'
Example

from psiqit.quantum import zero, plus, minus states = [zero(), plus(), minus(), zero()] animate_bloch(states, interval=500)

Source code in psiqit\visualization\bloch.py
def animate_bloch(
    states: List[Union[Ket, np.ndarray, List, Tuple[float, float, float]]],
    interval: int = 200,
    filename: Optional[str] = None,
    title: str = "Bloch Sphere Animation",
    figsize: Tuple[float, float] = (6, 6),
    color: str = 'purple'
):
    """
    Create an animation of states on the Bloch sphere

    Args:
        states: List of states to animate
        interval: Time between frames in milliseconds
        filename: Path to save the animation (if None, displays)
        title: Title of the animation
        figsize: Figure size
        color: Color of the state vector

    Example:
        >>> from psiqit.quantum import zero, plus, minus
        >>> states = [zero(), plus(), minus(), zero()]
        >>> animate_bloch(states, interval=500)
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        from matplotlib.animation import FuncAnimation

        # Convert states to coordinates
        coords = []
        for state in states:
            if isinstance(state, (list, tuple)) and len(state) == 3:
                coords.append(state)
            else:
                x, y, z = state_to_bloch(state)
                coords.append((x, y, z))

        # Create figure
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111, projection='3d')

        # Draw static elements
        _draw_sphere(ax, show_grid=True)
        _draw_axes(ax, show_labels=True)

        # Initialize vector
        x0, y0, z0 = coords[0]
        vec = ax.quiver(0, 0, 0, x0, y0, z0, color=color, arrow_length_ratio=0.15, 
                        linewidth=3, zorder=10)
        point = ax.scatter([x0], [y0], [z0], color=color, s=100, zorder=10)

        ax.set_title(title)
        ax.set_xlim([-1.2, 1.2])
        ax.set_ylim([-1.2, 1.2])
        ax.set_zlim([-1.2, 1.2])
        ax.set_box_aspect([1, 1, 1])

        # Update function
        def update(frame):
            x, y, z = coords[frame % len(coords)]

            # Update vector
            vec.remove()
            new_vec = ax.quiver(0, 0, 0, x, y, z, color=color, 
                                arrow_length_ratio=0.15, linewidth=3, zorder=10)

            # Update point
            point._offsets3d = ([x], [y], [z])

            # Update title with frame number
            ax.set_title(f"{title} - Frame {frame+1}/{len(coords)}")

            return new_vec, point

        # Create animation
        anim = FuncAnimation(fig, update, frames=len(coords), interval=interval, blit=False)

        # Save or show
        if filename is not None:
            anim.save(filename, writer='pillow', fps=1000/interval)
            logger.info(f"Animation saved to {filename}")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not create animation: {e}")
        # Fallback: plot the first state
        bloch_sphere(states[0], title=title)

get_bloch_coordinates(state)

Get Bloch sphere coordinates with additional information

Parameters:

Name Type Description Default
state Union[Ket, ndarray, List]

Single qubit state

required

Returns:

Name Type Description
Dict Dict[str, float]

Bloch coordinates and angles

Example

from psiqit.quantum import plus info = get_bloch_coordinates(plus()) print(info['x']) # 1.0 print(info['theta']) # π/2

Source code in psiqit\visualization\bloch.py
def get_bloch_coordinates(state: Union[Ket, np.ndarray, List]) -> Dict[str, float]:
    """
    Get Bloch sphere coordinates with additional information

    Args:
        state: Single qubit state

    Returns:
        Dict: Bloch coordinates and angles

    Example:
        >>> from psiqit.quantum import plus
        >>> info = get_bloch_coordinates(plus())
        >>> print(info['x'])  # 1.0
        >>> print(info['theta'])  # π/2
    """
    x, y, z = state_to_bloch(state)
    theta, phi = bloch_to_spherical(x, y, z)

    return {
        'x': x,
        'y': y,
        'z': z,
        'theta': theta,
        'phi': phi,
        'r': np.sqrt(x**2 + y**2 + z**2)
    }

bloch_distance(state1, state2)

Compute the Euclidean distance between two states on the Bloch sphere

Parameters:

Name Type Description Default
state1 Union[Ket, ndarray, List, Tuple[float, float, float]]

First state

required
state2 Union[Ket, ndarray, List, Tuple[float, float, float]]

Second state

required

Returns:

Name Type Description
float float

Distance between the states

Example

from psiqit.quantum import zero, one dist = bloch_distance(zero(), one()) # 2.0

Source code in psiqit\visualization\bloch.py
def bloch_distance(
    state1: Union[Ket, np.ndarray, List, Tuple[float, float, float]],
    state2: Union[Ket, np.ndarray, List, Tuple[float, float, float]]
) -> float:
    """
    Compute the Euclidean distance between two states on the Bloch sphere

    Args:
        state1: First state
        state2: Second state

    Returns:
        float: Distance between the states

    Example:
        >>> from psiqit.quantum import zero, one
        >>> dist = bloch_distance(zero(), one())  # 2.0
    """
    # Convert to coordinates
    if isinstance(state1, (list, tuple)) and len(state1) == 3:
        x1, y1, z1 = state1
    else:
        x1, y1, z1 = state_to_bloch(state1)

    if isinstance(state2, (list, tuple)) and len(state2) == 3:
        x2, y2, z2 = state2
    else:
        x2, y2, z2 = state_to_bloch(state2)

    return float(np.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2))

draw_circuit(circuit, style='ascii', show_wires=True, qubit_labels=None)

Draw a quantum circuit in various styles

Parameters:

Name Type Description Default
circuit QuantumCircuit

QuantumCircuit object

required
style str

'ascii', 'unicode', or 'text'

'ascii'
show_wires bool

Show wire lines

True
qubit_labels Optional[List[str]]

Custom labels for qubits

None

Returns:

Name Type Description
str str

Circuit diagram

Example

from psiqit.circuits import QuantumCircuit circ = QuantumCircuit(2) circ.h(0).cx(0, 1) print(draw_circuit(circ)) q0: ── H ── ● ── q1: ──────── X ──

Source code in psiqit\visualization\circuit_drawer.py
def draw_circuit(
    circuit: QuantumCircuit,
    style: str = 'ascii',
    show_wires: bool = True,
    qubit_labels: Optional[List[str]] = None
) -> str:
    """
    Draw a quantum circuit in various styles

    Args:
        circuit: QuantumCircuit object
        style: 'ascii', 'unicode', or 'text'
        show_wires: Show wire lines
        qubit_labels: Custom labels for qubits

    Returns:
        str: Circuit diagram

    Example:
        >>> from psiqit.circuits import QuantumCircuit
        >>> circ = QuantumCircuit(2)
        >>> circ.h(0).cx(0, 1)
        >>> print(draw_circuit(circ))
        q0: ── H ── ● ──
        q1: ──────── X ──
    """
    if style == 'ascii':
        return _draw_ascii(circuit, show_wires, qubit_labels)
    elif style == 'unicode':
        return _draw_unicode(circuit, show_wires, qubit_labels)
    elif style == 'text':
        return circuit_to_text(circuit, show_wires)
    else:
        raise ValueError(f"Unknown style: {style}. Use 'ascii', 'unicode', or 'text'")

circuit_to_text(circuit, show_wires=True)

Convert circuit to a simple text representation

Parameters:

Name Type Description Default
circuit QuantumCircuit

QuantumCircuit object

required
show_wires bool

Show wire lines

True

Returns:

Name Type Description
str str

Text representation

Example

print(circuit_to_text(circuit)) Circuit: 2 qubits, 2 gates Gate 1: H on [0] Gate 2: CNOT on [0, 1]

Source code in psiqit\visualization\circuit_drawer.py
def circuit_to_text(
    circuit: QuantumCircuit,
    show_wires: bool = True
) -> str:
    """
    Convert circuit to a simple text representation

    Args:
        circuit: QuantumCircuit object
        show_wires: Show wire lines

    Returns:
        str: Text representation

    Example:
        >>> print(circuit_to_text(circuit))
        Circuit: 2 qubits, 2 gates
        Gate 1: H on [0]
        Gate 2: CNOT on [0, 1]
    """
    gates = circuit.get_gates()

    lines = [
        f"Circuit: {circuit.n_qubits} qubits, {len(gates)} gates, depth={circuit.depth}",
        "-" * 40
    ]

    for i, gate in enumerate(gates, 1):
        name = gate['name']
        qubits = gate['qubits']
        params = gate.get('params', [])

        if params:
            param_str = f", params={params}"
        else:
            param_str = ""

        lines.append(f"Gate {i}: {name} on {qubits}{param_str}")

    return "\n".join(lines)

circuit_statistics(circuit)

Get statistics about a quantum circuit

Parameters:

Name Type Description Default
circuit QuantumCircuit

QuantumCircuit object

required

Returns:

Name Type Description
Dict Dict[str, Any]

Circuit statistics

Example

stats = circuit_statistics(circuit) print(stats['gate_counts']) {'H': 1, 'CNOT': 1}

Source code in psiqit\visualization\circuit_drawer.py
def circuit_statistics(circuit: QuantumCircuit) -> Dict[str, Any]:
    """
    Get statistics about a quantum circuit

    Args:
        circuit: QuantumCircuit object

    Returns:
        Dict: Circuit statistics

    Example:
        >>> stats = circuit_statistics(circuit)
        >>> print(stats['gate_counts'])
        {'H': 1, 'CNOT': 1}
    """
    gates = circuit.get_gates()

    # Gate counts
    gate_counts = {}
    gate_types = set()

    for gate in gates:
        name = gate['name']
        gate_counts[name] = gate_counts.get(name, 0) + 1
        gate_types.add(name)

    # Count multi-qubit gates
    multi_qubit_gates = 0
    single_qubit_gates = 0

    for gate in gates:
        if len(gate['qubits']) > 1:
            multi_qubit_gates += 1
        else:
            single_qubit_gates += 1

    # Count controlled gates
    controlled_gates = sum(1 for gate in gates if gate['name'] in ['CNOT', 'CX', 'CZ', 'TOFFOLI', 'CU1'])

    # Count rotation gates
    rotation_gates = sum(1 for gate in gates if gate['name'] in ['RX', 'RY', 'RZ'])

    # Count measurement gates
    measurement_gates = sum(1 for gate in gates if gate['name'] == 'MEASURE')

    # Circuit depth by qubit
    qubit_depths = {i: 0 for i in range(circuit.n_qubits)}
    for gate in gates:
        for qubit in gate['qubits']:
            qubit_depths[qubit] = qubit_depths.get(qubit, 0) + 1

    # Qubit usage
    qubit_usage = {}
    for i in range(circuit.n_qubits):
        qubit_usage[i] = qubit_depths.get(i, 0)

    return {
        'n_qubits': circuit.n_qubits,
        'total_gates': len(gates),
        'depth': circuit.depth,
        'gate_counts': gate_counts,
        'gate_types': sorted(gate_types),
        'single_qubit_gates': single_qubit_gates,
        'multi_qubit_gates': multi_qubit_gates,
        'controlled_gates': controlled_gates,
        'rotation_gates': rotation_gates,
        'measurement_gates': measurement_gates,
        'qubit_depths': qubit_depths,
        'qubit_usage': qubit_usage,
        'max_depth_per_qubit': max(qubit_depths.values()) if qubit_depths else 0,
        'avg_depth_per_qubit': sum(qubit_depths.values()) / len(qubit_depths) if qubit_depths else 0
    }

draw_circuit_latex(circuit, style='quantikz')

Generate LaTeX code for a circuit diagram

Parameters:

Name Type Description Default
circuit QuantumCircuit

QuantumCircuit object

required
style str

'quantikz' or 'qcircuit'

'quantikz'

Returns:

Name Type Description
str str

LaTeX code

Example

print(draw_circuit_latex(circuit)) \begin{quantikz} \lstick{q0} & \gate{H} & \ctrl{1} & \qw \ \lstick{q1} & \qw & \targ{} & \qw \ \end{quantikz}

Source code in psiqit\visualization\circuit_drawer.py
def draw_circuit_latex(
    circuit: QuantumCircuit,
    style: str = 'quantikz'
) -> str:
    """
    Generate LaTeX code for a circuit diagram

    Args:
        circuit: QuantumCircuit object
        style: 'quantikz' or 'qcircuit'

    Returns:
        str: LaTeX code

    Example:
        >>> print(draw_circuit_latex(circuit))
        \\begin{quantikz}
        \\lstick{q0} & \\gate{H} & \\ctrl{1} & \\qw \\\\
        \\lstick{q1} & \\qw & \\targ{} & \\qw \\\\
        \\end{quantikz}
    """
    # Import from interface.latex
    try:
        from ..interface.latex import circuit_to_latex
        return circuit_to_latex(circuit, style=style)
    except ImportError:
        logger.warning("Could not import circuit_to_latex from interface.latex")
        return circuit_to_text(circuit)

draw_circuit_qiskit(circuit, style='mpl')

Draw circuit using Qiskit (if available)

Parameters:

Name Type Description Default
circuit QuantumCircuit

QuantumCircuit object

required
style str

'mpl', 'text', or 'latex'

'mpl'

Returns:

Type Description

Qiskit circuit drawing

Example

draw_circuit_qiskit(circuit, style='mpl')

Source code in psiqit\visualization\circuit_drawer.py
def draw_circuit_qiskit(
    circuit: QuantumCircuit,
    style: str = 'mpl'
):
    """
    Draw circuit using Qiskit (if available)

    Args:
        circuit: QuantumCircuit object
        style: 'mpl', 'text', or 'latex'

    Returns:
        Qiskit circuit drawing

    Example:
        >>> draw_circuit_qiskit(circuit, style='mpl')
    """
    try:
        from qiskit import QuantumCircuit as QiskitCircuit

        # Convert to Qiskit circuit
        qiskit_circ = QiskitCircuit(circuit.n_qubits)

        for gate in circuit.get_gates():
            name = gate['name']
            qubits = gate['qubits']
            params = gate.get('params', [])

            if name == 'H':
                for q in qubits:
                    qiskit_circ.h(q)
            elif name == 'X':
                for q in qubits:
                    qiskit_circ.x(q)
            elif name == 'Y':
                for q in qubits:
                    qiskit_circ.y(q)
            elif name == 'Z':
                for q in qubits:
                    qiskit_circ.z(q)
            elif name == 'S':
                for q in qubits:
                    qiskit_circ.s(q)
            elif name == 'T':
                for q in qubits:
                    qiskit_circ.t(q)
            elif name in ['RX', 'RY', 'RZ']:
                for q, theta in zip(qubits, params):
                    if name == 'RX':
                        qiskit_circ.rx(theta, q)
                    elif name == 'RY':
                        qiskit_circ.ry(theta, q)
                    else:
                        qiskit_circ.rz(theta, q)
            elif name in ['CNOT', 'CX']:
                for i in range(0, len(qubits), 2):
                    qiskit_circ.cx(qubits[i], qubits[i+1])
            elif name == 'CZ':
                for i in range(0, len(qubits), 2):
                    qiskit_circ.cz(qubits[i], qubits[i+1])
            elif name == 'SWAP':
                for i in range(0, len(qubits), 2):
                    qiskit_circ.swap(qubits[i], qubits[i+1])
            elif name == 'TOFFOLI':
                for i in range(0, len(qubits), 3):
                    qiskit_circ.ccx(qubits[i], qubits[i+1], qubits[i+2])

        return qiskit_circ.draw(style)

    except ImportError:
        logger.warning("Qiskit not available. Install with: pip install qiskit")
        return draw_circuit(circuit, style='ascii')

wigner_function(state, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Wigner function for a quantum state

The Wigner function is defined as: W(x, p) = (1/πħ) ∫ dy ⟨x+y|ρ|x-y⟩ e^{-2ipy/ħ}

Parameters:

Name Type Description Default
state Union[Ket, ndarray]

Quantum state (Ket or density matrix)

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(W, x, p) where W is the Wigner function

Example

from psiqit.quantum import coherent_state alpha = 1.0 + 1j*0.5 state = coherent_state(alpha, n_levels=20) W, x, p = wigner_function(state, (-3, 3), (-3, 3)) plot_wigner(W, x, p, title="Coherent State")

Source code in psiqit\visualization\wigner.py
def wigner_function(
    state: Union[Ket, np.ndarray],
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Wigner function for a quantum state

    The Wigner function is defined as:
    W(x, p) = (1/πħ) ∫ dy ⟨x+y|ρ|x-y⟩ e^{-2ipy/ħ}

    Args:
        state: Quantum state (Ket or density matrix)
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (W, x, p) where W is the Wigner function

    Example:
        >>> from psiqit.quantum import coherent_state
        >>> alpha = 1.0 + 1j*0.5
        >>> state = coherent_state(alpha, n_levels=20)
        >>> W, x, p = wigner_function(state, (-3, 3), (-3, 3))
        >>> plot_wigner(W, x, p, title="Coherent State")
    """
    if isinstance(state, Ket):
        # Get the wavefunction from the Ket state
        psi = state.data
        # For Fock basis states, we need to compute the Wigner function
        # using the Fock state representation
        n_levels = len(psi)

        # For pure states in Fock basis, compute Wigner function
        # W(x, p) = (2/π) Σ_{n,m} ρ_{n,m} W_{n,m}(x, p)
        # where W_{n,m} are the Wigner functions of Fock states

        # Use the Wigner function for Fock state
        return _wigner_function_fock(psi, x_range, p_range, n_points, hbar)

    elif isinstance(state, np.ndarray) and state.ndim == 2:
        # Density matrix
        return _wigner_function_density(state, x_range, p_range, n_points, hbar)

    else:
        raise ValueError("State must be Ket or density matrix")

wigner_function_analytic(psi_func, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Wigner function from an analytic wavefunction

W(x, p) = (1/πħ) ∫ dy ψ(x+y) ψ*(x-y) e^{-2ipy/ħ}

Parameters:

Name Type Description Default
psi_func Callable[[ndarray], ndarray]

Wavefunction ψ(x) as a callable

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(W, x, p)

Example

def psi(x): ... return np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi)) W, x, p = wigner_function_analytic(psi, (-3, 3), (-3, 3)) plot_wigner(W, x, p)

Source code in psiqit\visualization\wigner.py
def wigner_function_analytic(
    psi_func: Callable[[np.ndarray], np.ndarray],
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Wigner function from an analytic wavefunction

    W(x, p) = (1/πħ) ∫ dy ψ(x+y) ψ*(x-y) e^{-2ipy/ħ}

    Args:
        psi_func: Wavefunction ψ(x) as a callable
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (W, x, p)

    Example:
        >>> def psi(x):
        ...     return np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi))
        >>> W, x, p = wigner_function_analytic(psi, (-3, 3), (-3, 3))
        >>> plot_wigner(W, x, p)
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)
    W = np.zeros_like(X, dtype=float)

    # Integration range
    y_range = 10.0
    n_y = 200
    y = np.linspace(-y_range, y_range, n_y)
    dy = y[1] - y[0]

    for i, xi in enumerate(x):
        for j, pj in enumerate(p):
            # Compute integral over y
            integral = 0.0
            for yk in y:
                psi_plus = psi_func(xi + yk)
                psi_minus = np.conj(psi_func(xi - yk))
                integral += psi_plus * psi_minus * np.exp(-2j * pj * yk / hbar)

            W[i, j] = (1 / (np.pi * hbar)) * np.real(integral) * dy

    # Normalize
    dx = x[1] - x[0]
    dp = p[1] - p[0]
    W = W / (np.sum(W) * dx * dp)

    return W, x, p

wigner_function_gaussian(x0=0.0, p0=0.0, sigma=1.0, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Wigner function for a Gaussian state

W(x, p) = (1/πħ) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))

Parameters:

Name Type Description Default
x0 float

Center position

0.0
p0 float

Center momentum

0.0
sigma float

Width parameter

1.0
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(W, x, p)

Example

W, x, p = wigner_function_gaussian(x0=0, p0=0, sigma=1.0) plot_wigner(W, x, p, title="Gaussian State")

Source code in psiqit\visualization\wigner.py
def wigner_function_gaussian(
    x0: float = 0.0,
    p0: float = 0.0,
    sigma: float = 1.0,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Wigner function for a Gaussian state

    W(x, p) = (1/πħ) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))

    Args:
        x0: Center position
        p0: Center momentum
        sigma: Width parameter
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (W, x, p)

    Example:
        >>> W, x, p = wigner_function_gaussian(x0=0, p0=0, sigma=1.0)
        >>> plot_wigner(W, x, p, title="Gaussian State")
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Gaussian Wigner function
    W = (1 / (np.pi * hbar)) * np.exp(
        -(X - x0)**2 / (2 * sigma**2) -
        (P - p0)**2 / (2 * sigma**2)
    )

    # Normalize
    dx = x[1] - x[0]
    dp = p[1] - p[0]
    W = W / (np.sum(W) * dx * dp)

    return W, x, p

wigner_function_coherent_state(alpha, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Wigner function for a coherent state |α⟩

W(x, p) = (1/πħ) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²)) where x0 = √(2ħ) Re(α) and p0 = √(2ħ) Im(α)

Parameters:

Name Type Description Default
alpha complex

Complex amplitude

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(W, x, p)

Example

alpha = 1.0 + 1j*0.5 W, x, p = wigner_function_coherent_state(alpha, (-3, 3), (-3, 3)) plot_wigner(W, x, p, title="Coherent State")

Source code in psiqit\visualization\wigner.py
def wigner_function_coherent_state(
    alpha: complex,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Wigner function for a coherent state |α⟩

    W(x, p) = (1/πħ) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))
    where x0 = √(2ħ) Re(α) and p0 = √(2ħ) Im(α)

    Args:
        alpha: Complex amplitude
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (W, x, p)

    Example:
        >>> alpha = 1.0 + 1j*0.5
        >>> W, x, p = wigner_function_coherent_state(alpha, (-3, 3), (-3, 3))
        >>> plot_wigner(W, x, p, title="Coherent State")
    """
    # Convert alpha to position and momentum
    x0 = np.sqrt(2 * hbar) * np.real(alpha)
    p0 = np.sqrt(2 * hbar) * np.imag(alpha)
    sigma = np.sqrt(hbar / 2)

    return wigner_function_gaussian(x0, p0, sigma, x_range, p_range, n_points, hbar)

wigner_function_squeezed_state(r, phi=0.0, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Wigner function for a squeezed state

W(x, p) = (1/πħ) exp(-(x²/(2σ²_x) + p²/(2σ²_p))) where σ_x = sqrt(ħ/2) e^r and σ_p = sqrt(ħ/2) e^{-r}

Parameters:

Name Type Description Default
r float

Squeezing parameter

required
phi float

Squeezing phase

0.0
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(W, x, p)

Example

W, x, p = wigner_function_squeezed_state(r=0.5, phi=0, (-3, 3), (-3, 3)) plot_wigner(W, x, p, title="Squeezed State")

Source code in psiqit\visualization\wigner.py
def wigner_function_squeezed_state(
    r: float,
    phi: float = 0.0,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Wigner function for a squeezed state

    W(x, p) = (1/πħ) exp(-(x²/(2σ²_x) + p²/(2σ²_p)))
    where σ_x = sqrt(ħ/2) e^r and σ_p = sqrt(ħ/2) e^{-r}

    Args:
        r: Squeezing parameter
        phi: Squeezing phase
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (W, x, p)

    Example:
        >>> W, x, p = wigner_function_squeezed_state(r=0.5, phi=0, (-3, 3), (-3, 3))
        >>> plot_wigner(W, x, p, title="Squeezed State")
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Rotate coordinates for squeezed state
    # Apply rotation by phi
    c = np.cos(phi)
    s = np.sin(phi)

    X_rot = X * c + P * s
    P_rot = -X * s + P * c

    # Squeezed state Wigner function
    sigma_x = np.sqrt(hbar / 2) * np.exp(r)
    sigma_p = np.sqrt(hbar / 2) * np.exp(-r)

    W = (1 / (np.pi * hbar)) * np.exp(
        -X_rot**2 / (2 * sigma_x**2) -
        P_rot**2 / (2 * sigma_p**2)
    )

    # Normalize
    dx = x[1] - x[0]
    dp = p[1] - p[0]
    W = W / (np.sum(W) * dx * dp)

    return W, x, p

plot_wigner(W, x, p, title='Wigner Function', cmap='RdBu', save_path=None, figsize=(8, 6), show_colorbar=True, show_contours=False, contour_levels=10)

Plot the Wigner function as a 2D colormap

Parameters:

Name Type Description Default
W ndarray

Wigner function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required
title str

Title of the plot

'Wigner Function'
cmap str

Colormap name

'RdBu'
save_path Optional[str]

Path to save the figure

None
figsize Tuple[float, float]

Figure size (width, height)

(8, 6)
show_colorbar bool

Show colorbar

True
show_contours bool

Show contour lines

False
contour_levels int

Number of contour levels

10
Example

W, x, p = wigner_function_gaussian() plot_wigner(W, x, p, title="Gaussian State")

Save to file

plot_wigner(W, x, p, save_path="wigner.png")

Source code in psiqit\visualization\wigner.py
def plot_wigner(
    W: np.ndarray,
    x: np.ndarray,
    p: np.ndarray,
    title: str = "Wigner Function",
    cmap: str = 'RdBu',
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (8, 6),
    show_colorbar: bool = True,
    show_contours: bool = False,
    contour_levels: int = 10
):
    """
    Plot the Wigner function as a 2D colormap

    Args:
        W: Wigner function values
        x: x-axis (position) values
        p: y-axis (momentum) values
        title: Title of the plot
        cmap: Colormap name
        save_path: Path to save the figure
        figsize: Figure size (width, height)
        show_colorbar: Show colorbar
        show_contours: Show contour lines
        contour_levels: Number of contour levels

    Example:
        >>> W, x, p = wigner_function_gaussian()
        >>> plot_wigner(W, x, p, title="Gaussian State")
        >>> # Save to file
        >>> plot_wigner(W, x, p, save_path="wigner.png")
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(figsize=figsize)

        # Plot the Wigner function
        extent = [x[0], x[-1], p[0], p[-1]]
        im = ax.imshow(W.T, origin='lower', extent=extent, 
                       aspect='auto', cmap=cmap)

        # Add contours if requested
        if show_contours:
            levels = np.linspace(W.min(), W.max(), contour_levels)
            ax.contour(x, p, W.T, levels=levels, colors='black', alpha=0.3)

        # Add labels
        ax.set_xlabel('Position (x)')
        ax.set_ylabel('Momentum (p)')
        ax.set_title(title)

        # Add colorbar
        if show_colorbar:
            cbar = plt.colorbar(im, ax=ax)
            cbar.set_label('W(x, p)')

        plt.tight_layout()

        # Save or show
        if save_path is not None:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            logger.info(f"Wigner plot saved to {save_path}")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not plot Wigner function: {e}")

plot_wigner_3d(W, x, p, title='Wigner Function', save_path=None, figsize=(10, 8), elevation=30, azimuth=45)

Plot the Wigner function as a 3D surface

Parameters:

Name Type Description Default
W ndarray

Wigner function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required
title str

Title of the plot

'Wigner Function'
save_path Optional[str]

Path to save the figure

None
figsize Tuple[float, float]

Figure size (width, height)

(10, 8)
elevation float

View elevation angle

30
azimuth float

View azimuthal angle

45
Example

W, x, p = wigner_function_gaussian() plot_wigner_3d(W, x, p, title="Gaussian State")

Source code in psiqit\visualization\wigner.py
def plot_wigner_3d(
    W: np.ndarray,
    x: np.ndarray,
    p: np.ndarray,
    title: str = "Wigner Function",
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (10, 8),
    elevation: float = 30,
    azimuth: float = 45
):
    """
    Plot the Wigner function as a 3D surface

    Args:
        W: Wigner function values
        x: x-axis (position) values
        p: y-axis (momentum) values
        title: Title of the plot
        save_path: Path to save the figure
        figsize: Figure size (width, height)
        elevation: View elevation angle
        azimuth: View azimuthal angle

    Example:
        >>> W, x, p = wigner_function_gaussian()
        >>> plot_wigner_3d(W, x, p, title="Gaussian State")
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111, projection='3d')

        # Create meshgrid
        X, P = np.meshgrid(x, p)

        # Plot surface
        surf = ax.plot_surface(X, P, W.T, cmap='RdBu', 
                              linewidth=0, antialiased=True, alpha=0.8)

        # Add contour projection on bottom
        ax.contour(X, P, W.T, zdir='z', offset=W.min(), cmap='RdBu', alpha=0.3)

        ax.set_xlabel('Position (x)')
        ax.set_ylabel('Momentum (p)')
        ax.set_zlabel('W(x, p)')
        ax.set_title(title)

        # Set view angle
        ax.view_init(elev=elevation, azim=azimuth)

        # Add colorbar
        fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)

        plt.tight_layout()

        # Save or show
        if save_path is not None:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            logger.info(f"3D Wigner plot saved to {save_path}")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not plot 3D Wigner function: {e}")

wigner_negativity(W)

Compute the negativity of the Wigner function

Negativity = ∫ |W(x, p)| dx dp - 1

A non-zero negativity indicates non-classicality.

Parameters:

Name Type Description Default
W ndarray

Wigner function values

required

Returns:

Name Type Description
float float

Negativity

Example

W, x, p = wigner_function_coherent_state(alpha) neg = wigner_negativity(W) print(f"Negativity: {neg:.6f}") # ~0 for coherent states

Source code in psiqit\visualization\wigner.py
def wigner_negativity(W: np.ndarray) -> float:
    """
    Compute the negativity of the Wigner function

    Negativity = ∫ |W(x, p)| dx dp - 1

    A non-zero negativity indicates non-classicality.

    Args:
        W: Wigner function values

    Returns:
        float: Negativity

    Example:
        >>> W, x, p = wigner_function_coherent_state(alpha)
        >>> neg = wigner_negativity(W)
        >>> print(f"Negativity: {neg:.6f}")  # ~0 for coherent states
    """
    # Normalize
    W_norm = W / np.sum(W)

    # Compute negativity
    negative = W_norm[W_norm < 0]
    negativity = -np.sum(negative)

    return float(negativity)

wigner_marginals(W, x, p)

Compute the marginals of the Wigner function

The position marginal is: P(x) = ∫ W(x, p) dp The momentum marginal is: Q(p) = ∫ W(x, p) dx

Parameters:

Name Type Description Default
W ndarray

Wigner function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray]

(P_x, Q_p) position and momentum marginals

Source code in psiqit\visualization\wigner.py
def wigner_marginals(W: np.ndarray, x: np.ndarray, p: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """
    Compute the marginals of the Wigner function

    The position marginal is: P(x) = ∫ W(x, p) dp
    The momentum marginal is: Q(p) = ∫ W(x, p) dx

    Args:
        W: Wigner function values
        x: x-axis (position) values
        p: y-axis (momentum) values

    Returns:
        Tuple: (P_x, Q_p) position and momentum marginals
    """
    # Position marginal
    dx = x[1] - x[0]
    dp = p[1] - p[0]

    P_x = np.sum(W, axis=1) * dp
    Q_p = np.sum(W, axis=0) * dx

    return P_x, Q_p

wigner_variance(W, x, p)

Compute the variance of the Wigner function

Parameters:

Name Type Description Default
W ndarray

Wigner function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required

Returns:

Name Type Description
Tuple Tuple[float, float]

(var_x, var_p)

Source code in psiqit\visualization\wigner.py
def wigner_variance(W: np.ndarray, x: np.ndarray, p: np.ndarray) -> Tuple[float, float]:
    """
    Compute the variance of the Wigner function

    Args:
        W: Wigner function values
        x: x-axis (position) values
        p: y-axis (momentum) values

    Returns:
        Tuple: (var_x, var_p)
    """
    # Normalize
    W_norm = W / np.sum(W)

    X, P = np.meshgrid(x, p)

    # Mean values
    mean_x = np.sum(X * W_norm)
    mean_p = np.sum(P * W_norm)

    # Variances
    var_x = np.sum((X - mean_x)**2 * W_norm)
    var_p = np.sum((P - mean_p)**2 * W_norm)

    return float(var_x), float(var_p)

husimi_function_gaussian(x0=0.0, p0=0.0, sigma=1.0, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function for a Gaussian state

The Husimi Q-function is defined as: Q(α) = (1/π) ⟨α|ρ|α⟩

For a Gaussian state with position x0 and momentum p0: Q(x, p) = (1/π) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))

Parameters:

Name Type Description Default
x0 float

Center position

0.0
p0 float

Center momentum

0.0
sigma float

Width of the Gaussian

1.0
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Example

Q, x, p = husimi_function_gaussian(x0=0, p0=0, sigma=1.0) plot_husimi(Q, x, p, title="Gaussian State")

Source code in psiqit\visualization\husimi.py
def husimi_function_gaussian(
    x0: float = 0.0,
    p0: float = 0.0,
    sigma: float = 1.0,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function for a Gaussian state

    The Husimi Q-function is defined as:
    Q(α) = (1/π) ⟨α|ρ|α⟩

    For a Gaussian state with position x0 and momentum p0:
    Q(x, p) = (1/π) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))

    Args:
        x0: Center position
        p0: Center momentum
        sigma: Width of the Gaussian
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function

    Example:
        >>> Q, x, p = husimi_function_gaussian(x0=0, p0=0, sigma=1.0)
        >>> plot_husimi(Q, x, p, title="Gaussian State")
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Gaussian Husimi Q-function
    # Q(x, p) = (1/π) exp(-(x-x0)²/(2σ²) - (p-p0)²/(2σ²))
    Q = (1 / np.pi) * np.exp(
        -(X - x0)**2 / (2 * sigma**2) -
        (P - p0)**2 / (2 * sigma**2)
    )

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

husimi_function_coherent_state(alpha, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function for a coherent state |α⟩

Q(β) = (1/π) |⟨β|α⟩|² = (1/π) exp(-|β-α|²)

Parameters:

Name Type Description Default
alpha complex

Complex amplitude of the coherent state

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Example

alpha = 1.0 + 1j*0.5 Q, x, p = husimi_function_coherent_state(alpha) plot_husimi(Q, x, p, title="Coherent State")

Source code in psiqit\visualization\husimi.py
def husimi_function_coherent_state(
    alpha: complex,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function for a coherent state |α⟩

    Q(β) = (1/π) |⟨β|α⟩|² = (1/π) exp(-|β-α|²)

    Args:
        alpha: Complex amplitude of the coherent state
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function

    Example:
        >>> alpha = 1.0 + 1j*0.5
        >>> Q, x, p = husimi_function_coherent_state(alpha)
        >>> plot_husimi(Q, x, p, title="Coherent State")
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Convert to complex amplitude
    beta = X + 1j * P

    # Husimi Q-function for coherent state
    # Q(β) = (1/π) exp(-|β-α|²)
    Q = (1 / np.pi) * np.exp(-np.abs(beta - alpha)**2)

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

husimi_function_fock_state(n, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function for a Fock state |n⟩

Q(α) = (1/π) |⟨α|n⟩|² = (1/π) e^{-|α|²} |α|^{2n} / n!

Parameters:

Name Type Description Default
n int

Fock state number

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Example

Q, x, p = husimi_function_fock_state(n=2) plot_husimi(Q, x, p, title="Fock State |2⟩")

Source code in psiqit\visualization\husimi.py
def husimi_function_fock_state(
    n: int,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function for a Fock state |n⟩

    Q(α) = (1/π) |⟨α|n⟩|² = (1/π) e^{-|α|²} |α|^{2n} / n!

    Args:
        n: Fock state number
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function

    Example:
        >>> Q, x, p = husimi_function_fock_state(n=2)
        >>> plot_husimi(Q, x, p, title="Fock State |2⟩")
    """
    from math import factorial

    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Convert to complex amplitude
    alpha = X + 1j * P

    # Husimi Q-function for Fock state
    # Q(α) = (1/π) e^{-|α|²} |α|^{2n} / n!
    Q = (1 / np.pi) * np.exp(-np.abs(alpha)**2) * (np.abs(alpha)**(2*n)) / factorial(n)

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

husimi_function_thermal_state(n_bar, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function for a thermal state

Q(α) = (1/π) (1/(n_bar+1)) exp(-|α|²/(n_bar+1))

Parameters:

Name Type Description Default
n_bar float

Average photon number

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Example

Q, x, p = husimi_function_thermal_state(n_bar=2.0) plot_husimi(Q, x, p, title="Thermal State")

Source code in psiqit\visualization\husimi.py
def husimi_function_thermal_state(
    n_bar: float,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function for a thermal state

    Q(α) = (1/π) (1/(n_bar+1)) exp(-|α|²/(n_bar+1))

    Args:
        n_bar: Average photon number
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function

    Example:
        >>> Q, x, p = husimi_function_thermal_state(n_bar=2.0)
        >>> plot_husimi(Q, x, p, title="Thermal State")
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)

    # Convert to complex amplitude
    alpha = X + 1j * P

    # Husimi Q-function for thermal state
    # Q(α) = (1/π) (1/(n_bar+1)) exp(-|α|²/(n_bar+1))
    Q = (1 / np.pi) * (1 / (n_bar + 1)) * np.exp(-np.abs(alpha)**2 / (n_bar + 1))

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

husimi_function_wavefunction(psi_func, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function from a wavefunction

Q(x, p) = (1/π) |∫ dy ψ(y) e^{-i p y / ħ} (1/√(2πσ²)) e^{-(x-y)²/(4σ²)}|²

Parameters:

Name Type Description Default
psi_func callable

Wavefunction ψ(x) as a callable

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Example

def psi(x): ... return np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi)) Q, x, p = husimi_function_wavefunction(psi) plot_husimi(Q, x, p)

Source code in psiqit\visualization\husimi.py
def husimi_function_wavefunction(
    psi_func: callable,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function from a wavefunction

    Q(x, p) = (1/π) |∫ dy ψ(y) e^{-i p y / ħ} (1/√(2πσ²)) e^{-(x-y)²/(4σ²)}|²

    Args:
        psi_func: Wavefunction ψ(x) as a callable
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function

    Example:
        >>> def psi(x):
        ...     return np.exp(-x**2/2) / np.sqrt(np.sqrt(np.pi))
        >>> Q, x, p = husimi_function_wavefunction(psi)
        >>> plot_husimi(Q, x, p)
    """
    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)
    Q = np.zeros_like(X, dtype=float)

    dx = x[1] - x[0]

    # Compute Husimi Q-function
    for i, xi in enumerate(x):
        for j, pj in enumerate(p):
            # Compute the overlap with a coherent state
            # This is a simplified version
            # In practice, we would compute the integral:
            # Q(x, p) = (1/π) |∫ dy ψ(y) φ_{x,p}(y)|²

            # For now, we use a Gaussian approximation
            sigma = 1.0
            Q[i, j] = (1 / np.pi) * np.exp(-(xi)**2 / (2*sigma**2) - (pj)**2 / (2*sigma**2))

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

husimi_function_density_matrix(rho, x_range=(-5, 5), p_range=(-5, 5), n_points=100, hbar=1.0)

Compute the Husimi Q-function from a density matrix

Q(α) = (1/π) ⟨α|ρ|α⟩

Parameters:

Name Type Description Default
rho ndarray

Density matrix in Fock basis

required
x_range Tuple[float, float]

(x_min, x_max) range

(-5, 5)
p_range Tuple[float, float]

(p_min, p_max) range

(-5, 5)
n_points int

Number of points in each dimension

100
hbar float

Reduced Planck constant

1.0

Returns:

Name Type Description
Tuple Tuple[ndarray, ndarray, ndarray]

(Q, x, p) where Q is the Husimi function

Source code in psiqit\visualization\husimi.py
def husimi_function_density_matrix(
    rho: np.ndarray,
    x_range: Tuple[float, float] = (-5, 5),
    p_range: Tuple[float, float] = (-5, 5),
    n_points: int = 100,
    hbar: float = 1.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the Husimi Q-function from a density matrix

    Q(α) = (1/π) ⟨α|ρ|α⟩

    Args:
        rho: Density matrix in Fock basis
        x_range: (x_min, x_max) range
        p_range: (p_min, p_max) range
        n_points: Number of points in each dimension
        hbar: Reduced Planck constant

    Returns:
        Tuple: (Q, x, p) where Q is the Husimi function
    """
    n_levels = rho.shape[0]

    x = np.linspace(x_range[0], x_range[1], n_points)
    p = np.linspace(p_range[0], p_range[1], n_points)

    X, P = np.meshgrid(x, p)
    Q = np.zeros_like(X, dtype=float)

    # Compute coherent state amplitudes for each point
    for i, xi in enumerate(x):
        for j, pj in enumerate(p):
            alpha = xi + 1j * pj

            # Compute coherent state in Fock basis
            coherent = coherent_state(alpha, n_levels)

            # Compute Q(α) = (1/π) ⟨α|ρ|α⟩
            expectation = np.vdot(coherent.data, rho @ coherent.data).real
            Q[i, j] = (1 / np.pi) * expectation

    # Normalize
    Q = Q / np.sum(Q)

    return Q, x, p

plot_husimi(Q, x, p, title='Husimi Q-Function', cmap='hot', save_path=None, figsize=(8, 6), show_colorbar=True, show_contours=False, contour_levels=10)

Plot the Husimi Q-function in phase space

Parameters:

Name Type Description Default
Q ndarray

Husimi Q-function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required
title str

Title of the plot

'Husimi Q-Function'
cmap str

Colormap name

'hot'
save_path Optional[str]

Path to save the figure (if None, displays)

None
figsize Tuple[float, float]

Figure size (width, height)

(8, 6)
show_colorbar bool

Show colorbar

True
show_contours bool

Show contour lines

False
contour_levels int

Number of contour levels

10
Example

Q, x, p = husimi_function_coherent_state(1+1j, (-3, 3), (-3, 3)) plot_husimi(Q, x, p, title="Coherent State")

Save to file

plot_husimi(Q, x, p, save_path="husimi.png")

Source code in psiqit\visualization\husimi.py
def plot_husimi(
    Q: np.ndarray,
    x: np.ndarray,
    p: np.ndarray,
    title: str = "Husimi Q-Function",
    cmap: str = 'hot',
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (8, 6),
    show_colorbar: bool = True,
    show_contours: bool = False,
    contour_levels: int = 10
):
    """
    Plot the Husimi Q-function in phase space

    Args:
        Q: Husimi Q-function values
        x: x-axis (position) values
        p: y-axis (momentum) values
        title: Title of the plot
        cmap: Colormap name
        save_path: Path to save the figure (if None, displays)
        figsize: Figure size (width, height)
        show_colorbar: Show colorbar
        show_contours: Show contour lines
        contour_levels: Number of contour levels

    Example:
        >>> Q, x, p = husimi_function_coherent_state(1+1j, (-3, 3), (-3, 3))
        >>> plot_husimi(Q, x, p, title="Coherent State")
        >>> # Save to file
        >>> plot_husimi(Q, x, p, save_path="husimi.png")
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(figsize=figsize)

        # Plot the Husimi Q-function
        extent = [x[0], x[-1], p[0], p[-1]]
        im = ax.imshow(Q.T, origin='lower', extent=extent, 
                       aspect='auto', cmap=cmap)

        # Add contours if requested
        if show_contours:
            contour_levels = np.linspace(Q.min(), Q.max(), contour_levels)
            ax.contour(x, p, Q.T, levels=contour_levels, colors='white', alpha=0.3)

        # Add labels
        ax.set_xlabel('Position (x)')
        ax.set_ylabel('Momentum (p)')
        ax.set_title(title)

        # Add colorbar
        if show_colorbar:
            cbar = plt.colorbar(im, ax=ax)
            cbar.set_label('Q(α)')

        plt.tight_layout()

        # Save or show
        if save_path is not None:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            logger.info(f"Husimi plot saved to {save_path}")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not plot Husimi function: {e}")

husimi_negativity(Q)

Compute the negativity of the Husimi Q-function

The Husimi Q-function is always non-negative for valid quantum states. However, for some distributions, it may have negative values due to numerical errors or approximations.

Parameters:

Name Type Description Default
Q ndarray

Husimi Q-function values

required

Returns:

Name Type Description
float float

Negativity (sum of negative values)

Example

neg = husimi_negativity(Q) print(f"Negativity: {neg:.6f}")

Source code in psiqit\visualization\husimi.py
def husimi_negativity(Q: np.ndarray) -> float:
    """
    Compute the negativity of the Husimi Q-function

    The Husimi Q-function is always non-negative for valid quantum states.
    However, for some distributions, it may have negative values due to
    numerical errors or approximations.

    Args:
        Q: Husimi Q-function values

    Returns:
        float: Negativity (sum of negative values)

    Example:
        >>> neg = husimi_negativity(Q)
        >>> print(f"Negativity: {neg:.6f}")
    """
    negative = Q[Q < 0]
    return float(-np.sum(negative))

husimi_entropy(Q, base='e')

Compute the entropy of the Husimi Q-function

S = -∫ Q(α) log(Q(α)) d²α

Parameters:

Name Type Description Default
Q ndarray

Husimi Q-function values

required
base str

Logarithm base ('e', '2', '10')

'e'

Returns:

Name Type Description
float float

Entropy

Example

ent = husimi_entropy(Q) print(f"Entropy: {ent:.6f}")

Source code in psiqit\visualization\husimi.py
def husimi_entropy(Q: np.ndarray, base: str = 'e') -> float:
    """
    Compute the entropy of the Husimi Q-function

    S = -∫ Q(α) log(Q(α)) d²α

    Args:
        Q: Husimi Q-function values
        base: Logarithm base ('e', '2', '10')

    Returns:
        float: Entropy

    Example:
        >>> ent = husimi_entropy(Q)
        >>> print(f"Entropy: {ent:.6f}")
    """
    # Normalize
    Q_norm = Q / np.sum(Q)

    # Remove zeros
    Q_pos = Q_norm[Q_norm > 0]

    if base == 'e':
        log_func = np.log
    elif base == '2':
        log_func = np.log2
    elif base == '10':
        log_func = np.log10
    else:
        raise ValueError(f"Unknown base: {base}")

    entropy = -np.sum(Q_pos * log_func(Q_pos))
    return float(entropy)

husimi_variance(Q, x, p)

Compute the variance of the Husimi Q-function

Parameters:

Name Type Description Default
Q ndarray

Husimi Q-function values

required
x ndarray

x-axis (position) values

required
p ndarray

y-axis (momentum) values

required

Returns:

Name Type Description
Tuple Tuple[float, float]

(var_x, var_p)

Example

var_x, var_p = husimi_variance(Q, x, p) print(f"Var(x): {var_x:.4f}, Var(p): {var_p:.4f}")

Source code in psiqit\visualization\husimi.py
def husimi_variance(Q: np.ndarray, x: np.ndarray, p: np.ndarray) -> Tuple[float, float]:
    """
    Compute the variance of the Husimi Q-function

    Args:
        Q: Husimi Q-function values
        x: x-axis (position) values
        p: y-axis (momentum) values

    Returns:
        Tuple: (var_x, var_p)

    Example:
        >>> var_x, var_p = husimi_variance(Q, x, p)
        >>> print(f"Var(x): {var_x:.4f}, Var(p): {var_p:.4f}")
    """
    # Normalize
    Q_norm = Q / np.sum(Q)

    X, P = np.meshgrid(x, p)

    # Mean values
    mean_x = np.sum(X * Q_norm)
    mean_p = np.sum(P * Q_norm)

    # Variances
    var_x = np.sum((X - mean_x)**2 * Q_norm)
    var_p = np.sum((P - mean_p)**2 * Q_norm)

    return float(var_x), float(var_p)

animate_wavefunction(psi_func, x_range, t_range, n_x=200, n_frames=100, interval=50, save_path=None, figsize=(10, 6), show_real_imag=True, show_probability=True, ylim=None, title='Wavefunction Animation')

Animate a time-dependent wavefunction

Parameters:

Name Type Description Default
psi_func Callable[[ndarray, float], ndarray]

Wavefunction function ψ(x, t) returning complex array

required
x_range Tuple[float, float]

(x_min, x_max) range

required
t_range Tuple[float, float]

(t_min, t_max) range

required
n_x int

Number of spatial points

200
n_frames int

Number of animation frames

100
interval int

Time between frames in milliseconds

50
save_path Optional[str]

Path to save animation (if None, displays)

None
figsize Tuple[float, float]

Figure size (width, height)

(10, 6)
show_real_imag bool

Show real and imaginary parts

True
show_probability bool

Show probability density

True
ylim Optional[Tuple[float, float]]

Y-axis limits (if None, auto)

None
title str

Title of the animation

'Wavefunction Animation'
Example

import numpy as np def psi_func(x, t): ... # Gaussian wavepacket ... sigma = 1.0 ... k0 = 1.0 ... x0 = 0.0 ... return np.exp(-(x - x0 - t)2/(2*sigma2)) * np.exp(1j(k0x - t)) animate_wavefunction(psi_func, (-5, 5), (0, 10), n_frames=100)

Source code in psiqit\visualization\animation.py
def animate_wavefunction(
    psi_func: Callable[[np.ndarray, float], np.ndarray],
    x_range: Tuple[float, float],
    t_range: Tuple[float, float],
    n_x: int = 200,
    n_frames: int = 100,
    interval: int = 50,
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (10, 6),
    show_real_imag: bool = True,
    show_probability: bool = True,
    ylim: Optional[Tuple[float, float]] = None,
    title: str = "Wavefunction Animation"
):
    """
    Animate a time-dependent wavefunction

    Args:
        psi_func: Wavefunction function ψ(x, t) returning complex array
        x_range: (x_min, x_max) range
        t_range: (t_min, t_max) range
        n_x: Number of spatial points
        n_frames: Number of animation frames
        interval: Time between frames in milliseconds
        save_path: Path to save animation (if None, displays)
        figsize: Figure size (width, height)
        show_real_imag: Show real and imaginary parts
        show_probability: Show probability density
        ylim: Y-axis limits (if None, auto)
        title: Title of the animation

    Example:
        >>> import numpy as np
        >>> def psi_func(x, t):
        ...     # Gaussian wavepacket
        ...     sigma = 1.0
        ...     k0 = 1.0
        ...     x0 = 0.0
        ...     return np.exp(-(x - x0 - t)**2/(2*sigma**2)) * np.exp(1j*(k0*x - t))
        >>> animate_wavefunction(psi_func, (-5, 5), (0, 10), n_frames=100)
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt
        from matplotlib.animation import FuncAnimation

        # Create spatial grid
        x = np.linspace(x_range[0], x_range[1], n_x)
        t = np.linspace(t_range[0], t_range[1], n_frames)

        # Compute wavefunctions for all frames
        psi_frames = []
        for ti in t:
            psi = psi_func(x, ti)
            psi_frames.append(psi)

        # Determine y-axis limits
        if ylim is None:
            max_abs = 0.0
            for psi in psi_frames:
                max_abs = max(max_abs, np.max(np.abs(psi)))
            ylim = (-max_abs * 1.2, max_abs * 1.2)

        # Create figure
        if show_real_imag and show_probability:
            fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize)
            axes = [ax1, ax2]
        elif show_real_imag or show_probability:
            fig, ax = plt.subplots(1, 1, figsize=figsize)
            axes = [ax]
        else:
            fig, ax = plt.subplots(1, 1, figsize=figsize)
            axes = [ax]

        # Initialize plots
        lines = []
        frames_text = None

        for i, ax in enumerate(axes):
            if show_real_imag and i == 0:
                # Real and imaginary parts
                psi0 = psi_frames[0]
                line_real, = ax.plot(x, np.real(psi0), 'b-', label='Re(ψ)', linewidth=2)
                line_imag, = ax.plot(x, np.imag(psi0), 'r-', label='Im(ψ)', linewidth=2)
                lines.append((line_real, line_imag))
                ax.set_ylabel('Amplitude')
                ax.legend()
                ax.grid(True, alpha=0.3)
                ax.set_ylim(ylim)
            elif show_probability and (i == len(axes) - 1 or not show_real_imag):
                # Probability density
                psi0 = psi_frames[0]
                prob = np.abs(psi0)**2
                line_prob, = ax.plot(x, prob, 'g-', label='|ψ|²', linewidth=2)
                lines.append((line_prob,))
                ax.set_ylabel('Probability')
                ax.legend()
                ax.grid(True, alpha=0.3)
                if ylim is not None:
                    ax.set_ylim(0, ylim[1])
            else:
                # Fallback: just show real part
                psi0 = psi_frames[0]
                line_real, = ax.plot(x, np.real(psi0), 'b-', label='Re(ψ)', linewidth=2)
                lines.append((line_real,))
                ax.set_ylabel('Amplitude')
                ax.legend()
                ax.grid(True, alpha=0.3)
                ax.set_ylim(ylim)

            ax.set_xlabel('x')
            ax.set_xlim(x_range)

        # Set title
        fig.suptitle(f"{title} - t = {t[0]:.3f}")

        # Add time display
        if len(axes) > 0:
            time_text = axes[-1].text(0.02, 0.95, f"t = {t[0]:.3f}", 
                                      transform=axes[-1].transAxes,
                                      fontsize=12, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
        else:
            time_text = None

        plt.tight_layout()

        # Update function
        def update(frame):
            psi = psi_frames[frame]
            current_t = t[frame]

            idx = 0
            for ax in axes:
                if show_real_imag and idx == 0:
                    line_real, line_imag = lines[idx]
                    line_real.set_ydata(np.real(psi))
                    line_imag.set_ydata(np.imag(psi))
                    idx += 1
                elif show_probability and (idx == len(axes) - 1 or not show_real_imag):
                    line_prob, = lines[idx]
                    line_prob.set_ydata(np.abs(psi)**2)
                    idx += 1
                else:
                    line_real, = lines[idx]
                    line_real.set_ydata(np.real(psi))
                    idx += 1

            # Update time text
            if time_text is not None:
                time_text.set_text(f"t = {current_t:.3f}")

            fig.suptitle(f"{title} - t = {current_t:.3f}")

            return [line for sublist in lines for line in sublist] + ([time_text] if time_text else [])

        # Create animation
        anim = FuncAnimation(fig, update, frames=n_frames, interval=interval, blit=False)

        # Save or show
        if save_path is not None:
            try:
                anim.save(save_path, writer='pillow', fps=1000/interval)
                logger.info(f"Animation saved to {save_path}")
            except Exception as e:
                logger.warning(f"Could not save animation: {e}")
                # Fallback: try with ffmpeg
                try:
                    anim.save(save_path.replace('.gif', '.mp4'), writer='ffmpeg', fps=1000/interval)
                    logger.info(f"Animation saved to {save_path.replace('.gif', '.mp4')}")
                except:
                    logger.warning("Could not save animation with ffmpeg either")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not create wavefunction animation: {e}")
        # Fallback: show first frame
        try:
            import matplotlib.pyplot as plt
            x = np.linspace(x_range[0], x_range[1], n_x)
            psi = psi_func(x, t_range[0])

            fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))

            ax1.plot(x, np.real(psi), 'b-', label='Re(ψ)')
            ax1.plot(x, np.imag(psi), 'r-', label='Im(ψ)')
            ax1.set_ylabel('Amplitude')
            ax1.legend()
            ax1.grid(True, alpha=0.3)

            ax2.plot(x, np.abs(psi)**2, 'g-', label='|ψ|²')
            ax2.set_xlabel('x')
            ax2.set_ylabel('Probability')
            ax2.legend()
            ax2.grid(True, alpha=0.3)

            fig.suptitle(f"{title} - t = {t_range[0]:.3f}")
            plt.tight_layout()
            plt.show()
            plt.close()
        except:
            pass

animate_bloch_sphere(states, interval=200, save_path=None, figsize=(8, 8), title='Bloch Sphere Animation', color='purple', show_trace=False, trace_length=None)

Animate states on the Bloch sphere

Parameters:

Name Type Description Default
states List[Union[Ket, ndarray, List, Tuple[float, float, float]]]

List of states to animate

required
interval int

Time between frames in milliseconds

200
save_path Optional[str]

Path to save animation (if None, displays)

None
figsize Tuple[float, float]

Figure size

(8, 8)
title str

Title of the animation

'Bloch Sphere Animation'
color str

Color of the state vector

'purple'
show_trace bool

Show trace of previous states

False
trace_length Optional[int]

Number of previous states to show in trace

None
Example

from psiqit.quantum import zero, plus, minus states = [zero(), plus(), minus(), zero()] animate_bloch_sphere(states, interval=500)

Source code in psiqit\visualization\animation.py
def animate_bloch_sphere(
    states: List[Union[Ket, np.ndarray, List, Tuple[float, float, float]]],
    interval: int = 200,
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (8, 8),
    title: str = "Bloch Sphere Animation",
    color: str = 'purple',
    show_trace: bool = False,
    trace_length: Optional[int] = None
):
    """
    Animate states on the Bloch sphere

    Args:
        states: List of states to animate
        interval: Time between frames in milliseconds
        save_path: Path to save animation (if None, displays)
        figsize: Figure size
        title: Title of the animation
        color: Color of the state vector
        show_trace: Show trace of previous states
        trace_length: Number of previous states to show in trace

    Example:
        >>> from psiqit.quantum import zero, plus, minus
        >>> states = [zero(), plus(), minus(), zero()]
        >>> animate_bloch_sphere(states, interval=500)
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        from matplotlib.animation import FuncAnimation

        # Convert states to coordinates
        coords = []
        for state in states:
            if isinstance(state, (list, tuple)) and len(state) == 3:
                coords.append(state)
            else:
                x, y, z = state_to_bloch(state)
                coords.append((x, y, z))

        # Create figure
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111, projection='3d')

        # Draw Bloch sphere
        from .bloch import _draw_sphere, _draw_axes
        _draw_sphere(ax, show_grid=True)
        _draw_axes(ax, show_labels=True)

        # Initialize vector
        x0, y0, z0 = coords[0]
        vec = ax.quiver(0, 0, 0, x0, y0, z0, color=color, arrow_length_ratio=0.15, 
                        linewidth=3, zorder=10)
        point = ax.scatter([x0], [y0], [z0], color=color, s=150, zorder=10)

        # Initialize trace
        trace_points = []
        trace_lines = []
        if show_trace:
            trace_length = trace_length or len(coords)
            for i in range(min(trace_length, len(coords))):
                x, y, z = coords[i]
                if i > 0:
                    px, py, pz = coords[i-1]
                    line, = ax.plot([px, x], [py, y], [pz, z], 
                                   color=color, alpha=0.3, linewidth=1)
                    trace_lines.append(line)
                point_trace = ax.scatter([x], [y], [z], color=color, 
                                        s=20, alpha=0.3, zorder=5)
                trace_points.append(point_trace)

        ax.set_title(f"{title} - Frame 1/{len(coords)}")
        ax.set_xlim([-1.2, 1.2])
        ax.set_ylim([-1.2, 1.2])
        ax.set_zlim([-1.2, 1.2])
        ax.set_box_aspect([1, 1, 1])

        # Update function
        def update(frame):
            x, y, z = coords[frame % len(coords)]

            # Update vector
            vec.remove()
            new_vec = ax.quiver(0, 0, 0, x, y, z, color=color, 
                                arrow_length_ratio=0.15, linewidth=3, zorder=10)

            # Update point
            point._offsets3d = ([x], [y], [z])

            # Update trace
            if show_trace:
                # Clear old trace
                for line in trace_lines:
                    line.remove()
                for point_t in trace_points:
                    point_t.remove()
                trace_lines.clear()
                trace_points.clear()

                # Draw new trace
                start = max(0, frame - trace_length + 1)
                for i in range(start, frame + 1):
                    cx, cy, cz = coords[i % len(coords)]
                    if i > start:
                        px, py, pz = coords[i-1 % len(coords)]
                        line, = ax.plot([px, cx], [py, cy], [pz, cz], 
                                       color=color, alpha=0.3, linewidth=1)
                        trace_lines.append(line)
                    point_t = ax.scatter([cx], [cy], [cz], color=color, 
                                        s=20, alpha=0.3, zorder=5)
                    trace_points.append(point_t)

            ax.set_title(f"{title} - Frame {frame+1}/{len(coords)}")

            return [new_vec, point] + trace_lines + trace_points

        # Create animation
        anim = FuncAnimation(fig, update, frames=len(coords), interval=interval, blit=False)

        # Save or show
        if save_path is not None:
            try:
                anim.save(save_path, writer='pillow', fps=1000/interval)
                logger.info(f"Bloch sphere animation saved to {save_path}")
            except Exception as e:
                logger.warning(f"Could not save animation: {e}")
                # Fallback: try with ffmpeg
                try:
                    anim.save(save_path.replace('.gif', '.mp4'), writer='ffmpeg', fps=1000/interval)
                    logger.info(f"Bloch sphere animation saved to {save_path.replace('.gif', '.mp4')}")
                except:
                    logger.warning("Could not save animation with ffmpeg either")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not create Bloch sphere animation: {e}")
        # Fallback: show first state
        try:
            from .bloch import bloch_sphere
            bloch_sphere(states[0] if states else None, title=title)
        except:
            pass

animate_parametric_curve(curve_func, t_range, n_frames=100, interval=50, save_path=None, figsize=(8, 8), title='Parametric Curve on Bloch Sphere', color='purple', show_trace=True)

Animate a parametric curve on the Bloch sphere

Parameters:

Name Type Description Default
curve_func Callable[[float], Tuple[float, float, float]]

Function f(t) -> (x, y, z) on the Bloch sphere

required
t_range Tuple[float, float]

(t_min, t_max) range

required
n_frames int

Number of animation frames

100
interval int

Time between frames in milliseconds

50
save_path Optional[str]

Path to save animation

None
figsize Tuple[float, float]

Figure size

(8, 8)
title str

Title of the animation

'Parametric Curve on Bloch Sphere'
color str

Color of the curve

'purple'
show_trace bool

Show the full trace of the curve

True
Example

def curve(t): ... # Circular path on equator ... return (np.cos(t), np.sin(t), 0.0) animate_parametric_curve(curve, (0, 2*np.pi), n_frames=50)

Source code in psiqit\visualization\animation.py
def animate_parametric_curve(
    curve_func: Callable[[float], Tuple[float, float, float]],
    t_range: Tuple[float, float],
    n_frames: int = 100,
    interval: int = 50,
    save_path: Optional[str] = None,
    figsize: Tuple[float, float] = (8, 8),
    title: str = "Parametric Curve on Bloch Sphere",
    color: str = 'purple',
    show_trace: bool = True
):
    """
    Animate a parametric curve on the Bloch sphere

    Args:
        curve_func: Function f(t) -> (x, y, z) on the Bloch sphere
        t_range: (t_min, t_max) range
        n_frames: Number of animation frames
        interval: Time between frames in milliseconds
        save_path: Path to save animation
        figsize: Figure size
        title: Title of the animation
        color: Color of the curve
        show_trace: Show the full trace of the curve

    Example:
        >>> def curve(t):
        ...     # Circular path on equator
        ...     return (np.cos(t), np.sin(t), 0.0)
        >>> animate_parametric_curve(curve, (0, 2*np.pi), n_frames=50)
    """
    # Generate points
    t_values = np.linspace(t_range[0], t_range[1], n_frames)
    points = [curve_func(t) for t in t_values]

    # Animate using animate_bloch_sphere
    animate_bloch_sphere(
        states=points,
        interval=interval,
        save_path=save_path,
        figsize=figsize,
        title=title,
        color=color,
        show_trace=show_trace,
        trace_length=n_frames if show_trace else None
    )

animate_quantum_circuit(circuit, shots=100, interval=200, save_path=None)

Animate measurement outcomes of a quantum circuit

Parameters:

Name Type Description Default
circuit

QuantumCircuit object

required
shots int

Number of measurement shots

100
interval int

Time between frames in milliseconds

200
save_path Optional[str]

Path to save animation

None
Example

from psiqit.circuits import QuantumCircuit circ = QuantumCircuit(2) circ.h(0).cx(0, 1) animate_quantum_circuit(circ, shots=100)

Source code in psiqit\visualization\animation.py
def animate_quantum_circuit(
    circuit,
    shots: int = 100,
    interval: int = 200,
    save_path: Optional[str] = None
):
    """
    Animate measurement outcomes of a quantum circuit

    Args:
        circuit: QuantumCircuit object
        shots: Number of measurement shots
        interval: Time between frames in milliseconds
        save_path: Path to save animation

    Example:
        >>> from psiqit.circuits import QuantumCircuit
        >>> circ = QuantumCircuit(2)
        >>> circ.h(0).cx(0, 1)
        >>> animate_quantum_circuit(circ, shots=100)
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return

    try:
        import matplotlib.pyplot as plt
        from matplotlib.animation import FuncAnimation

        # Get measurement results
        result = circuit.measure(shots=shots)
        counts = result['counts']
        all_states = list(counts.keys())
        all_counts = list(counts.values())

        # Create figure
        fig, ax = plt.subplots(figsize=(8, 5))

        # Initialize bars
        bars = ax.bar(all_states, [0] * len(all_states), color='skyblue', edgecolor='black')

        ax.set_xlabel('State')
        ax.set_ylabel('Counts')
        ax.set_title('Quantum Circuit Measurements')
        ax.set_ylim(0, max(all_counts) * 1.1)

        # Total shots
        total = sum(all_counts)
        ax.text(0.95, 0.95, f'Total: {total}', transform=ax.transAxes,
                ha='right', va='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

        # Update function
        def update(frame):
            # Simulate incremental measurements
            cumulative_counts = {state: 0 for state in all_states}
            for i in range(min(frame + 1, shots)):
                # Simulate a measurement
                state = np.random.choice(all_states, p=np.array(all_counts)/total)
                cumulative_counts[state] = cumulative_counts.get(state, 0) + 1

            # Update bars
            for bar, state in zip(bars, all_states):
                bar.set_height(cumulative_counts.get(state, 0))

            ax.set_title(f'Quantum Circuit Measurements - Shot {min(frame+1, shots)}/{shots}')

            return bars

        # Create animation
        anim = FuncAnimation(fig, update, frames=shots, interval=interval, blit=False)

        # Save or show
        if save_path is not None:
            anim.save(save_path, writer='pillow', fps=1000/interval)
            logger.info(f"Animation saved to {save_path}")
        else:
            plt.show()

        plt.close()

    except Exception as e:
        logger.warning(f"Could not create circuit animation: {e}")

render_equation(latex, output_file=None, fontsize=16, dpi=150, figsize=(8, 2))

Render a LaTeX equation as an image or return as string

Parameters:

Name Type Description Default
latex str

LaTeX equation string

required
output_file Optional[str]

Path to save the image (if None, returns LaTeX string)

None
fontsize int

Font size for the equation

16
dpi int

Image resolution

150
figsize Tuple[float, float]

Figure size (width, height)

(8, 2)

Returns:

Name Type Description
str str

LaTeX string or path to saved image

Example

latex = r"E = mc^2" render_equation(latex, output_file="einstein.png")

Or display in notebook

from IPython.display import display, Latex display(Latex(render_equation(latex)))

Source code in psiqit\visualization\symbolic_plot.py
def render_equation(
    latex: str,
    output_file: Optional[str] = None,
    fontsize: int = 16,
    dpi: int = 150,
    figsize: Tuple[float, float] = (8, 2)
) -> str:
    """
    Render a LaTeX equation as an image or return as string

    Args:
        latex: LaTeX equation string
        output_file: Path to save the image (if None, returns LaTeX string)
        fontsize: Font size for the equation
        dpi: Image resolution
        figsize: Figure size (width, height)

    Returns:
        str: LaTeX string or path to saved image

    Example:
        >>> latex = r"E = mc^2"
        >>> render_equation(latex, output_file="einstein.png")
        >>> # Or display in notebook
        >>> from IPython.display import display, Latex
        >>> display(Latex(render_equation(latex)))
    """
    if output_file is not None and _has_matplotlib():
        try:
            import matplotlib.pyplot as plt

            fig, ax = plt.subplots(figsize=figsize)
            ax.text(0.5, 0.5, f"${latex}$", 
                   fontsize=fontsize, ha='center', va='center')
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
            ax.axis('off')

            plt.tight_layout()
            plt.savefig(output_file, dpi=dpi, bbox_inches='tight', transparent=True)
            plt.close()

            logger.info(f"Equation rendered to {output_file}")
            return output_file

        except Exception as e:
            logger.warning(f"Could not render equation: {e}")

    return f"${latex}$"

schrodinger_equation(time_dependent=True)

Get the Schrodinger equation in LaTeX format

Parameters:

Name Type Description Default
time_dependent bool

If True, returns time-dependent Schrodinger equation If False, returns time-independent Schrodinger equation

True

Returns:

Name Type Description
str str

LaTeX equation string

Example

print(schrodinger_equation()) i\hbar\frac{\partial}{\partial t}\psi = \hat{H}\psi print(schrodinger_equation(time_dependent=False)) \hat{H}\psi = E\psi

Source code in psiqit\visualization\symbolic_plot.py
def schrodinger_equation(time_dependent: bool = True) -> str:
    """
    Get the Schrodinger equation in LaTeX format

    Args:
        time_dependent: If True, returns time-dependent Schrodinger equation
                        If False, returns time-independent Schrodinger equation

    Returns:
        str: LaTeX equation string

    Example:
        >>> print(schrodinger_equation())
        i\\hbar\\frac{\\partial}{\\partial t}\\psi = \\hat{H}\\psi
        >>> print(schrodinger_equation(time_dependent=False))
        \\hat{H}\\psi = E\\psi
    """
    if time_dependent:
        return r"i\hbar\frac{\partial}{\partial t}\psi = \hat{H}\psi"
    else:
        return r"\hat{H}\psi = E\psi"

dirac_notation()

Get common Dirac notation symbols in LaTeX

Returns:

Name Type Description
Dict Dict[str, str]

Mapping of notation to LaTeX code

Example

dirac = dirac_notation() print(dirac['ket_zero']) # |0\rangle print(dirac['inner_product']) # \langle \phi | \psi \rangle

Source code in psiqit\visualization\symbolic_plot.py
def dirac_notation() -> Dict[str, str]:
    """
    Get common Dirac notation symbols in LaTeX

    Returns:
        Dict: Mapping of notation to LaTeX code

    Example:
        >>> dirac = dirac_notation()
        >>> print(dirac['ket_zero'])  # |0\\rangle
        >>> print(dirac['inner_product'])  # \\langle \\phi | \\psi \\rangle
    """
    return {
        'ket_zero': r'|0\rangle',
        'ket_one': r'|1\rangle',
        'ket_plus': r'|+\rangle',
        'ket_minus': r'|-\rangle',
        'ket_psi': r'|\psi\rangle',
        'ket_phi': r'|\phi\rangle',
        'bra_zero': r'\langle 0|',
        'bra_one': r'\langle 1|',
        'bra_plus': r'\langle +|',
        'bra_minus': r'\langle -|',
        'bra_psi': r'\langle \psi|',
        'bra_phi': r'\langle \phi|',
        'inner_product': r'\langle \phi | \psi \rangle',
        'outer_product': r'|\psi\rangle\langle \psi|',
        'projector': r'|\psi\rangle\langle \psi|',
        'trace': r'\text{Tr}',
        'density_matrix': r'\rho = |\psi\rangle\langle \psi|',
    }

pauli_matrices()

Get Pauli matrices in LaTeX format

Returns:

Name Type Description
Dict Dict[str, str]

Pauli matrices as LaTeX strings

Example

pauli = pauli_matrices() print(pauli['X']) \sigma_x = \begin{pmatrix} 0 & 1 \ 1 & 0 \end{pmatrix}

Source code in psiqit\visualization\symbolic_plot.py
def pauli_matrices() -> Dict[str, str]:
    """
    Get Pauli matrices in LaTeX format

    Returns:
        Dict: Pauli matrices as LaTeX strings

    Example:
        >>> pauli = pauli_matrices()
        >>> print(pauli['X'])
        \\sigma_x = \\begin{pmatrix} 0 & 1 \\\\ 1 & 0 \\end{pmatrix}
    """
    return {
        'I': r'I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}',
        'X': r'\sigma_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}',
        'Y': r'\sigma_y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}',
        'Z': r'\sigma_z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}',
        'sigma_x': r'\sigma_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}',
        'sigma_y': r'\sigma_y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}',
        'sigma_z': r'\sigma_z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}',
        'commutation': r'[\sigma_i, \sigma_j] = 2i\epsilon_{ijk}\sigma_k',
        'anticommutation': r'\{\sigma_i, \sigma_j\} = 2\delta_{ij}I',
    }

bloch_sphere_equation(theta=None, phi=None)

Get the Bloch sphere equation in LaTeX format

Parameters:

Name Type Description Default
theta Optional[float]

Polar angle (if provided, includes specific state)

None
phi Optional[float]

Azimuthal angle (if provided, includes specific state)

None

Returns:

Name Type Description
str str

LaTeX equation string

Example

print(bloch_sphere_equation()) |\psi\rangle = \cos(\theta/2)|0\rangle + e^{i\phi}\sin(\theta/2)|1\rangle print(bloch_sphere_equation(theta=np.pi/4, phi=np.pi/2)) |\psi\rangle = \cos(\pi/8)|0\rangle + e^{i\pi/2}\sin(\pi/8)|1\rangle

Source code in psiqit\visualization\symbolic_plot.py
def bloch_sphere_equation(theta: Optional[float] = None, phi: Optional[float] = None) -> str:
    """
    Get the Bloch sphere equation in LaTeX format

    Args:
        theta: Polar angle (if provided, includes specific state)
        phi: Azimuthal angle (if provided, includes specific state)

    Returns:
        str: LaTeX equation string

    Example:
        >>> print(bloch_sphere_equation())
        |\\psi\\rangle = \\cos(\\theta/2)|0\\rangle + e^{i\\phi}\\sin(\\theta/2)|1\\rangle
        >>> print(bloch_sphere_equation(theta=np.pi/4, phi=np.pi/2))
        |\\psi\\rangle = \\cos(\\pi/8)|0\\rangle + e^{i\\pi/2}\\sin(\\pi/8)|1\\rangle
    """
    if theta is not None and phi is not None:
        theta_str = f"{theta:.2f}" if isinstance(theta, float) else str(theta)
        phi_str = f"{phi:.2f}" if isinstance(phi, float) else str(phi)
        return rf"|\psi\rangle = \cos({theta_str}/2)|0\rangle + e^{{i{phi_str}}}\sin({theta_str}/2)|1\rangle"
    elif theta is not None:
        theta_str = f"{theta:.2f}" if isinstance(theta, float) else str(theta)
        return rf"|\psi\rangle = \cos({theta_str}/2)|0\rangle + e^{{i\phi}}\sin({theta_str}/2)|1\rangle"
    else:
        return r"|\psi\rangle = \cos(\theta/2)|0\rangle + e^{i\phi}\sin(\theta/2)|1\rangle"

heisenberg_uncertainty()

Get the Heisenberg uncertainty principle in LaTeX format

Returns:

Name Type Description
str str

LaTeX equation string

Example

print(heisenberg_uncertainty()) \Delta x \Delta p \geq \frac{\hbar}{2}

Source code in psiqit\visualization\symbolic_plot.py
def heisenberg_uncertainty() -> str:
    """
    Get the Heisenberg uncertainty principle in LaTeX format

    Returns:
        str: LaTeX equation string

    Example:
        >>> print(heisenberg_uncertainty())
        \\Delta x \\Delta p \\geq \\frac{\\hbar}{2}
    """
    return r"\Delta x \Delta p \geq \frac{\hbar}{2}"

commutation_relation()

Get the canonical commutation relation in LaTeX format

Returns:

Name Type Description
str str

LaTeX equation string

Example

print(commutation_relation()) [x, p] = i\hbar

Source code in psiqit\visualization\symbolic_plot.py
def commutation_relation() -> str:
    """
    Get the canonical commutation relation in LaTeX format

    Returns:
        str: LaTeX equation string

    Example:
        >>> print(commutation_relation())
        [x, p] = i\\hbar
    """
    return r"[x, p] = i\hbar"

maxwell_equations()

Get Maxwell's equations in LaTeX format

Returns:

Type Description
List[str]

List[str]: List of LaTeX equation strings

Example

for eq in maxwell_equations(): ... print(eq) \nabla \cdot \mathbf{E} = \frac{\rho}{\varepsilon_0} \nabla \cdot \mathbf{B} = 0 \nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t} \nabla \times \mathbf{B} = \mu_0 \mathbf{J} + \mu_0 \varepsilon_0 \frac{\partial \mathbf{E}}{\partial t}

Source code in psiqit\visualization\symbolic_plot.py
def maxwell_equations() -> List[str]:
    """
    Get Maxwell's equations in LaTeX format

    Returns:
        List[str]: List of LaTeX equation strings

    Example:
        >>> for eq in maxwell_equations():
        ...     print(eq)
        \\nabla \\cdot \\mathbf{E} = \\frac{\\rho}{\\varepsilon_0}
        \\nabla \\cdot \\mathbf{B} = 0
        \\nabla \\times \\mathbf{E} = -\\frac{\\partial \\mathbf{B}}{\\partial t}
        \\nabla \\times \\mathbf{B} = \\mu_0 \\mathbf{J} + \\mu_0 \\varepsilon_0 \\frac{\\partial \\mathbf{E}}{\\partial t}
    """
    return [
        r"\nabla \cdot \mathbf{E} = \frac{\rho}{\varepsilon_0}",
        r"\nabla \cdot \mathbf{B} = 0",
        r"\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}",
        r"\nabla \times \mathbf{B} = \mu_0 \mathbf{J} + \mu_0 \varepsilon_0 \frac{\partial \mathbf{E}}{\partial t}",
    ]

quantum_equations()

Get common quantum mechanics equations in LaTeX format

Returns:

Name Type Description
Dict Dict[str, str]

Mapping of equation names to LaTeX strings

Example

eqs = quantum_equations() print(eqs['schrodinger']) i\hbar\frac{\partial}{\partial t}\psi = \hat{H}\psi

Source code in psiqit\visualization\symbolic_plot.py
def quantum_equations() -> Dict[str, str]:
    """
    Get common quantum mechanics equations in LaTeX format

    Returns:
        Dict: Mapping of equation names to LaTeX strings

    Example:
        >>> eqs = quantum_equations()
        >>> print(eqs['schrodinger'])
        i\\hbar\\frac{\\partial}{\\partial t}\\psi = \\hat{H}\\psi
    """
    return {
        'schrodinger': r"i\hbar\frac{\partial}{\partial t}\psi = \hat{H}\psi",
        'schrodinger_stationary': r"\hat{H}\psi = E\psi",
        'heisenberg': r"\frac{d\hat{A}}{dt} = \frac{i}{\hbar}[\hat{H}, \hat{A}] + \frac{\partial \hat{A}}{\partial t}",
        'lindblad': r"\frac{d\rho}{dt} = -\frac{i}{\hbar}[\hat{H}, \rho] + \sum_k \gamma_k (L_k \rho L_k^\dagger - \frac{1}{2}\{L_k^\dagger L_k, \rho\})",
        'density_matrix': r"\rho = \sum_i p_i |\psi_i\rangle\langle \psi_i|",
        'fidelity': r"F(\rho, \sigma) = \text{Tr}(\sqrt{\sqrt{\rho}\sigma\sqrt{\rho}})^2",
        'entanglement_entropy': r"S(\rho_A) = -\text{Tr}(\rho_A \log \rho_A)",
        'concurrence': r"C(\rho) = \max(0, \lambda_1 - \lambda_2 - \lambda_3 - \lambda_4)",
        'negativity': r"\mathcal{N}(\rho) = \frac{\|\rho^{T_A}\|_1 - 1}{2}",
        'uncertainty': r"\Delta x \Delta p \geq \frac{\hbar}{2}",
        'commutation': r"[x, p] = i\hbar",
        'bloch': r"|\psi\rangle = \cos(\theta/2)|0\rangle + e^{i\phi}\sin(\theta/2)|1\rangle",
        'bell': r"|\Phi^+\rangle = \frac{|00\rangle + |11\rangle}{\sqrt{2}}",
        'ghz': r"|\text{GHZ}\rangle = \frac{|00\ldots 0\rangle + |11\ldots 1\rangle}{\sqrt{2}}",
        'w': r"|W\rangle = \frac{|100\ldots 0\rangle + |010\ldots 0\rangle + \ldots + |000\ldots 1\rangle}{\sqrt{n}}",
    }

render_equation_as_image(latex, output_path, fontsize=20, dpi=200, figsize=(10, 2), bg_color='white', text_color='black')

Render a LaTeX equation as an image file

Parameters:

Name Type Description Default
latex str

LaTeX equation string

required
output_path str

Path to save the image

required
fontsize int

Font size

20
dpi int

Image resolution

200
figsize Tuple[float, float]

Figure size (width, height)

(10, 2)
bg_color str

Background color

'white'
text_color str

Text color

'black'

Returns:

Name Type Description
bool bool

True if successful, False otherwise

Example

success = render_equation_as_image( ... r"E = mc^2", ... "einstein.png", ... fontsize=24 ... )

Source code in psiqit\visualization\symbolic_plot.py
def render_equation_as_image(
    latex: str,
    output_path: str,
    fontsize: int = 20,
    dpi: int = 200,
    figsize: Tuple[float, float] = (10, 2),
    bg_color: str = 'white',
    text_color: str = 'black'
) -> bool:
    """
    Render a LaTeX equation as an image file

    Args:
        latex: LaTeX equation string
        output_path: Path to save the image
        fontsize: Font size
        dpi: Image resolution
        figsize: Figure size (width, height)
        bg_color: Background color
        text_color: Text color

    Returns:
        bool: True if successful, False otherwise

    Example:
        >>> success = render_equation_as_image(
        ...     r"E = mc^2",
        ...     "einstein.png",
        ...     fontsize=24
        ... )
    """
    if not _has_matplotlib():
        logger.warning("matplotlib not available. Install with: pip install matplotlib")
        return False

    try:
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(figsize=figsize)
        fig.patch.set_facecolor(bg_color)
        ax.set_facecolor(bg_color)

        ax.text(0.5, 0.5, f"${latex}$", 
               fontsize=fontsize, ha='center', va='center',
               color=text_color)
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 1)
        ax.axis('off')

        plt.tight_layout()
        plt.savefig(output_path, dpi=dpi, bbox_inches='tight', 
                   facecolor=bg_color, edgecolor='none')
        plt.close()

        logger.info(f"Equation rendered to {output_path}")
        return True

    except Exception as e:
        logger.warning(f"Could not render equation: {e}")
        return False

info()

Get information about the visualization module

Returns:

Name Type Description
dict dict

Module information

Source code in psiqit\visualization\__init__.py
def info() -> dict:
    """
    Get information about the visualization module

    Returns:
        dict: Module information
    """
    return {
        'module': 'psiqit.visualization',
        'version': __version__,
        'submodules': ['bloch', 'circuit_drawer', 'wigner', 'husimi', 'animation', 'symbolic_plot'],
        'exports': len(__all__),
    }

test()

Run basic tests for the visualization module

Returns:

Name Type Description
dict dict

Test results

Source code in psiqit\visualization\__init__.py
def test() -> dict:
    """
    Run basic tests for the visualization module

    Returns:
        dict: Test results
    """
    results = {}

    # Test bloch
    try:
        from .bloch import state_to_bloch, bloch_sphere
        from ..quantum.state import zero
        x, y, z = state_to_bloch(zero())
        results['bloch'] = abs(z - 1.0) < 1e-10
    except Exception as e:
        results['bloch'] = str(e)

    # Test circuit_drawer
    try:
        from .circuit_drawer import draw_circuit, circuit_statistics
        from ..circuits.circuit import QuantumCircuit
        circ = QuantumCircuit(2)
        circ.h(0).cx(0, 1)
        draw = draw_circuit(circ)
        stats = circuit_statistics(circ)
        results['circuit_drawer'] = stats['total_gates'] == 2
    except Exception as e:
        results['circuit_drawer'] = str(e)

    # Test wigner
    try:
        from .wigner import wigner_function_gaussian, plot_wigner
        W, x, p = wigner_function_gaussian()
        results['wigner'] = W.shape == (100, 100)
    except Exception as e:
        results['wigner'] = str(e)

    # Test husimi
    try:
        from .husimi import husimi_function_gaussian, plot_husimi
        Q, x, p = husimi_function_gaussian()
        results['husimi'] = Q.shape == (100, 100)
    except Exception as e:
        results['husimi'] = str(e)

    # Test animation
    try:
        from .animation import animate_bloch_sphere
        # Just check import
        results['animation'] = True
    except Exception as e:
        results['animation'] = str(e)

    # Test symbolic_plot
    try:
        from .symbolic_plot import render_equation, schrodinger_equation
        eq = schrodinger_equation()
        results['symbolic_plot'] = 'hbar' in eq
    except Exception as e:
        results['symbolic_plot'] = str(e)

    return results