Visualization and animation
Bloch sphere
- class Bloch(fig=None, axes=None, view=None, figsize=None, background=False)[source]
Class for plotting data on the Bloch sphere. Valid data can be either points, vectors, or Qobj objects.
- Attributes:
- axesmatplotlib.axes.Axes
User supplied Matplotlib axes for Bloch sphere animation.
- figmatplotlib.figure.Figure
User supplied Matplotlib Figure instance for plotting Bloch sphere.
- font_colorstr, default ‘black’
Color of font used for Bloch sphere labels.
- font_sizeint, default 20
Size of font used for Bloch sphere labels.
- frame_alphafloat, default 0.1
Sets transparency of Bloch sphere frame.
- frame_colorstr, default ‘gray’
Color of sphere wireframe.
- frame_widthint, default 1
Width of wireframe.
- point_colorlist, 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_markerlist, default [“o”, “s”, “d”, “^”]
List of point marker shapes to cycle through.
- point_sizelist, default [25, 32, 35, 45]
List of point marker sizes. Note, not all point markers look the same size when plotted!
- sphere_alphafloat, default 0.2
Transparency of Bloch sphere itself.
- sphere_colorstr, default ‘#FFDDDD’
Color of Bloch sphere.
- figsizelist, 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_colorlist, [“g”, “#CC6600”, “b”, “r”]
List of vector colors to cycle through.
- vector_widthint, default 5
Width of displayed vectors.
- vector_stylestr, default ‘-|>’
Vector arrowhead style (from matplotlib’s arrow style).
- vector_mutationint, default 20
Width of vectors arrowhead.
- viewlist, default [-60, 30]
Azimuthal and Elevation viewing angles.
- xlabellist, default [“$x$”, “”]
List of strings corresponding to +x and -x axes labels, respectively.
- xlposlist, default [1.1, -1.1]
Positions of +x and -x labels respectively.
- ylabellist, default [“$y$”, “”]
List of strings corresponding to +y and -y axes labels, respectively.
- ylposlist, default [1.2, -1.2]
Positions of +y and -y labels respectively.
- zlabellist, default [‘$\left|0\right>$’, ‘$\left|1\right>$’]
List of strings corresponding to +z and -z axes labels, respectively.
- zlposlist, default [1.2, -1.2]
Positions of +z and -z labels respectively.
- add_annotation(state_or_vector, text, **kwargs)[source]
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.
- textstr
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.
- state_or_vector
- add_arc(start, end, fmt='b', steps=None, **kwargs)[source]
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.
- fmtstr, default: “b”
A matplotlib format string for rendering the arc.
- stepsint, 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.
- **kwargsdict
Additional parameters to pass to the matplotlib .plot function when rendering this arc.
- start
- add_line(start, end, fmt='k', **kwargs)[source]
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.
- fmtstr, default: “k”
A matplotlib format string for rendering the line.
- **kwargsdict
Additional parameters to pass to the matplotlib .plot function when rendering this line.
- start
- add_points(
- points,
- meth: Literal['s', 'm', 'l'] = 's',
- colors=None,
- alpha=1.0,
Add a list of data points to bloch sphere.
- Parameters:
- pointsarray_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.
- colorsarray_like
Optional array with colors for the points. A single color for meth ‘s’, and list of colors for meth ‘m’
- alphafloat, 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 to0.75
and there was no way to alter it. When thealpha
parameter was added in QuTiP 4.7, the default becamealpha=1.0
for values ofmeth
.
- 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.
- colorsarray_like
Optional array with colors for the states.
- alphafloat, default=1.
Transparency value for the vectors. Values between 0 and 1.
- state
- add_vectors(vectors, colors=None, alpha=1.0)[source]
Add a list of vectors to Bloch sphere.
- Parameters:
- vectorsarray_like
Array with vectors of unit length or smaller.
- colorsarray_like
Optional array with colors for the vectors.
- alphafloat, default=1.
Transparency value for the vectors. Values between 0 and 1.
- save(name=None, format='png', dirc=None, dpin=None)[source]
Saves Bloch sphere to file of type
format
in directorydirc
.- Parameters:
- namestr
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.
- formatstr
Format of output image.
- dircstr
Directory for output images. Defaults to current working directory.
- dpinint
Resolution in dots per inch.
- Returns:
- File containing plot of Bloch sphere.
- set_label_convention(convention)[source]
Set x, y and z labels according to one of conventions.
- Parameters:
- conventionstring
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()[source]
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 callb.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:
- rhoqobj
Input density matrix or superoperator.
Note
Hinton plots of superoperators are currently only supported for qubits.
- x_basislist of strings, optional
list of x ticklabels to represent x basis of the input.
- y_basislist of strings, optional
list of y ticklabels to represent y basis of the input.
- color_stylestr, {“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_topbool, default: True
If True, x ticklabels will be placed on top, otherwise they will appear below the plot.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The ax context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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:
- MMatrix of Qobj
The matrix to visualize
- x_basislist of strings, optional
list of x ticklabels
- y_basislist of strings, optional
list of y ticklabels
- limitslist/array with two float numbers, optional
The z-axis limits [min, max]
- bar_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”
If set to
"real"
(default), each bar is plotted as the real part of the corresponding matrix elementIf set to
"img"
, each bar is plotted as the imaginary part of the corresponding matrix elementIf set to
"abs"
, each bar is plotted as the absolute value of the corresponding matrix elementIf set to
"phase"
(default), each bar is plotted as the angle of the corresponding matrix element
- color_limitslist/array with two float numbers, optional
The limits of colorbar [min, max]
- color_stylestr, {“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.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
show colorbar
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- optionsdict, 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, outputtuple
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_listList of Qobj
A list of Hamiltonians.
- h_lablesList of string, optional
A list of xticklabels for each Hamiltonian
- energy_levelsList of string, optional
A list of yticklabels to the left of energy levels of the initial Hamiltonian.
- Nint, default: 0
The number of energy levels to plot
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- Returns:
- fig, axtuple
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)[source]
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.
- ylabelslist of strings, optional
The y-axis labels. List should be of the same length as results.
- figa 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.
- results(list of)
- Returns:
- fig, axestuple
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_numberslist of strings, optional
list of x ticklabels to represent fock numbers
- colorcolor or list of colors, default: “green”
The colors of the bar faces.
- unit_y_rangebool, default: True
Set y-axis limits [0, 1] or not
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- rho
- Returns:
- fig, outputtuple
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:
- ketQobj
Pure state for plotting.
- themestr {‘light’, ‘dark’}, default: ‘light’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
- howstr {‘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_iterationint, default: 1
Helper lines to be drawn on plot. Show tiles for 2*grid_iteration particles vs all others.
- legend_iterationint 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.- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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:
- ketQobj
Pure state for plotting.
- themestr {‘light’, ‘dark’}, default: ‘light’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
- splittingint, optional
Plot for a number of first particles versus the rest. If not given, it is (number of particles + 1) // 2.
- labels_iterationint or pair of ints, default: (3, 2)
Number of particles to be shown as tick labels, for first (vertical) and last (horizontal) particles, respectively.
- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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:
- Pmatrix
Distribution values as a meshgrid matrix.
- THETAmatrix
Meshgrid matrix for the theta coordinate. Its range is between 0 and pi
- PHImatrix
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’).
- cmapa matplotlib cmap instance, optional
The colormap.
- colorbarbool, default: False
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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=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.
- xvecarray_like, optional
x-coordinates at which to calculate the Wigner function.
- yvecarray_like, optional
y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.
- methodstr {‘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’).
- gfloat
Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2). See the documentation for qutip.wigner for details.
- sparsebool {False, True}
Flag for sparse format. See the documentation for qutip.wigner for details.
- parforbool {False, True}
Flag for parallel calculation. See the documentation for qutip.wigner for details.
- cmapa matplotlib cmap instance, optional
The colormap.
- colorbarbool, default: False
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- rho
- Returns:
- fig, outputtuple
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:
- wignera wigner transformation
The wigner transformation at steps different theta and phi.
- reflectionsbool, default: False
If the reflections of the sphere should be plotted as well.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The ax context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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)[source]
Plots a matrix of values on a sphere
- Parameters:
- valuesarray
Data set to be plotted
- thetafloat
Angle with respect to z-axis. Its range is between 0 and pi
- phifloat
Angle in x-y plane. Its range is between 0 and 2*pi
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- Returns:
- fig, outputtuple
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 ofQobj
The density matrix (or ket) of the state to visualize.
- fock_numberslist of strings, optional
list of x ticklabels to represent fock numbers
- colorcolor or list of colors, default: “green”
The colors of the bar faces.
- unit_y_rangebool, default: True
Set y-axis limits [0, 1] or not
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- rhos
- Returns:
- fig, anituple
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 ofQobj
Input density matrix or superoperator.
Note
Hinton plots of superoperators are currently only supported for qubits.
- x_basislist of strings, optional
list of x ticklabels to represent x basis of the input.
- y_basislist of strings, optional
list of y ticklabels to represent y basis of the input.
- color_stylestr, {“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_topbool, default: True
If True, x ticklabels will be placed on top, otherwise they will appear below the plot.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The ax context in which the plot will be drawn.
- rhos
- Returns:
- fig, anituple
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:
- Mslist of matrices or
Result
The matrix to visualize
- x_basislist of strings, optional
list of x ticklabels
- y_basislist of strings, optional
list of y ticklabels
- limitslist/array with two float numbers, optional
The z-axis limits [min, max]
- bar_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”
If set to
"real"
(default), each bar is plotted as the real part of the corresponding matrix elementIf set to
"img"
, each bar is plotted as the imaginary part of the corresponding matrix elementIf set to
"abs"
, each bar is plotted as the absolute value of the corresponding matrix elementIf set to
"phase"
(default), each bar is plotted as the angle of the corresponding matrix element
- color_limitslist/array with two float numbers, optional
The limits of colorbar [min, max]
- color_stylestr, {“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.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
show colorbar
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- optionsdict, 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.
- Mslist of matrices or
- Returns:
- fig, anituple
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 ofQobj
Pure states for animation.
- themestr {‘light’, ‘dark’}, default: ‘light’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
- howstr {‘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_iterationint, default: 1
Helper lines to be drawn on plot. Show tiles for 2*grid_iteration particles vs all others.
- legend_iterationint 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.- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- kets
- Returns:
- fig, anituple
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 ofQobj
Pure states for animation.
- themestr {‘light’, ‘dark’}, default: ‘light’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
- splittingint, optional
Plot for a number of first particles versus the rest. If not given, it is (number of particles + 1) // 2.
- labels_iterationint or pair of ints, default: (3, 2)
Number of particles to be shown as tick labels, for first (vertical) and last (horizontal) particles, respectively.
- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- ket
- Returns:
- fig, anituple
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)[source]
animation of a matrices of values on a sphere
- Parameters:
- Vlist of array instances
Data set to be plotted
- thetafloat
Angle with respect to z-axis. Its range is between 0 and pi
- phifloat
Angle in x-y plane. Its range is between 0 and 2*pi
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- Returns:
- fig, anituple
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:
- Pslist of matrices
Distribution values as a meshgrid matrix.
- THETAmatrix
Meshgrid matrix for the theta coordinate. Its range is between 0 and pi
- PHImatrix
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’).
- cmapa matplotlib cmap instance, optional
The colormap.
- colorbarbool, default: False
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
- figa matplotlib figure instance, optional
The figure canvas on which the plot will be drawn.
- axa matplotlib axis instance, optional
The axis context in which the plot will be drawn.
- Returns:
- fig, anituple
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=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 ofQobj
The density matrix (or ket) of the state to visualize.
- xvecarray_like, optional
x-coordinates at which to calculate the Wigner function.
- yvecarray_like, optional
y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.
- methodstr {‘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’).
- gfloat
Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2). See the documentation for qutip.wigner for details.
- sparsebool {False, True}
Flag for sparse format. See the documentation for qutip.wigner for details.
- parforbool {False, True}
Flag for parallel calculation. See the documentation for qutip.wigner for details.
- cmapa matplotlib cmap instance, optional
The colormap.
- colorbarbool, default: False
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The axes context in which the plot will be drawn.
- rhos
- Returns:
- fig, anituple
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:
- wignerslist of transformations
The wigner transformation at steps different theta and phi.
- reflectionsbool, default: False
If the reflections of the sphere should be plotted as well.
- cmapa matplotlib colormap instance, optional
Color map to use when plotting.
- colorbarbool, default: True
Whether (True) or not (False) a colorbar should be attached.
- figa matplotlib Figure instance, optional
The Figure canvas in which the plot will be drawn.
- axa matplotlib axes instance, optional
The ax context in which the plot will be drawn.
- Returns:
- fig, anituple
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()[source]
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:
- Warray
Wigner function array, or any array.
- levelsint, default: 1024
Number of color levels to create.
- shiftfloat, default: 0
Shifts the value at which Wigner elements are emphasized. This parameter should typically be negative and small (i.e -1e-5).
- max_colorstr, default: ‘#09224F’
String for color corresponding to maximum value of data. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
- mid_colorstr, default: ‘#FFFFFF’
Color corresponding to zero values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
- min_colorstr, default: ‘#530017’
Color corresponding to minimum data values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
- neg_colorstr, default: ‘#FF97D4’
Color that starts highlighting negative values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
- invertbool, 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 = 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, yvecarray_like
x- and y-coordinates at which to calculate the Husimi-Q function.
- gfloat, 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_memoryreal, 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
.
- state
- 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)[source]
The Husimi Q function for spins is defined as
Q(theta, phi) = SCS.dag() * rho * SCS
for the spin coherent stateSCS = 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:
- stateqobj
A state vector or density matrix for a spin-j quantum system.
- thetaarray_like
Polar (colatitude) angle at which to calculate the Husimi-Q function.
- phiarray_like
Azimuthal angle at which to calculate the Husimi-Q function.
- Returns:
- Q, THETA, PHI2d-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)[source]
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:
- stateqobj
A state vector or density matrix for a spin-j quantum system.
- thetaarray_like
Polar (colatitude) angle at which to calculate the W function.
- phiarray_like
Azimuthal angle at which to calculate the W function.
- Returns:
- W, THETA, PHI2d-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=1.4142135623730951,
- sparse=False,
- parfor=False,
Wigner function for a state vector or density matrix at points xvec + i * yvec.
- Parameters:
- stateqobj
A state vector or density matrix.
- xvecarray_like
x-coordinates at which to calculate the Wigner function.
- yvecarray_like
y-coordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.
- gfloat, 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.
- methodstring {‘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.
- sparsebool, 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.
- parforbool, optional
Flag for calculating the Laguerre polynomial based Wigner function method=’laguerre’ in parallel using the parfor function.
- Returns:
- Warray
Values representing the Wigner function calculated over the specified range [xvec,yvec].
- yvexarray
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 = 1.4142135623730951, memory: float = 1024)[source]
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 thanqfunc
, 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, yvecarray_like
x- and y-coordinates at which to calculate the Husimi-Q function.
- gfloat, 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\).- memoryreal, 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, useqfunc
withprecompute_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)[source]
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:
- UQobj
Transformation operator. Can be calculated using QuTiP propagator function.
- op_basis_listlist
A list of Qobj’s representing the basis states.
- Returns:
- chiarray
QPT chi matrix
- qpt_plot(chi, lbls_list, title=None, fig=None, axes=None)[source]
Visualize the quantum process tomography chi matrix. Plot the real and imaginary parts separately.
- Parameters:
- chiarray
Input QPT chi matrix.
- lbls_listlist
List of labels for QPT plot axes.
- titlestr, optional
Plot title.
- figfigure instance, optional
User defined figure instance used for generating QPT plot.
- axeslist of figure axis instance, optional
User defined figure axis instance (list of two axes) used for generating QPT plot.
- Returns:
- fig, axtuple
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:
- chiarray
Input QPT chi matrix.
- lbls_listlist
List of labels for QPT plot axes.
- titlestr, optional
Plot title.
- figfigure 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.- axfigure 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, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.