# Visualization and animation

## Bloch sphere

class Bloch(fig=None, axes=None, view=None, figsize=None, background=False)

  Class for plotting data on the Bloch sphere. Valid data can be either points, vectors, or Qobj objects.

  Attributes:
    axes matplotlib.axes.Axes

      User supplied Matplotlib axes for Bloch sphere animation.

    fig matplotlib.figure.Figure

      User supplied Matplotlib Figure instance for plotting Bloch sphere.

    font_color str, default ‘black’

      Color of font used for Bloch sphere labels.

    font_size int, default 20

      Size of font used for Bloch sphere labels.

    frame_alpha float, default 0.1

      Sets transparency of Bloch sphere frame.

    frame_color str, default ‘gray’

      Color of sphere wireframe.

    frame_width int, default 1

      Width of wireframe.

    point_color list, default [“b”, “r”, “g”, “#CC6600”]

      List of colors for Bloch sphere point markers to cycle through, i.e. by default, points 0 and 4 will both be blue (‘b’).

    point_marker list, default [“o”, “s”, “d”, “^”]

      List of point marker shapes to cycle through.

    point_size list, default [25, 32, 35, 45]

      List of point marker sizes. Note, not all point markers look the same size when plotted!

    sphere_alpha float, default 0.2

      Transparency of Bloch sphere itself.

    sphere_color str, default ‘#FFDDDD’

      Color of Bloch sphere.

    figsize list, default [7, 7]

      Figure size of Bloch sphere plot. Best to have both numbers the same; otherwise you will have a Bloch sphere that looks like a football.

    vector_color list, [“g”, “#CC6600”, “b”, “r”]

      List of vector colors to cycle through.

    vector_width int, default 5

      Width of displayed vectors.

    vector_style str, default ‘-|>’

      Vector arrowhead style (from matplotlib’s arrow style).

    vector_mutation int, default 20

      Width of vectors arrowhead.

    view list, default [-60, 30]

      Azimuthal and Elevation viewing angles.

    xlabel list, default [“$x$”, “”]

      List of strings corresponding to +x and -x axes labels, respectively.

    xlpos list, default [1.1, -1.1]

      Positions of +x and -x labels respectively.

    ylabel list, default [“$y$”, “”]

      List of strings corresponding to +y and -y axes labels, respectively.

    ylpos list, default [1.2, -1.2]

      Positions of +y and -y labels respectively.

    zlabel list, default [‘$\left|0\right>$’, ‘$\left|1\right>$’]

      List of strings corresponding to +z and -z axes labels, respectively.

    zlpos list, default [1.2, -1.2]

      Positions of +z and -z labels respectively.

  add_annotation(state_or_vector, text, **kwargs)

    Add a text or LaTeX annotation to Bloch sphere, parametrized by a qubit state or a vector.

    Parameters:
      state_or_vector `Qobj`/array/list/tuple

        Position for the annotaion. Qobj of a qubit or a vector of 3 elements.

      text str

        Annotation text. You can use LaTeX, but remember to use raw string e.g. r”$langle x rangle$” or escape backslashes e.g. “$\langle x \rangle$”.

      kwargs

        Options as for mplot3d.axes3d.text, including: fontsize, color, horizontalalignment, verticalalignment.

  add_arc(start, end, fmt='b', steps=None, **kwargs)

    Adds an arc between two points on a sphere. The arc is set to be blue solid curve by default.

    The start and end points must be on the same sphere (i.e. have the same radius) but need not be on the unit sphere.

    Parameters:
      start `Qobj` or array-like

        Array with cartesian coordinates of the first point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

      end `Qobj` or array-like

        Array with cartesian coordinates of the second point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

      fmt str, default: “b”

        A matplotlib format string for rendering the arc.

      steps int, default: None

        The number of segments to use when rendering the arc. The default uses 100 steps times the distance between the start and end points, with a minimum of 2 steps.

      **kwargs dict

        Additional parameters to pass to the matplotlib .plot function when rendering this arc.

  add_line(start, end, fmt='k', **kwargs)

    Adds a line segment connecting two points on the bloch sphere.

    The line segment is set to be a black solid line by default.

    Parameters:
      start `Qobj` or array-like

        Array with cartesian coordinates of the first point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

      end `Qobj` or array-like

        Array with cartesian coordinates of the second point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

      fmt str, default: “k”

        A matplotlib format string for rendering the line.

      **kwargs dict

        Additional parameters to pass to the matplotlib .plot function when rendering this line.

  add_points(
    points,
    meth: Literal['s', 'm', 'l'] = 's',
    colors=None,
    alpha=1.0,
  )

    Add a list of data points to bloch sphere.

    Parameters:
      points array_like

        Collection of data points.

      meth{‘s’, ‘m’, ‘l’}

        Type of points to plot, use ‘m’ for multicolored, ‘l’ for points connected with a line.

      colors array_like

        Optional array with colors for the points. A single color for meth ‘s’, and list of colors for meth ‘m’

      alpha float, default=1.

        Transparency value for the vectors. Values between 0 and 1.

    Notes

    When using `meth=l` in QuTiP 4.6, the line transparency defaulted to `0.75` and there was no way to alter it. When the `alpha` parameter was added in QuTiP 4.7, the default became `alpha=1.0` for values of `meth`.

  add_states(
    state,
    kind: Literal['vector', 'point'] = 'vector',
    colors=None,
    alpha=1.0,
  )

    Add a state vector Qobj to Bloch sphere.

    Parameters:
      state `Qobj` or array_like

        Input state vector or list.

      kind{‘vector’, ‘point’}

        Type of object to plot.

      colors array_like

        Optional array with colors for the states.

      alpha float, default=1.

        Transparency value for the vectors. Values between 0 and 1.

  add_vectors(vectors, colors=None, alpha=1.0)

    Add a list of vectors to Bloch sphere.

    Parameters:
      vectors array_like

        Array with vectors of unit length or smaller.

      colors array_like

        Optional array with colors for the vectors.

      alpha float, default=1.

        Transparency value for the vectors. Values between 0 and 1.

  clear()

    Resets Bloch sphere data sets to empty.

  make_sphere()

    Plots Bloch sphere and data sets.

  render()

    Render the Bloch sphere and its data sets in on given figure and axes.

  save(name=None, format='png', dirc=None, dpin=None)

    Saves Bloch sphere to file of type `format` in directory `dirc`.

    Parameters:
      name str

        Name of saved image. Must include path and format as well. i.e. ‘/Users/Me/Desktop/bloch.png’ This overrides the ‘format’ and ‘dirc’ arguments.

      format str

        Format of output image.

      dirc str

        Directory for output images. Defaults to current working directory.

      dpin int

        Resolution in dots per inch.

    Returns:
      File containing plot of Bloch sphere.
  set_label_convention(convention)

    Set x, y and z labels according to one of conventions.

    Parameters:
      convention string

        One of the following:

        - “original”

        - “xyz”

        - “sx sy sz”

        - “01”

        - “polarization jones”

        - “polarization jones letters” see also: https://en.wikipedia.org/wiki/Jones_calculus

        - “polarization stokes” see also: https://en.wikipedia.org/wiki/Stokes_parameters

  show()

    Display Bloch sphere and corresponding data sets.

    Notes

    When using inline plotting in Jupyter notebooks, any figure created in a notebook cell is displayed after the cell executes. Thus if you create a figure yourself and use it create a Bloch sphere with `b = Bloch(..., fig=fig)` and then call `b.show()` in the same cell, then the figure will be displayed twice. If you do create your own figure, the simplest solution to this is to not call `.show()` in the cell you create the figure in.

## Graphs and Visualization

Functions for visualizing results of quantum dynamics simulations, visualizations of quantum states and processes.

hinton(

  rho,
  x_basis=None,
  y_basis=None,
  color_style='scaled',
  label_top=True,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Draws a Hinton diagram to visualize a density matrix or superoperator.

  Parameters:
    rho qobj

      Input density matrix or superoperator.

      Note

      Hinton plots of superoperators are currently only supported for qubits.

    x_basis list of strings, optional

      list of x ticklabels to represent x basis of the input.

    y_basis list of strings, optional

      list of y ticklabels to represent y basis of the input.

    color_style str, {“scaled”, “threshold”, “phase”}, default: “scaled”

      Determines how colors are assigned to each square:

      - If set to `"scaled"` (default), each color is chosen by passing the absolute value of the corresponding matrix element into cmap with the sign of the real part.

      - If set to `"threshold"`, each square is plotted as the maximum of cmap for the positive real part and as the minimum for the negative part of the matrix element; note that this generalizes “threshold” to complex numbers.

      - If set to `"phase"`, each color is chosen according to the angle of the corresponding matrix element.

    label_top bool, default: True

      If True, x ticklabels will be placed on top, otherwise they will appear below the plot.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The ax context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

  Raises:
    ValueError

      Input argument is not a quantum object.

  Examples

      >>> import qutip

      >>> dm = qutip.rand_dm(4)
      >>> fig, ax = qutip.hinton(dm)
      >>> fig.show()

      >>> qutip.settings.colorblind_safe = True
      >>> fig, ax = qutip.hinton(dm, color_style="threshold")
      >>> fig.show()
      >>> qutip.settings.colorblind_safe = False

      >>> fig, ax = qutip.hinton(dm, color_style="phase")
      >>> fig.show()

matrix_histogram(

  M,
  x_basis=None,
  y_basis=None,
  limits=None,
  bar_style='real',
  color_limits=None,
  color_style='real',
  options=None,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Draw a histogram for the matrix M, with the given x and y labels and title.

  Parameters:
    M Matrix of Qobj

      The matrix to visualize

    x_basis list of strings, optional

      list of x ticklabels

    y_basis list of strings, optional

      list of y ticklabels

    limits list/array with two float numbers, optional

      The z-axis limits [min, max]

    bar_style str, {“real”, “img”, “abs”, “phase”}, default: “real”

      - If set to `"real"` (default), each bar is plotted as the real part of the corresponding matrix element

      - If set to `"img"`, each bar is plotted as the imaginary part of the corresponding matrix element

      - If set to `"abs"`, each bar is plotted as the absolute value of the corresponding matrix element

      - If set to `"phase"` (default), each bar is plotted as the angle of the corresponding matrix element

    color_limits list/array with two float numbers, optional

      The limits of colorbar [min, max]

    color_style str, {“real”, “img”, “abs”, “phase”}, default: “real”

      Determines how colors are assigned to each square:

      - If set to `"real"` (default), each color is chosen according to the real part of the corresponding matrix element.

      - If set to `"img"`, each color is chosen according to the imaginary part of the corresponding matrix element.

      - If set to `"abs"`, each color is chosen according to the absolute value of the corresponding matrix element.

      - If set to `"phase"`, each color is chosen according to the angle of the corresponding matrix element.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      show colorbar

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

    options dict, optional

      A dictionary containing extra options for the plot. The names (keys) and values of the options are described below:

      ‘zticks’list of numbers, optional

        A list of z-axis tick locations.

      ‘bars_spacing’float, default: 0.1

        spacing between bars.

      ‘bars_alpha’float, default: 1.

        transparency of bars, should be in range 0 - 1

      ‘bars_lw’float, default: 0.5

        linewidth of bars’ edges.

      ‘bars_edgecolor’color, default: ‘k’

        The colors of the bars’ edges. Examples: ‘k’, (0.1, 0.2, 0.5) or ‘#0f0f0f80’.

      ‘shade’bool, default: True

        Whether to shade the dark sides of the bars (True) or not (False). The shading is relative to plot’s source of light.

      ‘azim’float, default: -35

        The azimuthal viewing angle.

      ‘elev’float, default: 35

        The elevation viewing angle.

      ‘stick’bool, default: False

        Changes xlim and ylim in such a way that bars next to XZ and YZ planes will stick to those planes. This option has no effect if `ax` is passed as a parameter.

      ‘cbar_pad’float, default: 0.04

        The fraction of the original axes between the colorbar and the new image axes. (i.e. the padding between the 3D figure and the colorbar).

      ‘cbar_to_z’bool, default: False

        Whether to set the color of maximum and minimum z-values to the maximum and minimum colors in the colorbar (True) or not (False).

      ‘threshold’: float, optional

        Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

  Raises:
    ValueError

      Input argument is not valid.

plot_energy_levels(

  H_list,
  h_labels=None,
  energy_levels=None,
  N=0,
  *,
  fig=None,
  ax=None,

)

  Plot the energy level diagrams for a list of Hamiltonians. Include up to N energy levels. For each element in H_list, the energy levels diagram for the cummulative Hamiltonian sum(H_list[0:n]) is plotted, where n is the index of an element in H_list.

  Parameters:
    H_list List of Qobj

      A list of Hamiltonians.

    h_lables List of string, optional

      A list of xticklabels for each Hamiltonian

    energy_levels List of string, optional

      A list of yticklabels to the left of energy levels of the initial Hamiltonian.

    N int, default: 0

      The number of energy levels to plot

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, ax tuple

      A tuple of the matplotlib figure and axes instances used to produce the figure.

  Raises:
    ValueError

      Input argument is not valid.

plot_expectation_values(results, ylabels=None, *, fig=None, axes=None)

  Visualize the results (expectation values) for an evolution solver. results is assumed to be an instance of Result, or a list of Result instances.

  Parameters:
    results(list of) `Result`

      List of results objects returned by any of the QuTiP evolution solvers.

    ylabels list of strings, optional

      The y-axis labels. List should be of the same length as results.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    axes(list of) axes instances, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, axes tuple

      A tuple of the matplotlib figure and array of axes instances used to produce the figure.

plot_fock_distribution(

  rho,
  fock_numbers=None,
  color='green',
  unit_y_range=True,
  *,
  fig=None,
  ax=None,

)

  Plot the Fock distribution for a density matrix (or ket) that describes an oscillator mode.

  Parameters:
    rho `Qobj`

      The density matrix (or ket) of the state to visualize.

    fock_numbers list of strings, optional

      list of x ticklabels to represent fock numbers

    color color or list of colors, default: “green”

      The colors of the bar faces.

    unit_y_range bool, default: True

      Set y-axis limits [0, 1] or not

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

plot_qubism(

  ket,
  theme='light',
  how='pairs',
  grid_iteration=1,
  legend_iteration=0,
  *,
  fig=None,
  ax=None,

)

  Qubism plot for pure states of many qudits. Works best for spin chains, especially with even number of particles of the same dimension. Allows to see entanglement between first 2k particles and the rest.

  Note

  colorblind_safe does not apply because of its unique colormap

  Parameters:
    ket Qobj

      Pure state for plotting.

    theme str {‘light’, ‘dark’}, default: ‘light’

      Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.

    how str {‘pairs’, ‘pairs_skewed’ or ‘before_after’}, default: ‘pairs’

      Type of Qubism plotting. Options:

      - ‘pairs’ - typical coordinates,

      - ‘pairs_skewed’ - for ferromagnetic/antriferromagnetic plots,

      - ‘before_after’ - related to Schmidt plot (see also: plot_schmidt).

    grid_iteration int, default: 1

      Helper lines to be drawn on plot. Show tiles for 2*grid_iteration particles vs all others.

    legend_iteration int or ‘grid_iteration’ or ‘all’, default: 0

      Show labels for first `2*legend_iteration` particles. Option ‘grid_iteration’ sets the same number of particles as for grid_iteration. Option ‘all’ makes label for all particles. Typically it should be 0, 1, 2 or perhaps 3.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

  Notes

  See also [1].

  References

  [1]

  J. Rodriguez-Laguna, P. Migdal, M. Ibanez Berganza, M. Lewenstein and G. Sierra, Qubism: self-similar visualization of many-body wavefunctions, New J. Phys. 14 053028, arXiv:1112.3560 (2012), open access.

plot_schmidt(

  ket,
  theme='light',
  splitting=None,
  labels_iteration=(3, 2),
  *,
  fig=None,
  ax=None,

)

  Plotting scheme related to Schmidt decomposition. Converts a state into a matrix (A_ij -> A_i^j), where rows are first particles and columns - last.

  See also: plot_qubism with how=’before_after’ for a similar plot.

  Note

  colorblind_safe does not apply because of its unique colormap

  Parameters:
    ket Qobj

      Pure state for plotting.

    theme str {‘light’, ‘dark’}, default: ‘light’

      Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.

    splitting int, optional

      Plot for a number of first particles versus the rest. If not given, it is (number of particles + 1) // 2.

    labels_iteration int or pair of ints, default: (3, 2)

      Number of particles to be shown as tick labels, for first (vertical) and last (horizontal) particles, respectively.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

plot_spin_distribution(

  P,
  THETA,
  PHI,
  projection='2d',
  *,
  cmap=None,
  colorbar=False,
  fig=None,
  ax=None,

)

  Plots a spin distribution (given as meshgrid data).

  Parameters:
    P matrix

      Distribution values as a meshgrid matrix.

    THETA matrix

      Meshgrid matrix for the theta coordinate. Its range is between 0 and pi

    PHI matrix

      Meshgrid matrix for the phi coordinate. Its range is between 0 and 2*pi

    projection: str {‘2d’, ‘3d’}, default: ‘2d’

      Specify whether the spin distribution function is to be plotted as a 2D projection where the surface of the unit sphere is mapped on the unit disk (‘2d’) or surface plot (‘3d’).

    cmap a matplotlib cmap instance, optional

      The colormap.

    colorbar bool, default: False

      Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

plot_wigner(

  rho,
  xvec=None,
  yvec=None,
  method='clenshaw',
  projection='2d',
  g=np.float64(1.4142135623730951),
  sparse=False,
  parfor=False,
  *,
  cmap=None,
  colorbar=False,
  fig=None,
  ax=None,

)

  Plot the the Wigner function for a density matrix (or ket) that describes an oscillator mode.

  Parameters:
    rho `Qobj`

      The density matrix (or ket) of the state to visualize.

    xvec array_like, optional

      x-coordinates at which to calculate the Wigner function.

    yvec array_like, optional

      y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.

    method str {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

      The method used for calculating the wigner function. See the documentation for qutip.wigner for details.

    projection: str {‘2d’, ‘3d’}, default: ‘2d’

      Specify whether the Wigner function is to be plotted as a contour graph (‘2d’) or surface plot (‘3d’).

    g float

      Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2). See the documentation for qutip.wigner for details.

    sparse bool {False, True}

      Flag for sparse format. See the documentation for qutip.wigner for details.

    parfor bool {False, True}

      Flag for parallel calculation. See the documentation for qutip.wigner for details.

    cmap a matplotlib cmap instance, optional

      The colormap.

    colorbar bool, default: False

      Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

plot_wigner_sphere(

  wigner,
  reflections=False,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Plots a coloured Bloch sphere.

  Parameters:
    wigner a wigner transformation

      The wigner transformation at steps different theta and phi.

    reflections bool, default: False

      If the reflections of the sphere should be plotted as well.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The ax context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

  Notes

  Special thanks to Russell P Rundle for writing this function.

sphereplot(values, theta, phi, *, cmap=None, colorbar=True, fig=None, ax=None)

  Plots a matrix of values on a sphere

  Parameters:
    values array

      Data set to be plotted

    theta float

      Angle with respect to z-axis. Its range is between 0 and pi

    phi float

      Angle in x-y plane. Its range is between 0 and 2*pi

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, output tuple

      A tuple of the matplotlib figure and the axes instance or animation instance used to produce the figure.

Functions to animate results of quantum dynamics simulations,

anim_fock_distribution(

  rhos,
  fock_numbers=None,
  color='green',
  unit_y_range=True,
  *,
  fig=None,
  ax=None,

)

  Animation of the Fock distribution for a density matrix (or ket) that describes an oscillator mode.

  Parameters:
    rhos `Result` or list of `Qobj`

      The density matrix (or ket) of the state to visualize.

    fock_numbers list of strings, optional

      list of x ticklabels to represent fock numbers

    color color or list of colors, default: “green”

      The colors of the bar faces.

    unit_y_range bool, default: True

      Set y-axis limits [0, 1] or not

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

anim_hinton(

  rhos,
  x_basis=None,
  y_basis=None,
  color_style='scaled',
  label_top=True,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Draws an animation of Hinton diagram.

  Parameters:
    rhos `Result` or list of `Qobj`

      Input density matrix or superoperator.

      Note

      Hinton plots of superoperators are currently only supported for qubits.

    x_basis list of strings, optional

      list of x ticklabels to represent x basis of the input.

    y_basis list of strings, optional

      list of y ticklabels to represent y basis of the input.

    color_style str, {“scaled”, “threshold”, “phase”}, default: “scaled”

      Determines how colors are assigned to each square:

      - If set to `"scaled"` (default), each color is chosen by passing the absolute value of the corresponding matrix element into cmap with the sign of the real part.

      - If set to `"threshold"`, each square is plotted as the maximum of cmap for the positive real part and as the minimum for the negative part of the matrix element; note that this generalizes “threshold” to complex numbers.

      - If set to `"phase"`, each color is chosen according to the angle of the corresponding matrix element.

    label_top bool, default: True

      If True, x ticklabels will be placed on top, otherwise they will appear below the plot.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The ax context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

  Raises:
    ValueError

      Input argument is not a quantum object.

anim_matrix_histogram(

  Ms,
  x_basis=None,
  y_basis=None,
  limits=None,
  bar_style='real',
  color_limits=None,
  color_style='real',
  options=None,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Draw an animation of a histogram for the matrix M, with the given x and y labels.

  Parameters:
    Ms list of matrices or `Result`

      The matrix to visualize

    x_basis list of strings, optional

      list of x ticklabels

    y_basis list of strings, optional

      list of y ticklabels

    limits list/array with two float numbers, optional

      The z-axis limits [min, max]

    bar_style str, {“real”, “img”, “abs”, “phase”}, default: “real”

      - If set to `"real"` (default), each bar is plotted as the real part of the corresponding matrix element

      - If set to `"img"`, each bar is plotted as the imaginary part of the corresponding matrix element

      - If set to `"abs"`, each bar is plotted as the absolute value of the corresponding matrix element

      - If set to `"phase"` (default), each bar is plotted as the angle of the corresponding matrix element

    color_limits list/array with two float numbers, optional

      The limits of colorbar [min, max]

    color_style str, {“real”, “img”, “abs”, “phase”}, default: “real”

      Determines how colors are assigned to each square:

      - If set to `"real"` (default), each color is chosen according to the real part of the corresponding matrix element.

      - If set to `"img"`, each color is chosen according to the imaginary part of the corresponding matrix element.

      - If set to `"abs"`, each color is chosen according to the absolute value of the corresponding matrix element.

      - If set to `"phase"`, each color is chosen according to the angle of the corresponding matrix element.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      show colorbar

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

    options dict, optional

      A dictionary containing extra options for the plot. The names (keys) and values of the options are described below:

      ‘zticks’list of numbers, optional

        A list of z-axis tick locations.

      ‘bars_spacing’float, default: 0.1

        spacing between bars.

      ‘bars_alpha’float, default: 1.

        transparency of bars, should be in range 0 - 1

      ‘bars_lw’float, default: 0.5

        linewidth of bars’ edges.

      ‘bars_edgecolor’color, default: ‘k’

        The colors of the bars’ edges. Examples: ‘k’, (0.1, 0.2, 0.5) or ‘#0f0f0f80’.

      ‘shade’bool, default: True

        Whether to shade the dark sides of the bars (True) or not (False). The shading is relative to plot’s source of light.

      ‘azim’float, default: -35

        The azimuthal viewing angle.

      ‘elev’float, default: 35

        The elevation viewing angle.

      ‘stick’bool, default: False

        Changes xlim and ylim in such a way that bars next to XZ and YZ planes will stick to those planes. This option has no effect if `ax` is passed as a parameter.

      ‘cbar_pad’float, default: 0.04

        The fraction of the original axes between the colorbar and the new image axes. (i.e. the padding between the 3D figure and the colorbar).

      ‘cbar_to_z’bool, default: False

        Whether to set the color of maximum and minimum z-values to the maximum and minimum colors in the colorbar (True) or not (False).

      ‘threshold’: float, optional

        Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

  Raises:
    ValueError

      Input argument is not valid.

anim_qubism(

  kets,
  theme='light',
  how='pairs',
  grid_iteration=1,
  legend_iteration=0,
  *,
  fig=None,
  ax=None,

)

  Animation of Qubism plot for pure states of many qudits. Works best for spin chains, especially with even number of particles of the same dimension. Allows to see entanglement between first 2k particles and the rest.

  Note

  colorblind_safe does not apply because of its unique colormap

  Parameters:
    kets `Result` or list of `Qobj`

      Pure states for animation.

    theme str {‘light’, ‘dark’}, default: ‘light’

      Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.

    how str {‘pairs’, ‘pairs_skewed’, ‘before_after’}, default: ‘pairs’

      Type of Qubism plotting. Options:

      - ‘pairs’ - typical coordinates,

      - ‘pairs_skewed’ - for ferromagnetic/antriferromagnetic plots,

      - ‘before_after’ - related to Schmidt plot (see also: plot_schmidt).

    grid_iteration int, default: 1

      Helper lines to be drawn on plot. Show tiles for 2*grid_iteration particles vs all others.

    legend_iteration int or ‘grid_iteration’ or ‘all’, default: 0

      Show labels for first `2*legend_iteration` particles. Option ‘grid_iteration’ sets the same number of particles as for grid_iteration. Option ‘all’ makes label for all particles. Typically it should be 0, 1, 2 or perhaps 3.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

  Notes

  See also [1].

  References

  [1]

  J. Rodriguez-Laguna, P. Migdal, M. Ibanez Berganza, M. Lewenstein and G. Sierra, Qubism: self-similar visualization of many-body wavefunctions, New J. Phys. 14 053028, arXiv:1112.3560 (2012), open access.

anim_schmidt(

  kets,
  theme='light',
  splitting=None,
  labels_iteration=(3, 2),
  *,
  fig=None,
  ax=None,

)

  Animation of Schmidt decomposition. Converts a state into a matrix (A_ij -> A_i^j), where rows are first particles and columns - last.

  See also: plot_qubism with how=’before_after’ for a similar plot.

  Note

  colorblind_safe does not apply because of its unique colormap

  Parameters:
    ket `Result` or list of `Qobj`

      Pure states for animation.

    theme str {‘light’, ‘dark’}, default: ‘light’

      Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.

    splitting int, optional

      Plot for a number of first particles versus the rest. If not given, it is (number of particles + 1) // 2.

    labels_iteration int or pair of ints, default: (3, 2)

      Number of particles to be shown as tick labels, for first (vertical) and last (horizontal) particles, respectively.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

anim_sphereplot(V, theta, phi, *, cmap=None, colorbar=True, fig=None, ax=None)

  animation of a matrices of values on a sphere

  Parameters:
    V list of array instances

      Data set to be plotted

    theta float

      Angle with respect to z-axis. Its range is between 0 and pi

    phi float

      Angle in x-y plane. Its range is between 0 and 2*pi

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

anim_spin_distribution(

  Ps,
  THETA,
  PHI,
  projection='2d',
  *,
  cmap=None,
  colorbar=False,
  fig=None,
  ax=None,

)

  Animation of a spin distribution (given as meshgrid data).

  Parameters:
    Ps list of matrices

      Distribution values as a meshgrid matrix.

    THETA matrix

      Meshgrid matrix for the theta coordinate. Its range is between 0 and pi

    PHI matrix

      Meshgrid matrix for the phi coordinate. Its range is between 0 and 2*pi

    projection: str {‘2d’, ‘3d’}, default: ‘2d’

      Specify whether the spin distribution function is to be plotted as a 2D projection where the surface of the unit sphere is mapped on the unit disk (‘2d’) or surface plot (‘3d’).

    cmap a matplotlib cmap instance, optional

      The colormap.

    colorbar bool, default: False

      Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.

    fig a matplotlib figure instance, optional

      The figure canvas on which the plot will be drawn.

    ax a matplotlib axis instance, optional

      The axis context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

anim_wigner(

  rhos,
  xvec=None,
  yvec=None,
  method='clenshaw',
  projection='2d',
  g=np.float64(1.4142135623730951),
  sparse=False,
  parfor=False,
  *,
  cmap=None,
  colorbar=False,
  fig=None,
  ax=None,

)

  Animation of the Wigner function for a density matrix (or ket) that describes an oscillator mode.

  Parameters:
    rhos `Result` or list of `Qobj`

      The density matrix (or ket) of the state to visualize.

    xvec array_like, optional

      x-coordinates at which to calculate the Wigner function.

    yvec array_like, optional

      y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.

    method str {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

      The method used for calculating the wigner function. See the documentation for qutip.wigner for details.

    projection: str {‘2d’, ‘3d’}, default: ‘2d’

      Specify whether the Wigner function is to be plotted as a contour graph (‘2d’) or surface plot (‘3d’).

    g float

      Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2). See the documentation for qutip.wigner for details.

    sparse bool {False, True}

      Flag for sparse format. See the documentation for qutip.wigner for details.

    parfor bool {False, True}

      Flag for parallel calculation. See the documentation for qutip.wigner for details.

    cmap a matplotlib cmap instance, optional

      The colormap.

    colorbar bool, default: False

      Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The axes context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

anim_wigner_sphere(

  wigners,
  reflections=False,
  *,
  cmap=None,
  colorbar=True,
  fig=None,
  ax=None,

)

  Animate a coloured Bloch sphere.

  Parameters:
    wigners list of transformations

      The wigner transformation at steps different theta and phi.

    reflections bool, default: False

      If the reflections of the sphere should be plotted as well.

    cmap a matplotlib colormap instance, optional

      Color map to use when plotting.

    colorbar bool, default: True

      Whether (True) or not (False) a colorbar should be attached.

    fig a matplotlib Figure instance, optional

      The Figure canvas in which the plot will be drawn.

    ax a matplotlib axes instance, optional

      The ax context in which the plot will be drawn.

  Returns:
    fig, ani tuple

      A tuple of the matplotlib figure and the animation instance used to produce the figure.

  Notes

  Special thanks to Russell P Rundle for writing this function.

This module contains utility functions that enhance Matplotlib in one way or another.

complex_phase_cmap()

  Create a cyclic colormap for representing the phase of complex variables

  Returns:
    cmap

      A matplotlib linear segmented colormap.

wigner_cmap(

  W,
  levels=1024,
  shift=0,
  max_color='#09224F',
  mid_color='#FFFFFF',
  min_color='#530017',
  neg_color='#FF97D4',
  invert=False,

)

  A custom colormap that emphasizes negative values by creating a nonlinear colormap.

  Parameters:
    W array

      Wigner function array, or any array.

    levels int, default: 1024

      Number of color levels to create.

    shift float, default: 0

      Shifts the value at which Wigner elements are emphasized. This parameter should typically be negative and small (i.e -1e-5).

    max_color str, default: ‘#09224F’

      String for color corresponding to maximum value of data. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.

    mid_color str, default: ‘#FFFFFF’

      Color corresponding to zero values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.

    min_color str, default: ‘#530017’

      Color corresponding to minimum data values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.

    neg_color str, default: ‘#FF97D4’

      Color that starts highlighting negative values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.

    invert bool, default: False

      Invert the color scheme for negative values so that smaller negative values have darker color.

  Returns:
    Returns a Matplotlib colormap instance for use in plotting.

  Notes

  The ‘shift’ parameter allows you to vary where the colormap begins to highlight negative colors. This is beneficial in cases where there are small negative Wigner elements due to numerical round-off and/or truncation.

## Pseudoprobability Functions

qfunc(

  state: Qobj,
  xvec,
  yvec,
  g: float = np.float64(1.4142135623730951),
  precompute_memory: float = 1024,

)

  Husimi-Q function of a given state vector or density matrix at phase-space points `0.5 * g * (xvec + i*yvec)`.

  Parameters:
    state `Qobj`

      A state vector or density matrix. This cannot have tensor-product structure.

    xvec, yvec array_like

      x- and y-coordinates at which to calculate the Husimi-Q function.

    g float, default: sqrt(2)

      Scaling factor for `a = 0.5 * g * (x + iy)`. The value of g is related to the value of \(\hbar\) in the commutation relation \([x,\,y] = i\hbar\) via \(\hbar=2/g^2\), so the default corresponds to \(\hbar=1\).

    precompute_memory real, default: 1024

      Size in MB that may be used during calculations as working space when dealing with density-matrix inputs. This is ignored for state-vector inputs. The bound is not quite exact due to other, order-of-magnitude smaller, intermediaries being necessary, but is a good approximation. If you want to use the same iterative algorithm for density matrices that is used for single kets, set `precompute_memory=None`.

  Returns:
    ndarray

      Values representing the Husimi-Q function calculated over the specified range `[xvec, yvec]`.

  See also

  `QFunc`

    a class-based version, more efficient if you want to calculate the Husimi-Q function for several states over the same coordinates.

spin_q_function(rho, theta, phi)

  The Husimi Q function for spins is defined as `Q(theta, phi) = SCS.dag() * rho * SCS` for the spin coherent state `SCS = spin_coherent( j, theta, phi)` where j is the spin length. The implementation here is more efficient as it doesn’t generate all of the SCS at theta and phi (see references).

  The spin Q function is normal when integrated over the surface of the sphere

  \[\frac{4 \pi}{2j + 1}\int_\phi \int_\theta Q(\theta, \phi) \sin(\theta) d\theta d\phi = 1\]
  Parameters:
    state qobj

      A state vector or density matrix for a spin-j quantum system.

    theta array_like

      Polar (colatitude) angle at which to calculate the Husimi-Q function.

    phi array_like

      Azimuthal angle at which to calculate the Husimi-Q function.

  Returns:
    Q, THETA, PHI 2d-array

      Values representing the spin Husimi Q function at the values specified by THETA and PHI.

  References

  [1] Lee Loh, Y., & Kim, M. (2015). American J. of Phys., 83(1), 30–35. https://doi.org/10.1119/1.4898595

spin_wigner(rho, theta, phi)

  Wigner function for a spin-j system.

  The spin W function is normal when integrated over the surface of the sphere

  \[\sqrt{\frac{4 \pi}{2j + 1}}\int_\phi \int_\theta W(\theta,\phi) \sin(\theta) d\theta d\phi = 1\]
  Parameters:
    state qobj

      A state vector or density matrix for a spin-j quantum system.

    theta array_like

      Polar (colatitude) angle at which to calculate the W function.

    phi array_like

      Azimuthal angle at which to calculate the W function.

  Returns:
    W, THETA, PHI 2d-array

      Values representing the spin Wigner function at the values specified by THETA and PHI.

  References

  [1] Agarwal, G. S. (1981). Phys. Rev. A, 24(6), 2889–2896. https://doi.org/10.1103/PhysRevA.24.2889

  [2] Dowling, J. P., Agarwal, G. S., & Schleich, W. P. (1994). Phys. Rev. A, 49(5), 4101–4109. https://doi.org/10.1103/PhysRevA.49.4101

  [3] Conversion between Wigner 3-j symbol and Clebsch-Gordan coefficients taken from Wikipedia (https://en.wikipedia.org/wiki/3-j_symbol)

wigner(

  psi,
  xvec,
  yvec=None,
  method='clenshaw',
  g=np.float64(1.4142135623730951),
  sparse=False,
  parfor=False,

)

  Wigner function for a state vector or density matrix at points xvec + i * yvec.

  Parameters:
    state qobj

      A state vector or density matrix.

    xvec array_like

      x-coordinates at which to calculate the Wigner function.

    yvec array_like

      y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.

    g float, default: sqrt(2)

      Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2). The value of g is related to the value of hbar in the commutation relation [x, y] = i * hbar via hbar=2/g^2 giving the default value hbar=1.

    method string {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

      Select method ‘clenshaw’ ‘iterative’, ‘laguerre’, or ‘fft’, where ‘clenshaw’ and ‘iterative’ use an iterative method to evaluate the Wigner functions for density matrices \(|m><n|\), while ‘laguerre’ uses the Laguerre polynomials in scipy for the same task. The ‘fft’ method evaluates the Fourier transform of the density matrix. The ‘iterative’ method is default, and in general recommended, but the ‘laguerre’ method is more efficient for very sparse density matrices (e.g., superpositions of Fock states in a large Hilbert space). The ‘clenshaw’ method is the preferred method for dealing with density matrices that have a large number of excitations (>~50). ‘clenshaw’ is a fast and numerically stable method.

    sparse bool, optional

      Tells the default solver whether or not to keep the input density matrix in sparse format. As the dimensions of the density matrix grow, setthing this flag can result in increased performance.

    parfor bool, optional

      Flag for calculating the Laguerre polynomial based Wigner function method=’laguerre’ in parallel using the parfor function.

  Returns:
    W array

      Values representing the Wigner function calculated over the specified range [xvec,yvec].

    yvex array

      FFT ONLY. Returns the y-coordinate values calculated via the Fourier transform.

  Notes

  The ‘fft’ method accepts only an xvec input for the x-coordinate. The y-coordinates are calculated internally.

  References

  Ulf Leonhardt, Measuring the Quantum State of Light, (Cambridge University Press, 1997)

class QFunc(

  xvec,
  yvec,
  g: float = np.float64(1.4142135623730951),
  memory: float = 1024,

)

  Class-based method of calculating the Husimi-Q function of many different quantum states at fixed phase-space points `0.5*g* (xvec + i*yvec)`. This class has slightly higher first-usage costs than `qfunc`, but subsequent operations will be several times faster. However, it can require quite a lot of memory. Call the created object as a function to retrieve the Husimi-Q function.

  Parameters:
    xvec, yvec array_like

      x- and y-coordinates at which to calculate the Husimi-Q function.

    g float, default: sqrt(2)

      Scaling factor for `a = 0.5 * g * (x + iy)`. The value of g is related to the value of hbar in the commutation relation \([x,\,y] = i\hbar\) via \(\hbar=2/g^2\), so the default corresponds to \(\hbar=1\).

    memory real, default: 1024

      Size in MB that may be used internally as workspace. This class will raise `MemoryError` if subsequently passed a state of sufficiently large dimension that this bound would be exceeded. In those cases, use `qfunc` with `precompute_memory=None` instead to force using the slower, more memory-efficient algorithm.

  See also

  `qfunc`

    A single function version, which will involve computing several quantities multiple times in order to use less memory.

  Examples

  Initialise the class for a square set of coordinates, with some states we want to investigate.

      >>> xvec = np.linspace(-2, 2, 101)
      >>> states = [qutip.rand_dm(10) for _ in [None]*10]
      >>> qfunc = qutip.QFunc(xvec, xvec)

  Now we can calculate the Husimi-Q function over each of the states more efficiently with:

      >>> husimiq = np.array([qfunc(state) for state in states])

## Quantum Process Tomography

qpt(U, op_basis_list)

  Calculate the quantum process tomography chi matrix for a given (possibly nonunitary) transformation matrix U, which transforms a density matrix in vector form according to:

  > vec(rho) = U * vec(rho0)

  > or

  > rho = unstack_columns(U * stack_columns(rho0))

  U can be calculated for an open quantum system using the QuTiP propagator function.

  Parameters:
    U Qobj

      Transformation operator. Can be calculated using QuTiP propagator function.

    op_basis_list list

      A list of Qobj’s representing the basis states.

  Returns:
    chi array

      QPT chi matrix

qpt_plot(chi, lbls_list, title=None, fig=None, axes=None)

  Visualize the quantum process tomography chi matrix. Plot the real and imaginary parts separately.

  Parameters:
    chi array

      Input QPT chi matrix.

    lbls_list list

      List of labels for QPT plot axes.

    title str, optional

      Plot title.

    fig figure instance, optional

      User defined figure instance used for generating QPT plot.

    axes list of figure axis instance, optional

      User defined figure axis instance (list of two axes) used for generating QPT plot.

  Returns:
    fig, ax tuple

      A tuple of the matplotlib figure and axes instances used to produce the figure.

qpt_plot_combined(

  chi,
  lbls_list,
  title=None,
  fig=None,
  ax=None,
  figsize=(8, 6),
  threshold=None,

)

  Visualize the quantum process tomography chi matrix. Plot bars with height and color corresponding to the absolute value and phase, respectively.

  Parameters:
    chi array

      Input QPT chi matrix.

    lbls_list list

      List of labels for QPT plot axes.

    title str, optional

      Plot title.

    fig figure instance, optional

      User defined figure instance used for generating QPT plot.

    figsize(int, int), default: (8, 6)

      Size of the figure when the `fig` is not provided.

    ax figure axis instance, optional

      User defined figure axis instance used for generating QPT plot (alternative to the fig argument).

    threshold: float, optional

      Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map.

  Returns:
    fig, ax tuple

      A tuple of the matplotlib figure and axes instances used to produce the figure.