Functions

Manipulation and Creation of States and Operators

Quantum States

basis(N, n=0, offset=0)

Generates the vector representation of a Fock state.

Parameters:

N : int

Number of Fock states in Hilbert space.

n : int

Integer corresponding to desired number state, defaults to 0 if omitted.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the state.

Returns:

state : qobj

Qobj representing the requested number state |n>.

Notes

A subtle incompatibility with the quantum optics toolbox: In QuTiP:

basis(N, 0) = ground state

but in the qotoolbox:

basis(N, 1) = ground state

Examples

>>> basis(5,2)
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 0.+0.j]
 [ 0.+0.j]
 [ 1.+0.j]
 [ 0.+0.j]
 [ 0.+0.j]]
coherent(N, alpha, offset=0, method='operator')

Generates a coherent state with eigenvalue alpha.

Constructed using displacement operator on vacuum state.

Parameters:

N : int

Number of Fock states in Hilbert space.

alpha : float/complex

Eigenvalue of coherent state.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the state. Using a non-zero offset will make the default method ‘analytic’.

method : string {‘operator’, ‘analytic’}

Method for generating coherent state.

Returns:

state : qobj

Qobj quantum object for coherent state

Notes

Select method ‘operator’ (default) or ‘analytic’. With the ‘operator’ method, the coherent state is generated by displacing the vacuum state using the displacement operator defined in the truncated Hilbert space of size ‘N’. This method guarantees that the resulting state is normalized. With ‘analytic’ method the coherent state is generated using the analytical formula for the coherent state coefficients in the Fock basis. This method does not guarantee that the state is normalized if truncated to a small number of Fock states, but would in that case give more accurate coefficients.

Examples

>>> coherent(5,0.25j)
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[  9.69233235e-01+0.j        ]
 [  0.00000000e+00+0.24230831j]
 [ -4.28344935e-02+0.j        ]
 [  0.00000000e+00-0.00618204j]
 [  7.80904967e-04+0.j        ]]
coherent_dm(N, alpha, offset=0, method='operator')

Density matrix representation of a coherent state.

Constructed via outer product of qutip.states.coherent

Parameters:

N : int

Number of Fock states in Hilbert space.

alpha : float/complex

Eigenvalue for coherent state.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the state.

method : string {‘operator’, ‘analytic’}

Method for generating coherent density matrix.

Returns:

dm : qobj

Density matrix representation of coherent state.

Notes

Select method ‘operator’ (default) or ‘analytic’. With the ‘operator’ method, the coherent density matrix is generated by displacing the vacuum state using the displacement operator defined in the truncated Hilbert space of size ‘N’. This method guarantees that the resulting density matrix is normalized. With ‘analytic’ method the coherent density matrix is generated using the analytical formula for the coherent state coefficients in the Fock basis. This method does not guarantee that the state is normalized if truncated to a small number of Fock states, but would in that case give more accurate coefficients.

Examples

>>> coherent_dm(3,0.25j)
Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.93941695+0.j          0.00000000-0.23480733j -0.04216943+0.j        ]
 [ 0.00000000+0.23480733j  0.05869011+0.j          0.00000000-0.01054025j]
 [-0.04216943+0.j          0.00000000+0.01054025j  0.00189294+0.j        ]]
fock(N, n=0, offset=0)

Bosonic Fock (number) state.

Same as qutip.states.basis.

Parameters:

N : int

Number of states in the Hilbert space.

n : int

int for desired number state, defaults to 0 if omitted.

Returns:

Requested number state :math:`left|nright>`. :

Examples

>>> fock(4,3)
Quantum object: dims = [[4], [1]], shape = [4, 1], type = ket
Qobj data =
[[ 0.+0.j]
 [ 0.+0.j]
 [ 0.+0.j]
 [ 1.+0.j]]
fock_dm(N, n=0, offset=0)

Density matrix representation of a Fock state

Constructed via outer product of qutip.states.fock.

Parameters:

N : int

Number of Fock states in Hilbert space.

n : int

int for desired number state, defaults to 0 if omitted.

Returns:

dm : qobj

Density matrix representation of Fock state.

Examples

>>> fock_dm(3,1)
Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  1.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]]
ket2dm(Q)

Takes input ket or bra vector and returns density matrix formed by outer product.

Parameters:

Q : qobj

Ket or bra type quantum object.

Returns:

dm : qobj

Density matrix formed by outer product of Q.

Examples

>>> x=basis(3,2)
>>> ket2dm(x)
Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  1.+0.j]]
qutrit_basis()

Basis states for a three level system (qutrit)

Returns:

qstates : array

Array of qutrit basis vectors

thermal_dm(N, n, method='operator')

Density matrix for a thermal state of n particles

Parameters:

N : int

Number of basis states in Hilbert space.

n : float

Expectation value for number of particles in thermal state.

method : string {‘operator’, ‘analytic’}

string that sets the method used to generate the thermal state probabilities

Returns:

dm : qobj

Thermal state density matrix.

Notes

The ‘operator’ method (default) generates the thermal state using the truncated number operator num(N). This is the method that should be used in computations. The ‘analytic’ method uses the analytic coefficients derived in an infinite Hilbert space. The analytic form is not necessarily normalized, if truncated too aggressively.

Examples

>>> thermal_dm(5, 1)
Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isHerm = True
Qobj data =
[[ 0.51612903  0.          0.          0.          0.        ]
 [ 0.          0.25806452  0.          0.          0.        ]
 [ 0.          0.          0.12903226  0.          0.        ]
 [ 0.          0.          0.          0.06451613  0.        ]
 [ 0.          0.          0.          0.          0.03225806]]
>>> thermal_dm(5, 1, 'analytic')
Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isHerm = True
Qobj data =
[[ 0.5      0.       0.       0.       0.     ]
 [ 0.       0.25     0.       0.       0.     ]
 [ 0.       0.       0.125    0.       0.     ]
 [ 0.       0.       0.       0.0625   0.     ]
 [ 0.       0.       0.       0.       0.03125]]
state_number_enumerate(dims, state=None, idx=0)

An iterator that enumerate all the state number arrays (quantum numbers on the form [n1, n2, n3, ...]) for a system with dimensions given by dims.

Example:

>>> for state in state_number_enumerate([2,2]):
>>>     print state
[ 0.  0.]
[ 0.  1.]
[ 1.  0.]
[ 1.  1.]
Parameters:

dims : list or array

The quantum state dimensions array, as it would appear in a Qobj.

state : list

Current state in the iteration. Used internally.

idx : integer

Current index in the iteration. Used internally.

Returns:

state_number : list

Successive state number arrays that can be used in loops and other iterations, using standard state enumeration by definition.

state_number_index(dims, state)

Return the index of a quantum state corresponding to state, given a system with dimensions given by dims.

Example:

>>> state_number_index([2, 2, 2], [1, 1, 0])
6.0
Parameters:

dims : list or array

The quantum state dimensions array, as it would appear in a Qobj.

state : list

State number array.

Returns:

idx : list

The index of the state given by state in standard enumeration ordering.

state_index_number(dims, index)

Return a quantum number representation given a state index, for a system of composite structure defined by dims.

Example:

>>> state_index_number([2, 2, 2], 6)
[1, 1, 0]
Parameters:

dims : list or array

The quantum state dimensions array, as it would appear in a Qobj.

index : integer

The index of the state in standard enumeration ordering.

Returns:

state : list

The state number array corresponding to index index in standard enumeration ordering.

state_number_qobj(dims, state)

Return a Qobj representation of a quantum state specified by the state array state.

Example:

>>> state_number_qobj([2, 2, 2], [1, 0, 1])
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
Qobj data =
[[ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 1.]
 [ 0.]
 [ 0.]]
Parameters:

dims : list or array

The quantum state dimensions array, as it would appear in a Qobj.

state : list

State number array.

Returns:

state : qutip.Qobj.qobj

The state as a qutip.Qobj.qobj instance.

phase_basis(N, m, phi0=0)

Basis vector for the mth phase of the Pegg-Barnett phase operator.

Parameters:

N : int

Number of basis vectors in Hilbert space.

m : int

Integer corresponding to the mth discrete phase phi_m=phi0+2*pi*m/N

phi0 : float (default=0)

Reference phase angle.

Returns:

state : qobj

Ket vector for mth Pegg-Barnett phase operator basis state.

Notes

The Pegg-Barnett basis states form a complete set over the truncated Hilbert space.

Quantum Operators

create(N, offset=0)

Creation (raising) operator.

Parameters:

N : int

Dimension of Hilbert space.

Returns:

oper : qobj

Qobj for raising operator.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the operator.

Examples

>>> create(4)
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
 [ 1.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
 [ 0.00000000+0.j  1.41421356+0.j  0.00000000+0.j  0.00000000+0.j]
 [ 0.00000000+0.j  0.00000000+0.j  1.73205081+0.j  0.00000000+0.j]]
destroy(N, offset=0)

Destruction (lowering) operator.

Parameters:

N : int

Dimension of Hilbert space.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the operator.

Returns:

oper : qobj

Qobj for lowering operator.

Examples

>>> destroy(4)
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 0.00000000+0.j  1.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
 [ 0.00000000+0.j  0.00000000+0.j  1.41421356+0.j  0.00000000+0.j]
 [ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  1.73205081+0.j]
 [ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]]
displace(N, alpha, offset=0)

Single-mode displacement operator.

Parameters:

N : int

Dimension of Hilbert space.

alpha : float/complex

Displacement amplitude.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the operator.

Returns:

oper : qobj

Displacement operator.

Examples

>>> displace(4,0.25)
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 0.96923323+0.j -0.24230859+0.j  0.04282883+0.j -0.00626025+0.j]
 [ 0.24230859+0.j  0.90866411+0.j -0.33183303+0.j  0.07418172+0.j]
 [ 0.04282883+0.j  0.33183303+0.j  0.84809499+0.j -0.41083747+0.j]
 [ 0.00626025+0.j  0.07418172+0.j  0.41083747+0.j  0.90866411+0.j]]
jmat(j, *args)

Higher-order spin operators:

Parameters:

j : float

Spin of operator

args : str

Which operator to return ‘x’,’y’,’z’,’+’,’-‘. If no args given, then output is [‘x’,’y’,’z’]

Returns:

jmat : qobj/list

qobj for requested spin operator(s).

Notes

If no ‘args’ input, then returns array of [‘x’,’y’,’z’] operators.

Examples

>>> jmat(1)
[ Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.          0.70710678  0.        ]
 [ 0.70710678  0.          0.70710678]
 [ 0.          0.70710678  0.        ]]
 Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j          0.+0.70710678j  0.+0.j        ]
 [ 0.-0.70710678j  0.+0.j          0.+0.70710678j]
 [ 0.+0.j          0.-0.70710678j  0.+0.j        ]]
 Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 1.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0. -1.]]]
num(N, offset=0)

Quantum object for number operator.

Parameters:

N : int

The dimension of the Hilbert space.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the operator.

Returns:

oper: qobj :

Qobj for number operator.

Examples

>>> num(4)
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[0 0 0 0]
 [0 1 0 0]
 [0 0 2 0]
 [0 0 0 3]]
qeye(N)

Identity operator

Parameters:

N : int

Dimension of Hilbert space.

Returns:

oper : qobj

Identity operator Qobj.

Examples

>>> qeye(3)
Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
identity(N)

Identity operator. Alternative name to qeye.

Parameters:

N : int

Dimension of Hilbert space.

Returns:

oper : qobj

Identity operator Qobj.

qutrit_ops()

Operators for a three level system (qutrit).

Returns:

opers: array :

array of qutrit operators.

sigmam()

Annihilation operator for Pauli spins.

Examples

>>> sigmam()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 0.  0.]
 [ 1.  0.]]
sigmap()

Creation operator for Pauli spins.

Examples

>>> sigmam()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 0.  1.]
 [ 0.  0.]]
sigmax()

Pauli spin 1/2 sigma-x operator

Examples

>>> sigmax()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 0.  1.]
 [ 1.  0.]]
sigmay()

Pauli spin 1/2 sigma-y operator.

Examples

>>> sigmay()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j  0.-1.j]
 [ 0.+1.j  0.+0.j]]
sigmaz()

Pauli spin 1/2 sigma-z operator.

Examples

>>> sigmaz()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = True
Qobj data =
[[ 1.  0.]
 [ 0. -1.]]
squeeze(N, sp, offset=0)

Single-mode Squeezing operator.

Parameters:

N : int

Dimension of hilbert space.

sp : float/complex

Squeezing parameter.

offset : int (default 0)

The lowest number state that is included in the finite number state representation of the operator.

Returns:

oper : qutip.qobj.Qobj

Squeezing operator.

Examples

>>> squeeze(4,0.25)
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 0.98441565+0.j  0.00000000+0.j  0.17585742+0.j  0.00000000+0.j]
 [ 0.00000000+0.j  0.95349007+0.j  0.00000000+0.j  0.30142443+0.j]
 [-0.17585742+0.j  0.00000000+0.j  0.98441565+0.j  0.00000000+0.j]
 [ 0.00000000+0.j -0.30142443+0.j  0.00000000+0.j  0.95349007+0.j]]
squeezing(a1, a2, z)

Generalized squeezing operator.

\[S(z) = \exp\left(\frac{1}{2}\left(z^*a_1a_2 - za_1^\dagger a_2^\dagger\right)\right)\]
Parameters:

a1 : qutip.qobj.Qobj

Operator 1.

a2 : qutip.qobj.Qobj

Operator 2.

z : float/complex

Squeezing parameter.

Returns:

oper : qutip.qobj.Qobj

Squeezing operator.

phase(N, phi0=0)

Single-mode Pegg-Barnett phase operator.

Parameters:

N : int

Number of basis states in Hilbert space.

phi0 : float

Reference phase.

Returns:

oper : qobj

Phase operator with respect to reference phase.

Notes

The Pegg-Barnett phase operator is Hermitian on a truncated Hilbert space.

Random Operators and States

This module is a collection of random state and operator generators. The sparsity of the ouput Qobj’s is controlled by varing the density parameter.

rand_dm(N, density=0.75, pure=False, dims=None)

Creates a random NxN density matrix.

Parameters:

N : int

Shape of output density matrix.

density : float

Density between [0,1] of output density matrix.

dims : list

Dimensions of quantum object. Used for specifying tensor structure. Default is dims=[[N],[N]].

Returns:

oper : qobj

NxN density matrix quantum operator.

Notes

For small density matrices., choosing a low density will result in an error as no diagonal elements will be generated such that \(Tr(\rho)=1\).

rand_herm(N, density=0.75, dims=None)

Creates a random NxN sparse Hermitian quantum object.

Uses \(H=X+X^{+}\) where \(X\) is a randomly generated quantum operator with a given density.

Parameters:

N : int

Shape of output quantum operator.

density : float

Density between [0,1] of output Hermitian operator.

dims : list

Dimensions of quantum object. Used for specifying tensor structure. Default is dims=[[N],[N]].

Returns:

oper : qobj

NxN Hermitian quantum operator.

rand_ket(N, density=1, dims=None)

Creates a random Nx1 sparse ket vector.

Parameters:

N : int

Number of rows for output quantum operator.

density : float

Density between [0,1] of output ket state.

dims : list

Dimensions of quantum object. Used for specifying tensor structure. Default is dims=[[N],[1]].

Returns:

oper : qobj

Nx1 ket state quantum operator.

rand_unitary(N, density=0.75, dims=None)

Creates a random NxN sparse unitary quantum object.

Uses \(\exp(-iH)\) where H is a randomly generated Hermitian operator.

Parameters:

N : int

Shape of output quantum operator.

density : float

Density between [0,1] of output Unitary operator.

dims : list

Dimensions of quantum object. Used for specifying tensor structure. Default is dims=[[N],[N]].

Returns:

oper : qobj

NxN Unitary quantum operator.

Three-Level Atoms

This module provides functions that are useful for simulating the three level atom with QuTiP. A three level atom (qutrit) has three states, which are linked by dipole transitions so that 1 <-> 2 <-> 3. Depending on there relative energies they are in the ladder, lambda or vee configuration. The structure of the relevant operators is the same for any of the three configurations:

Ladder:          Lambda:                 Vee:
                            |two>                       |three>
  -------|three>           -------                      -------
     |                       / \             |one>         /
     |                      /   \           -------       /
     |                     /     \             \         /
  -------|two>            /       \             \       /
     |                   /         \             \     /
     |                  /           \             \   /
     |                 /        --------           \ /
  -------|one>      -------      |three>         -------
                     |one>                       |two>

References

The naming of qutip operators follows the convention in [R1] .

[R1]Shore, B. W., “The Theory of Coherent Atomic Excitation”, Wiley, 1990.

Notes

Contributed by Markus Baden, Oct. 07, 2011

three_level_basis()

Basis states for a three level atom.

Returns:

states : array

array of three level atom basis vectors.

three_level_ops()

Operators for a three level system (qutrit)

Returns:

ops : array

array of three level operators.

Superoperators and Liouvillians

operator_to_vector(op)

Create a vector representation of a quantum operator given the matrix representation.

vector_to_operator(op)

Create a matrix representation given a quantum operator in vector form.

liouvillian(H, c_ops=, []data_only=False)

Assembles the Liouvillian superoperator from a Hamiltonian and a list of collapse operators. Like liouvillian, but with an experimental implementation which avoids creating extra Qobj instances, which can be advantageous for large systems.

Parameters:

H : qobj

System Hamiltonian.

c_ops : array_like

A list or array of collapse operators.

Returns:

L : qobj

Liouvillian superoperator.

spost(A)

Superoperator formed from post-multiplication by operator A

Parameters:

A : qobj

Quantum operator for post multiplication.

Returns:

super : qobj

Superoperator formed from input qauntum object.

spre(A)

Superoperator formed from pre-multiplication by operator A.

Parameters:

A : qobj

Quantum operator for pre-multiplication.

Returns:

super :qobj :

Superoperator formed from input quantum object.

lindblad_dissipator(a, b=None, data_only=False)

Lindblad dissipator (generalized) for a single pair of collapse operators (a, b), or for a single collapse operator (a) when b is not specified:

\[\mathcal{D}[a,b]\rho = a \rho b^\dagger - \frac{1}{2}a^\dagger b\rho - \frac{1}{2}\rho a^\dagger b\]
Parameters:

a : qobj

Left part of collapse operator.

b : qobj (optional)

Right part of collapse operator. If not specified, b defaults to a.

Returns:

D : qobj

Lindblad dissipator superoperator.

Superoperator Representations

This module implements transformations between superoperator representations, including supermatrix, Kraus, Choi and Chi (process) matrix formalisms.

to_choi(q_oper)

Converts a Qobj representing a quantum map to the Choi representation, such that the trace of the returned operator is equal to the dimension of the system.

Parameters:

q_oper : Qobj

Superoperator to be converted to Choi representation.

Returns:

choi : Qobj

A quantum object representing the same map as q_oper, such that choi.superrep == "choi".

Raises:

TypeError: if the given quantum object is not a map, or cannot be converted :

to Choi representation.

to_super(q_oper)

Converts a Qobj representing a quantum map to the supermatrix (Liouville) representation.

Parameters:

q_oper : Qobj

Superoperator to be converted to supermatrix representation.

Returns:

superop : Qobj

A quantum object representing the same map as q_oper, such that superop.superrep == "super".

Raises:

TypeError: if the given quantum object is not a map, or cannot be converted :

to supermatrix representation.

to_kraus(q_oper)

Converts a Qobj representing a quantum map to a list of quantum objects, each representing an operator in the Kraus decomposition of the given map.

Parameters:

q_oper : Qobj

Superoperator to be converted to Kraus representation.

Returns:

kraus_ops : list of Qobj

A list of quantum objects, each representing a Kraus operator in the decomposition of q_oper.

Raises:

TypeError: if the given quantum object is not a map, or cannot be :

decomposed into Kraus operators.

Functions acting on states and operators

Tensor

Module for the creation of composite quantum objects via the tensor product.

tensor(*args)

Calculates the tensor product of input operators.

Parameters:

args : array_like

list or array of quantum objects for tensor product.

Returns:

obj : qobj

A composite quantum object.

Examples

>>> tensor([sigmax(), sigmax()])
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]
 [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j]
 [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j]
 [ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]]

Expectation Values

expect(oper, state)

Calculates the expectation value for operator(s) and state(s).

Parameters:

oper : qobj/array-like

A single or a list or operators for expectation value.

state : qobj/array-like

A single or a list of quantum states or density matrices.

Returns:

expt : float/complex/array-like

Expectation value. real if oper is Hermitian, complex otherwise. A (nested) array of expectaction values of state or operator are arrays.

Examples

>>> expect(num(4), basis(4, 3))
3
variance(oper, state)

Variance of an operator for the given state vector or density matrix.

Parameters:

oper : qobj

Operator for expectation value.

state : qobj/list

A single or list of quantum states or density matrices..

Returns:

var : float

Variance of operator ‘oper’ for given state.

Partial Transpose

partial_transpose(rho, mask, method='dense')

Return the partial transpose of a Qobj instance rho, where mask is an array/list with length that equals the number of components of rho (that is, the length of rho.dims[0]), and the values in mask indicates whether or not the corresponding subsystem is to be transposed. The elements in mask can be boolean or integers 0 or 1, where True/1 indicates that the corresponding subsystem should be tranposed.

Parameters:

rho : qutip.qobj

A density matrix.

mask : list / array

A mask that selects which subsystems should be transposed.

method : str

choice of method, dense or sparse. The default method is dense. The sparse implementation can be faster for large and sparse systems (hundreds of quantum states).

Returns:

rho_pr: :class:`qutip.qobj` :

A density matrix with the selected subsystems transposed.

Entropy Functions

concurrence(rho)

Calculate the concurrence entanglement measure for a two-qubit state.

Parameters:

state : qobj

Ket, bra, or density matrix for a two-qubit state.

Returns:

concur : float

Concurrence

References

[R2]http://en.wikipedia.org/wiki/Concurrence_(quantum_computing)
entropy_conditional(rho, selB, base=2.718281828459045, sparse=False)

Calculates the conditional entropy \(S(A|B)=S(A,B)-S(B)\) of a slected density matrix component.

Parameters:

rho : qobj

Density matrix of composite object

selB : int/list

Selected components for density matrix B

base : {e,2}

Base of logarithm.

sparse : {False,True}

Use sparse eigensolver.

Returns:

ent_cond : float

Value of conditional entropy

entropy_linear(rho)

Linear entropy of a density matrix.

Parameters:

rho : qobj

sensity matrix or ket/bra vector.

Returns:

entropy : float

Linear entropy of rho.

Examples

>>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
>>> entropy_linear(rho)
0.5
entropy_mutual(rho, selA, selB, base=2.718281828459045, sparse=False)

Calculates the mutual information S(A:B) between selection components of a system density matrix.

Parameters:

rho : qobj

Density matrix for composite quantum systems

selA : int/list

int or list of first selected density matrix components.

selB : int/list

int or list of second selected density matrix components.

base : {e,2}

Base of logarithm.

sparse : {False,True}

Use sparse eigensolver.

Returns:

ent_mut : float

Mutual information between selected components.

entropy_vn(rho, base=2.718281828459045, sparse=False)

Von-Neumann entropy of density matrix

Parameters:

rho : qobj

Density matrix.

base : {e,2}

Base of logarithm.

sparse : {False,True}

Use sparse eigensolver.

Returns:

entropy : float

Von-Neumann entropy of rho.

Examples

>>> rho=0.5*fock_dm(2,0)+0.5*fock_dm(2,1)
>>> entropy_vn(rho,2)
1.0

Density Matrix Metrics

This module contains a collection of functions for calculating metrics (distance measures) between states and operators.

fidelity(A, B)

Calculates the fidelity (pseudo-metric) between two density matrices. See: Nielsen & Chuang, “Quantum Computation and Quantum Information”

Parameters:

A : qobj

Density matrix or state vector.

B : qobj

Density matrix or state vector with same dimensions as A.

Returns:

fid : float

Fidelity pseudo-metric between A and B.

Examples

>>> x=fock_dm(5,3)
>>> y=coherent_dm(5,1)
>>> fidelity(x,y)
0.24104350624628332
tracedist(A, B, sparse=False, tol=0)

Calculates the trace distance between two density matrices.. See: Nielsen & Chuang, “Quantum Computation and Quantum Information”

Parameters:

A : qobj

Density matrix or state vector.

B : qobj

Density matrix or state vector with same dimensions as A.

tol : float

Tolerance used by sparse eigensolver, if used. (0=Machine precision)

sparse : {False, True}

Use sparse eigensolver.

Returns:

tracedist : float

Trace distance between A and B.

Examples

>>> x=fock_dm(5,3)
>>> y=coherent_dm(5,1)
>>> tracedist(x,y)
0.9705143161472971

Continous Variables

This module contains a collection functions for calculating continuous variable quantities from fock-basis representation of the state of multi-mode fields.

correlation_matrix(basis, rho=None)

Given a basis set of operators \(\{a\}_n\), calculate the correlation matrix:

\[C_{mn} = \langle a_m a_n \rangle\]
Parameters:

basis : list of qutip.qobj.Qobj

List of operators that defines the basis for the correlation matrix.

rho : qutip.qobj.Qobj

Density matrix for which to calculate the correlation matrix. If rho is None, then a matrix of correlation matrix operators is returned instead of expectation values of those operators.

Returns:

corr_mat: *array* :

A 2-dimensional array of correlation values or operators.

covariance_matrix(basis, rho, symmetrized=True)

Given a basis set of operators \(\{a\}_n\), calculate the covariance matrix:

\[V_{mn} = \frac{1}{2}\langle a_m a_n + a_n a_m \rangle - \langle a_m \rangle \langle a_n\rangle\]

or, if of the optional argument symmetrized=False,

\[V_{mn} = \langle a_m a_n\rangle - \langle a_m \rangle \langle a_n\rangle\]
Parameters:

basis : list of qutip.qobj.Qobj

List of operators that defines the basis for the covariance matrix.

rho : qutip.qobj.Qobj

Density matrix for which to calculate the covariance matrix.

symmetrized : bool

Flag indicating whether the symmetrized (default) or non-symmetrized correlation matrix is to be calculated.

Returns:

corr_mat: *array* :

A 2-dimensional array of covariance values.

correlation_matrix_field(a1, a2, rho=None)

Calculate the correlation matrix for given field operators \(a_1\) and \(a_2\). If a density matrix is given the expectation values are calculated, otherwise a matrix with operators is returned.

Parameters:

a1 : qutip.qobj.Qobj

Field operator for mode 1.

a2 : qutip.qobj.Qobj

Field operator for mode 2.

rho : qutip.qobj.Qobj

Density matrix for which to calculate the covariance matrix.

Returns:

cov_mat: *array* of complex numbers or :class:`qutip.qobj.Qobj` :

A 2-dimensional array of covariance values, or, if rho=0, a matrix of operators.

correlation_matrix_quadrature(a1, a2, rho=None)

Calculate the quadrature correlation matrix with given field operators \(a_1\) and \(a_2\). If a density matrix is given the expectation values are calculated, otherwise a matrix with operators is returned.

Parameters:

a1 : qutip.qobj.Qobj

Field operator for mode 1.

a2 : qutip.qobj.Qobj

Field operator for mode 2.

rho : qutip.qobj.Qobj

Density matrix for which to calculate the covariance matrix.

Returns:

corr_mat: *array* of complex numbers or :class:`qutip.qobj.Qobj` :

A 2-dimensional array of covariance values for the field quadratures, or, if rho=0, a matrix of operators.

wigner_covariance_matrix(a1=None, a2=None, R=None, rho=None)

Calculate the Wigner covariance matrix \(V_{ij} = \frac{1}{2}(R_{ij} + R_{ji})\), given the quadrature correlation matrix \(R_{ij} = \langle R_{i} R_{j}\rangle - \langle R_{i}\rangle \langle R_{j}\rangle\), where \(R = (q_1, p_1, q_2, p_2)^T\) is the vector with quadrature operators for the two modes.

Alternatively, if R = None, and if annihilation operators a1 and a2 for the two modes are supplied instead, the quadrature correlation matrix is constructed from the annihilation operators before then the covariance matrix is calculated.

Parameters:

a1 : qutip.qobj.Qobj

Field operator for mode 1.

a2 : qutip.qobj.Qobj

Field operator for mode 2.

R : array

The quadrature correlation matrix.

rho : qutip.qobj.Qobj

Density matrix for which to calculate the covariance matrix.

Returns:

cov_mat: *array* :

A 2-dimensional array of covariance values.

logarithmic_negativity(V)

Calculate the logarithmic negativity given the symmetrized covariance matrix, see qutip.continous_variables.covariance_matrix. Note that the two-mode field state that is described by V must be Gaussian for this function to applicable.

Parameters:

V : 2d array

The covariance matrix.

Returns:

N: *float*, the logarithmic negativity for the two-mode Gaussian state :

that is described by the the Wigner covariance matrix V. :

Dynamics and Time-Evolution

Schrödinger Equation

This module provides solvers for the unitary Schrodinger equation.

sesolve(H, rho0, tlist, e_ops, args={}, options=None, progress_bar=<qutip.ui.progressbar.BaseProgressBar object at 0x2b11f65d3a90>)

Schrodinger equation evolution of a state vector for a given Hamiltonian.

Evolve the state vector or density matrix (rho0) using a given Hamiltonian (H), by integrating the set of ordinary differential equations that define the system.

The output is either the state vector at arbitrary points in time (tlist), or the expectation values of the supplied operators (e_ops). If e_ops is a callback function, it is invoked for each time in tlist with time and the state as arguments, and the function does not use any return values.

Parameters:

H : qutip.qobj

system Hamiltonian, or a callback function for time-dependent Hamiltonians.

rho0 : qutip.qobj

initial density matrix or state vector (ket).

tlist : list / array

list of times for \(t\).

e_ops : list of qutip.qobj / callback function single

single operator or list of operators for which to evaluate expectation values.

args : dictionary

dictionary of parameters for time-dependent Hamiltonians and collapse operators.

options : qutip.Qdeoptions

with options for the ODE solver.

Returns:

output: :class:`qutip.solver` :

An instance of the class qutip.solver, which contains either an array of expectation values for the times specified by tlist, or an array or state vectors or density matrices corresponding to the times in tlist [if e_ops is an empty list], or nothing if a callback function was given inplace of operators for which to calculate the expectation values.

Master Equation

This module provides solvers for the Lindblad master equation and von Neumann equation.

mesolve(H, rho0, tlist, c_ops, e_ops, args={}, options=None, progress_bar=<qutip.ui.progressbar.BaseProgressBar object at 0x2b11f65d3b10>)

Master equation evolution of a density matrix for a given Hamiltonian.

Evolve the state vector or density matrix (rho0) using a given Hamiltonian (H) and an [optional] set of collapse operators (c_op_list), by integrating the set of ordinary differential equations that define the system. In the absence of collapse operators the system is evolved according to the unitary evolution of the Hamiltonian.

The output is either the state vector at arbitrary points in time (tlist), or the expectation values of the supplied operators (e_ops). If e_ops is a callback function, it is invoked for each time in tlist with time and the state as arguments, and the function does not use any return values.

Time-dependent operators

For problems with time-dependent problems H and c_ops can be callback functions that takes two arguments, time and args, and returns the Hamiltonian or Liouvillian for the system at that point in time (callback format).

Alternatively, H and c_ops can be a specified in a nested-list format where each element in the list is a list of length 2, containing an operator (qutip.qobj) at the first element and where the second element is either a string (list string format), a callback function (list callback format) that evaluates to the time-dependent coefficient for the corresponding operator, or a numpy array (list array format) which specifies the value of the coefficient to the corresponding operator for each value of t in tlist.

Examples

H = [[H0, ‘sin(w*t)’], [H1, ‘sin(2*w*t)’]]

H = [[H0, sin(w*tlist)], [H1, sin(2*w*tlist)]]

H = [[H0, f0_t], [H1, f1_t]]

where f0_t and f1_t are python functions with signature f_t(t, args).

In the list string format and list callback format, the string expression and the callback function must evaluate to a real or complex number (coefficient for the corresponding operator).

In all cases of time-dependent operators, args is a dictionary of parameters that is used when evaluating operators. It is passed to the callback functions as second argument

Note

If an element in the list-specification of the Hamiltonian or the list of collapse operators are in super-operator for it will be added to the total Liouvillian of the problem with out further transformation. This allows for using mesolve for solving master equations that are not on standard Lindblad form.

Note

On using callback function: mesolve transforms all qutip.qobj objects to sparse matrices before handing the problem to the integrator function. In order for your callback function to work correctly, pass all qutip.qobj objects that are used in constructing the Hamiltonian via args. mesolve will check for qutip.qobj in args and handle the conversion to sparse matrices. All other qutip.qobj objects that are not passed via args will be passed on to the integrator in scipy which will raise an NotImplemented exception.

Parameters:

H : qutip.Qobj

system Hamiltonian, or a callback function for time-dependent Hamiltonians.

rho0 : qutip.Qobj

initial density matrix or state vector (ket).

tlist : list / array

list of times for \(t\).

c_ops : list of qutip.Qobj

single collapse operator, or list of collapse operators.

e_ops : list of qutip.Qobj / callback function single

single operator or list of operators for which to evaluate expectation values.

args : dictionary

dictionary of parameters for time-dependent Hamiltonians and collapse operators.

options : qutip.Options

with options for the ODE solver.

Returns:

output: :class:`qutip.solver` :

An instance of the class qutip.solver, which contains either an array of expectation values for the times specified by tlist, or an array or state vectors or density matrices corresponding to the times in tlist [if e_ops is an empty list], or nothing if a callback function was given in place of operators for which to calculate the expectation values.

Monte Carlo Evolution

mcsolve(H, psi0, tlist, c_ops, e_ops, ntraj=None, args={}, options=<qutip.solver.Options instance at 0x2b11f5a5ccf8>)

Monte-Carlo evolution of a state vector \(|\psi \rangle\) for a given Hamiltonian and sets of collapse operators, and possibly, operators for calculating expectation values. Options for the underlying ODE solver are given by the Options class.

mcsolve supports time-dependent Hamiltonians and collapse operators using either Python functions of strings to represent time-dependent coefficients. Note that, the system Hamiltonian MUST have at least one constant term.

As an example of a time-dependent problem, consider a Hamiltonian with two terms H0 and H1, where H1 is time-dependent with coefficient sin(w*t), and collapse operators C0 and C1, where C1 is time-dependent with coeffcient exp(-a*t). Here, w and a are constant arguments with values W and A.

Using the Python function time-dependent format requires two Python functions, one for each collapse coefficient. Therefore, this problem could be expressed as:

def H1_coeff(t,args):
    return sin(args['w']*t)

def C1_coeff(t,args):
    return exp(-args['a']*t)

H=[H0,[H1,H1_coeff]]

c_op_list=[C0,[C1,C1_coeff]]

args={'a':A,'w':W}

or in String (Cython) format we could write:

H=[H0,[H1,'sin(w*t)']]

c_op_list=[C0,[C1,'exp(-a*t)']]

args={'a':A,'w':W}

Constant terms are preferably placed first in the Hamiltonian and collapse operator lists.

Parameters:

H : qobj

System Hamiltonian.

psi0 : qobj

Initial state vector

tlist : array_like

Times at which results are recorded.

ntraj : int

Number of trajectories to run.

c_ops : array_like

single collapse operator or list or array of collapse operators.

e_ops : array_like

single operator or list or array of operators for calculating expectation values.

args : dict

Arguments for time-dependent Hamiltonian and collapse operator terms.

options : Options

Instance of ODE solver options.

Returns:

results : Result

Object storing all results from simulation.

mcsolve_f90(H, psi0, tlist, c_ops, e_ops, ntraj=None, options=<qutip.solver.Options instance at 0x2b11f5a5cd40>, sparse_dms=True, serial=False, ptrace_sel=, []calc_entropy=False)

Monte-Carlo wave function solver with fortran 90 backend. Usage is identical to qutip.mcsolve, for problems without explicit time-dependence, and with some optional input:

Parameters:

H : qobj

System Hamiltonian.

psi0 : qobj

Initial state vector

tlist : array_like

Times at which results are recorded.

ntraj : int

Number of trajectories to run.

c_ops : array_like

list or array of collapse operators.

e_ops : array_like

list or array of operators for calculating expectation values.

options : Options

Instance of solver options.

sparse_dms : boolean

If averaged density matrices are returned, they will be stored as sparse (Compressed Row Format) matrices during computation if sparse_dms = True (default), and dense matrices otherwise. Dense matrices might be preferable for smaller systems.

serial : boolean

If True (default is False) the solver will not make use of the multiprocessing module, and simply run in serial.

ptrace_sel: list :

This optional argument specifies a list of components to keep when returning a partially traced density matrix. This can be convenient for large systems where memory becomes a problem, but you are only interested in parts of the density matrix.

calc_entropy : boolean

If ptrace_sel is specified, calc_entropy=True will have the solver return the averaged entropy over trajectories in results.entropy. This can be interpreted as a measure of entanglement. See Phys. Rev. Lett. 93, 120408 (2004), Phys. Rev. A 86, 022310 (2012).

Returns:

results : Result

Object storing all results from simulation.

Exponential Series

essolve(H, rho0, tlist, c_op_list, e_ops)

Evolution of a state vector or density matrix (rho0) for a given Hamiltonian (H) and set of collapse operators (c_op_list), by expressing the ODE as an exponential series. The output is either the state vector at arbitrary points in time (tlist), or the expectation values of the supplied operators (e_ops).

Parameters:

H : qobj/function_type

System Hamiltonian.

rho0 : qutip.qobj

Initial state density matrix.

tlist : list/array

list of times for \(t\).

c_op_list : list of qutip.qobj

list of qutip.qobj collapse operators.

e_ops : list of qutip.qobj

list of qutip.qobj operators for which to evaluate expectation values.

Returns:

expt_array : array

Expectation values of wavefunctions/density matrices for the times specified in tlist.

.. note:: This solver does not support time-dependent Hamiltonians. :

ode2es(L, rho0)

Creates an exponential series that describes the time evolution for the initial density matrix (or state vector) rho0, given the Liouvillian (or Hamiltonian) L.

Parameters:

L : qobj

Liouvillian of the system.

rho0 : qobj

Initial state vector or density matrix.

Returns:

eseries : qutip.eseries

eseries represention of the system dynamics.

Bloch-Redfield Master Equation

brmesolve(H, psi0, tlist, a_ops, e_ops=, []spectra_cb=, []args={}, options=<qutip.solver.Options instance at 0x2b11f6845680>)

Solve the dynamics for the system using the Bloch-Redfeild master equation.

Note

This solver does not currently support time-dependent Hamiltonian or collapse operators.

Parameters:

H : qutip.qobj

System Hamiltonian.

rho0 / psi0: :class:`qutip.qobj` :

Initial density matrix or state vector (ket).

tlist : list / array

List of times for \(t\).

a_ops : list of qutip.qobj

List of system operators that couple to bath degrees of freedom.

e_ops : list of qutip.qobj / callback function

List of operators for which to evaluate expectation values.

args : dictionary

Dictionary of parameters for time-dependent Hamiltonians and collapse operators.

options : qutip.Qdeoptions

Options for the ODE solver.

Returns:

output: :class:`qutip.solver` :

An instance of the class qutip.solver, which contains either a list of expectation values, for operators given in e_ops, or a list of states for the times specified by tlist.

bloch_redfield_tensor(H, a_ops, spectra_cb, use_secular=True)

Calculate the Bloch-Redfield tensor for a system given a set of operators and corresponding spectral functions that describes the system’s coupling to its environment.

Parameters:

H : qutip.qobj

System Hamiltonian.

a_ops : list of qutip.qobj

List of system operators that couple to the environment.

spectra_cb : list of callback functions

List of callback functions that evaluate the noise power spectrum at a given frequency.

use_secular : bool

Flag (True of False) that indicates if the secular approximation should be used.

Returns:

R, kets: :class:`qutip.qobj`, list of :class:`qutip.qobj` :

R is the Bloch-Redfield tensor and kets is a list eigenstates of the Hamiltonian.

bloch_redfield_solve(R, ekets, rho0, tlist, e_ops=, []options=None)

Evolve the ODEs defined by Bloch-Redfield master equation. The Bloch-Redfield tensor can be calculated by the function bloch_redfield_tensor.

Parameters:

R : qutip.qobj

Bloch-Redfield tensor.

ekets : array of qutip.qobj

Array of kets that make up a basis tranformation for the eigenbasis.

rho0 : qutip.qobj

Initial density matrix.

tlist : list / array

List of times for \(t\).

e_ops : list of qutip.qobj / callback function

List of operators for which to evaluate expectation values.

options : qutip.Qdeoptions

Options for the ODE solver.

Returns:

output: :class:`qutip.solver` :

An instance of the class qutip.solver, which contains either an array of expectation values for the times specified by tlist.

Floquet States and Floquet-Markov Master Equation

fmmesolve(H, rho0, tlist, c_ops, e_ops=, []spectra_cb=, []T=None, args={}, options=<qutip.solver.Options instance at 0x2b11f68454d0>, floquet_basis=True, kmax=5)

Solve the dynamics for the system using the Floquet-Markov master equation.

Note

This solver currently does not support multiple collapse operators.

Parameters:

H : qutip.qobj

system Hamiltonian.

rho0 / psi0 : qutip.qobj

initial density matrix or state vector (ket).

tlist : list / array

list of times for \(t\).

c_ops : list of qutip.qobj

list of collapse operators.

e_ops : list of qutip.qobj / callback function

list of operators for which to evaluate expectation values.

spectra_cb : list callback functions

List of callback functions that compute the noise power spectrum as a function of frequency for the collapse operators in c_ops.

T : float

The period of the time-dependence of the hamiltonian. The default value ‘None’ indicates that the ‘tlist’ spans a single period of the driving.

args : dictionary

dictionary of parameters for time-dependent Hamiltonians and collapse operators.

This dictionary should also contain an entry ‘w_th’, which is the temperature of the environment (if finite) in the energy/frequency units of the Hamiltonian. For example, if the Hamiltonian written in units of 2pi GHz, and the temperature is given in K, use the following conversion

>>> temperature = 25e-3 # unit K
>>> h = 6.626e-34
>>> kB = 1.38e-23
>>> args['w_th'] = temperature * (kB / h) * 2 * pi * 1e-9

options : qutip.solver

options for the ODE solver.

k_max : int

The truncation of the number of sidebands (default 5).

Returns:

output : qutip.solver

An instance of the class qutip.solver, which contains either an array of expectation values for the times specified by tlist.

floquet_modes(H, T, args=None, sort=False, U=None)

Calculate the initial Floquet modes Phi_alpha(0) for a driven system with period T.

Returns a list of qutip.qobj instances representing the Floquet modes and a list of corresponding quasienergies, sorted by increasing quasienergy in the interval [-pi/T, pi/T]. The optional parameter sort decides if the output is to be sorted in increasing quasienergies or not.

Parameters:

H : qutip.qobj

system Hamiltonian, time-dependent with period T

args : dictionary

dictionary with variables required to evaluate H

T : float

The period of the time-dependence of the hamiltonian. The default value ‘None’ indicates that the ‘tlist’ spans a single period of the driving.

U : qutip.qobj

The propagator for the time-dependent Hamiltonian with period T. If U is None (default), it will be calculated from the Hamiltonian H using qutip.propagator.propagator.

Returns:

output : list of kets, list of quasi energies

Two lists: the Floquet modes as kets and the quasi energies.

floquet_modes_t(f_modes_0, f_energies, t, H, T, args=None)

Calculate the Floquet modes at times tlist Phi_alpha(tlist) propagting the initial Floquet modes Phi_alpha(0)

Parameters:

f_modes_0 : list of qutip.qobj (kets)

Floquet modes at \(t\)

f_energies : list

Floquet energies.

t : float

The time at which to evaluate the floquet modes.

H : qutip.qobj

system Hamiltonian, time-dependent with period T

args : dictionary

dictionary with variables required to evaluate H

T : float

The period of the time-dependence of the hamiltonian.

Returns:

output : list of kets

The Floquet modes as kets at time \(t\)

floquet_modes_table(f_modes_0, f_energies, tlist, H, T, args=None)

Pre-calculate the Floquet modes for a range of times spanning the floquet period. Can later be used as a table to look up the floquet modes for any time.

Parameters:

f_modes_0 : list of qutip.qobj (kets)

Floquet modes at \(t\)

f_energies : list

Floquet energies.

tlist : array

The list of times at which to evaluate the floquet modes.

H : qutip.qobj

system Hamiltonian, time-dependent with period T

T : float

The period of the time-dependence of the hamiltonian.

args : dictionary

dictionary with variables required to evaluate H

Returns:

output : nested list

A nested list of Floquet modes as kets for each time in tlist

floquet_modes_t_lookup(f_modes_table_t, t, T)

Lookup the floquet mode at time t in the pre-calculated table of floquet modes in the first period of the time-dependence.

Parameters:

f_modes_table_t : nested list of qutip.qobj (kets)

A lookup-table of Floquet modes at times precalculated by qutip.floquet.floquet_modes_table.

t : float

The time for which to evaluate the Floquet modes.

T : float

The period of the time-dependence of the hamiltonian.

Returns:

output : nested list

A list of Floquet modes as kets for the time that most closely matching the time t in the supplied table of Floquet modes.

floquet_states_t(f_modes_0, f_energies, t, H, T, args=None)

Evaluate the floquet states at time t given the initial Floquet modes.

Parameters:

f_modes_t : list of qutip.qobj (kets)

A list of initial Floquet modes (for time \(t=0\)).

f_energies : array

The Floquet energies.

t : float

The time for which to evaluate the Floquet states.

H : qutip.qobj

System Hamiltonian, time-dependent with period T.

T : float

The period of the time-dependence of the hamiltonian.

args : dictionary

Dictionary with variables required to evaluate H.

Returns:

output : list

A list of Floquet states for the time \(t\).

floquet_wavefunction_t(f_modes_0, f_energies, f_coeff, t, H, T, args=None)

Evaluate the wavefunction for a time t using the Floquet state decompositon, given the initial Floquet modes.

Parameters:

f_modes_t : list of qutip.qobj (kets)

A list of initial Floquet modes (for time \(t=0\)).

f_energies : array

The Floquet energies.

f_coeff : array

The coefficients for Floquet decomposition of the initial wavefunction.

t : float

The time for which to evaluate the Floquet states.

H : qutip.qobj

System Hamiltonian, time-dependent with period T.

T : float

The period of the time-dependence of the hamiltonian.

args : dictionary

Dictionary with variables required to evaluate H.

Returns:

output : qutip.qobj

The wavefunction for the time \(t\).

floquet_state_decomposition(f_states, f_energies, psi)

Decompose the wavefunction psi (typically an initial state) in terms of the Floquet states, \(\psi = \sum_\alpha c_\alpha \psi_\alpha(0)\).

Parameters:

f_states : list of qutip.qobj (kets)

A list of Floquet modes.

f_energies : array

The Floquet energies.

psi : qutip.qobj

The wavefunction to decompose in the Floquet state basis.

Returns:

output : array

The coefficients \(c_\alpha\) in the Floquet state decomposition.

fsesolve(H, psi0, tlist, e_ops=, []T=None, args={}, Tsteps=100)

Solve the Schrodinger equation using the Floquet formalism.

Parameters:

H : qutip.qobj.Qobj

System Hamiltonian, time-dependent with period T.

psi0 : qutip.qobj

Initial state vector (ket).

tlist : list / array

list of times for \(t\).

e_ops : list of qutip.qobj / callback function

list of operators for which to evaluate expectation values. If this list is empty, the state vectors for each time in tlist will be returned instead of expectation values.

T : float

The period of the time-dependence of the hamiltonian.

args : dictionary

Dictionary with variables required to evaluate H.

Tsteps : integer

The number of time steps in one driving period for which to precalculate the Floquet modes. Tsteps should be an even number.

Returns:

output : qutip.solver.Result

An instance of the class qutip.solver.Result, which contains either an array of expectation values or an array of state vectors, for the times specified by tlist.

Stochastic Schrödinger Equation and Master Equation

This module contains experimental functions for solving stochastic schrodinger and master equations. The API should not be considered stable, and is subject to change when we work more on optimizing this module for performance and features.

Todo:

  • parallelize
smesolve(H, rho0, times, c_ops, sc_ops, e_ops, **kwargs)

Solve stochastic master equation. Dispatch to specific solvers depending on the value of the solver keyword argument.

Parameters:

H : qutip.Qobj

System Hamiltonian.

rho0 : qutip.Qobj

Initial density matrix or state vector (ket).

times : list / array

List of times for \(t\). Must be uniformly spaced.

c_ops : list of qutip.Qobj

Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation.

sc_ops : list of qutip.Qobj

List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined.

e_ops : list of qutip.Qobj / callback function single

single operator or list of operators for which to evaluate expectation values.

kwargs : dictionary

Optional keyword arguments. See qutip.stochastic.StochasticSolverOptions.

Returns:

output: :class:`qutip.solver.SolverResult` :

An instance of the class qutip.solver.SolverResult.

ssesolve(H, psi0, times, sc_ops, e_ops, **kwargs)

Solve stochastic Schrödinger equation. Dispatch to specific solvers depending on the value of the solver keyword argument.

Parameters:

H : qutip.Qobj

System Hamiltonian.

psi0 : qutip.Qobj

Initial state vector (ket).

times : list / array

List of times for \(t\). Must be uniformly spaced.

sc_ops : list of qutip.Qobj

List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the equation of motion according to how the d1 and d2 functions are defined.

e_ops : list of qutip.Qobj

Single operator or list of operators for which to evaluate expectation values.

kwargs : dictionary

Optional keyword arguments. See qutip.stochastic.StochasticSolverOptions.

Returns:

output: :class:`qutip.solver.SolverResult` :

An instance of the class qutip.solver.SolverResult.

smepdpsolve(H, rho0, times, c_ops, e_ops, **kwargs)

A stochastic (piecewse deterministic process) PDP solver for density matrix evolution.

Parameters:

H : qutip.Qobj

System Hamiltonian.

rho0 : qutip.Qobj

Initial density matrix.

times : list / array

List of times for \(t\). Must be uniformly spaced.

c_ops : list of qutip.Qobj

Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation.

sc_ops : list of qutip.Qobj

List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined.

e_ops : list of qutip.Qobj / callback function single

single operator or list of operators for which to evaluate expectation values.

kwargs : dictionary

Optional keyword arguments. See qutip.stochastic.StochasticSolverOptions.

Returns:

output: :class:`qutip.solver.SolverResult` :

An instance of the class qutip.solver.SolverResult.

ssepdpsolve(H, psi0, times, c_ops, e_ops, **kwargs)

A stochastic (piecewse deterministic process) PDP solver for wavefunction evolution. For most purposes, use qutip.mcsolve instead for quantum trajectory simulations.

Parameters:

H : qutip.Qobj

System Hamiltonian.

psi0 : qutip.Qobj

Initial state vector (ket).

times : list / array

List of times for \(t\). Must be uniformly spaced.

c_ops : list of qutip.Qobj

Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation.

e_ops : list of qutip.Qobj / callback function single

single operator or list of operators for which to evaluate expectation values.

kwargs : dictionary

Optional keyword arguments. See qutip.stochastic.StochasticSolverOptions.

Returns:

output: :class:`qutip.solver.SolverResult` :

An instance of the class qutip.solver.SolverResult.

Correlation Functions

correlation(H, rho0, tlist, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args=None, options=<qutip.solver.Options instance at 0x2b11f682fd88>)

Calculate a two-operator two-time correlation function on the form \(\left<A(t+\tau)B(t)\right>\) or \(\left<A(t)B(t+\tau)\right>\) (if reverse=True), using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

tlist : list / array

list of times for \(t\).

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj

operator A.

b_op : qutip.qobj

operator B.

solver : str

choice of solver (me for master-equation, es for exponential series and mc for Monte-carlo)

Returns:

corr_mat: *array* :

An 2-dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index). If tlist is None, then a 1-dimensional array of correlation values is returned instead.

correlation_ss(H, taulist, c_ops, a_op, b_op, rho0=None, solver='me', reverse=False, args=None, options=<qutip.solver.Options instance at 0x2b11f682fd40>)

Calculate a two-operator two-time correlation function \(\left<A(\tau)B(0)\right>\) or \(\left<A(0)B(\tau)\right>\) (if reverse=True), using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

operator A.

b_op : qutip.qobj.Qobj

operator B.

reverse : bool

If True, calculate \(\left<A(0)B(\tau)\right>\) instead of \(\left<A(\tau)B(0)\right>\).

solver : str

choice of solver (me for master-equation, es for exponential series and mc for Monte-carlo)

Returns:

corr_vec: *array* :

An array of correlation values for the times specified by tlist

correlation_2op_1t(H, rho0, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args=None, options=<qutip.solver.Options instance at 0x2b11f682fb90>)

Calculate a two-operator two-time correlation function \(\left<A(\tau)B(0)\right>\) or \(\left<A(0)B(\tau)\right>\) (if reverse=True), using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If rho0 is None, then the steady state will be used as initial state.

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

operator A.

b_op : qutip.qobj.Qobj

operator B.

reverse : bool

If True, calculate \(\left<A(0)B(\tau)\right>\) instead of \(\left<A(\tau)B(0)\right>\).

solver : str

choice of solver (me for master-equation, es for exponential series and mc for Monte-carlo)

Returns:

corr_vec: *array* :

An array of correlation values for the times specified by taulist

correlation_2op_2t(H, rho0, tlist, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args=None, options=<qutip.solver.Options instance at 0x2b11f682fbd8>)

Calculate a two-operator two-time correlation function on the form \(\left<A(t+\tau)B(t)\right>\) or \(\left<A(t)B(t+\tau)\right>\) (if reverse=True), using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix \(\rho(t_0)\) (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

tlist : list / array

list of times for \(t\).

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

operator A.

b_op : qutip.qobj.Qobj

operator B.

solver : str

choice of solver (me for master-equation, es for exponential series and mc for Monte-carlo)

reverse : bool

If True, calculate \(\left<A(t)B(t+\tau)\right>\) instead of \(\left<A(t+\tau)B(t)\right>\).

Returns:

corr_mat: *array* :

An 2-dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index). If tlist is None, then a 1-dimensional array of correlation values is returned instead.

correlation_4op_1t(H, rho0, taulist, c_ops, a_op, b_op, c_op, d_op, solver='me', args=None, options=<qutip.solver.Options instance at 0x2b11f682fc20>)

Calculate the four-operator two-time correlation function on the from \(\left<A(0)B(\tau)C(\tau)D(0)\right>\) using the quantum regression theorem and the solver indicated by the ‘solver’ parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

operator A.

b_op : qutip.qobj.Qobj

operator B.

c_op : qutip.qobj.Qobj

operator C.

d_op : qutip.qobj.Qobj

operator D.

solver : str

choice of solver (currently only me for master-equation)

Returns:

corr_vec: *array* :

An array of correlation values for the times specified by taulist

References

See, Gardiner, Quantum Noise, Section 5.2.1.

correlation_4op_2t(H, rho0, tlist, taulist, c_ops, a_op, b_op, c_op, d_op, solver='me', args=None, options=<qutip.solver.Options instance at 0x2b11f682fc68>)

Calculate the four-operator two-time correlation function on the from \(\left<A(t)B(t+\tau)C(t+\tau)D(t)\right>\) using the quantum regression theorem and the solver indicated by the ‘solver’ parameter.

Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

tlist : list / array

list of times for \(t\).

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

operator A.

b_op : qutip.qobj.Qobj

operator B.

c_op : qutip.qobj.Qobj

operator C.

d_op : qutip.qobj.Qobj

operator D.

solver : str

choice of solver (currently only me for master-equation)

Returns:

corr_mat: *array* :

An 2-dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index). If tlist is None, then a 1-dimensional array of correlation values is returned instead.

References

See, Gardiner, Quantum Noise, Section 5.2.1.

spectrum_ss(H, wlist, c_ops, a_op, b_op)

Calculate the spectrum corresponding to a correlation function \(\left<A(\tau)B(0)\right>\), i.e., the Fourier transform of the correlation function:

\[\begin{split}S(\omega) = \int_{-\infty}^{\infty} \left<A(\tau)B(0)\right> e^{-i\omega\tau} d\tau.\end{split}\]
Parameters:

H : qutip.qobj

system Hamiltonian.

wlist : list / array

list of frequencies for \(\omega\).

c_ops : list of qutip.qobj

list of collapse operators.

a_op : qutip.qobj

operator A.

b_op : qutip.qobj

operator B.

Returns:

spectrum: *array* :

An array with spectrum \(S(\omega)\) for the frequencies specified in wlist.

spectrum_pi(H, wlist, c_ops, a_op, b_op, use_pinv=False)

Calculate the spectrum corresponding to a correlation function \(\left<A(\tau)B(0)\right>\), i.e., the Fourier transform of the correlation function:

\[\begin{split}S(\omega) = \int_{-\infty}^{\infty} \left<A(\tau)B(0)\right> e^{-i\omega\tau} d\tau.\end{split}\]
Parameters:

H : qutip.qobj

system Hamiltonian.

wlist : list / array

list of frequencies for \(\omega\).

c_ops : list of qutip.qobj

list of collapse operators.

a_op : qutip.qobj

operator A.

b_op : qutip.qobj

operator B.

Returns:

s_vec: *array* :

An array with spectrum \(S(\omega)\) for the frequencies specified in wlist.

spectrum_correlation_fft(tlist, y)

Calculate the power spectrum corresponding to a two-time correlation function using FFT.

Parameters:

tlist : list / array

list/array of times \(t\) which the correlation function is given.

y : list / array

list/array of correlations corresponding to time delays \(t\).

Returns:

w, S : tuple

Returns an array of angular frequencies ‘w’ and the corresponding one-sided power spectrum ‘S(w)’.

coherence_function_g1(H, rho0, taulist, c_ops, a_op, solver='me', args=None, options=<qutip.solver.Options instance at 0x2b11f682fcb0>)

Calculate the first-order quantum coherence function:

\[g^{(1)}(\tau) = \frac{\langle a^\dagger(\tau)a(0)\rangle} {\sqrt{\langle a^\dagger(\tau)a(\tau)\rangle \langle a^\dagger(0)a(0)\rangle}}\]
Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

The annihilation operator of the mode.

solver : str

choice of solver (‘me’, ‘mc’, ‘es’)

Returns:

g1, G2: tuble of *array* :

The normalized and unnormalized first-order coherence function.

coherence_function_g2(H, rho0, taulist, c_ops, a_op, solver='me', args=None, options=<qutip.solver.Options instance at 0x2b11f682fcf8>)

Calculate the second-order quantum coherence function:

\[g^{(2)}(\tau) = \frac{\langle a^\dagger(0)a^\dagger(\tau)a(\tau)a(0)\rangle} {\langle a^\dagger(\tau)a(\tau)\rangle \langle a^\dagger(0)a(0)\rangle}\]
Parameters:

H : qutip.qobj.Qobj

system Hamiltonian.

rho0 : qutip.qobj.Qobj

Initial state density matrix (or state vector). If ‘rho0’ is ‘None’, then the steady state will be used as initial state.

taulist : list / array

list of times for \(\tau\).

c_ops : list of qutip.qobj.Qobj

list of collapse operators.

a_op : qutip.qobj.Qobj

The annihilation operator of the mode.

solver : str

choice of solver (currently only ‘me’)

Returns:

g2, G2: tuble of *array* :

The normalized and unnormalized second-order coherence function.

Steady-state Solvers

Module contains functions for solving for the steady state density matrix of open quantum systems defined by a Liouvillian or Hamiltonian and a list of collapse operators.

steadystate(A, c_op_list=, []**kwargs)

Calculates the steady state for quantum evolution subject to the supplied Hamiltonian or Liouvillian operator and (if given a Hamiltonian) a list of collapse operators.

If the user passes a Hamiltonian then it, along with the list of collapse operators, will be converted into a Liouvillian operator in Lindblad form.

Parameters:

A : qobj

A Hamiltonian or Liouvillian operator.

c_op_list : list

A list of collapse operators.

method : str {‘direct’, ‘eigen’, ‘iterative-bicg’,

‘iterative-gmres’, ‘svd’, ‘power’}

Method for solving the underlying linear equation. Direct LU solver ‘direct’ (default), sparse eigenvalue problem ‘eigen’, iterative GMRES method ‘iterative-gmres’, iterative LGMRES method ‘iterative-lgmres’, SVD ‘svd’ (dense), or inverse-power method ‘power’.

sparse : bool, optional, default=True

Solve for the steady state using sparse algorithms. If set to False, the underlying Liouvillian operator will be converted into a dense matrix. Use only for ‘smaller’ systems.

use_rcm : bool, optional, default=True

Use reverse Cuthill-Mckee reordering to minimize fill-in in the LU factorization of the Liouvillian.

use_wbm : bool, optional, default=False

Use Weighted Bipartite Matching reordering to make the Liouvillian diagonally dominant. This is useful for iterative preconditioners only, and is set to True by default when finding a preconditioner.

weight : float, optional

Sets the size of the elements used for adding the unity trace condition to the linear solvers. This is set to the average abs value of the Liouvillian elements if not specified by the user.

use_umfpack : bool {False, True}

Use umfpack solver instead of SuperLU. For SciPy 0.14+, this option requires installing scikits.umfpack.

maxiter : int, optional, default=10000

Maximum number of iterations to perform if using an iterative method.

tol : float, optional, default=1e-9

Tolerance used for terminating solver solution when using iterative solvers.

permc_spec : str, optional, default=’COLAMD’

Column ordering used internally by superLU for the ‘direct’ LU decomposition method. Options include ‘COLAMD’ and ‘NATURAL’. If using RCM then this is set to ‘NATURAL’ automatically unless explicitly specified.

use_precond : bool optional, default = True

ITERATIVE ONLY. Use an incomplete sparse LU decomposition as a preconditioner for the ‘iterative’ GMRES and BICG solvers. Speeds up convergence time by orders of magnitude in many cases.

M : {sparse matrix, dense matrix, LinearOperator}, optional

Preconditioner for A. The preconditioner should approximate the inverse of A. Effective preconditioning dramatically improves the rate of convergence, for iterative methods only . If no preconditioner is given and use_precond=True, then one is generated automatically.

fill_factor : float, optional, default=10

ITERATIVE ONLY. Specifies the fill ratio upper bound (>=1) of the iLU preconditioner. Lower values save memory at the cost of longer execution times and a possible singular factorization.

drop_tol : float, optional, default=1e-3

ITERATIVE ONLY. Sets the threshold for the magnitude of preconditioner elements that should be dropped. Can be reduced for a courser factorization at the cost of an increased number of iterations, and a possible singular factorization.

diag_pivot_thresh : float, optional, default=None

ITERATIVE ONLY. Sets the threshold between [0,1] for which diagonal elements are considered acceptable pivot points when using a preconditioner. A value of zero forces the pivot to be the diagonal element.

ILU_MILU : str, optional, default=’smilu_2’

Selects the incomplete LU decomposition method algoithm used in creating the preconditoner. Should only be used by advanced users.

Returns:

dm : qobj

Steady state density matrix.

Notes

The SVD method works only for dense operators (i.e. small systems).

Propagators

propagator(H, t, c_op_list, args=None, options=None, sparse=False)

Calculate the propagator U(t) for the density matrix or wave function such that \(\psi(t) = U(t)\psi(0)\) or \(\rho_{\mathrm vec}(t) = U(t) \rho_{\mathrm vec}(0)\) where \(\rho_{\mathrm vec}\) is the vector representation of the density matrix.

Parameters:

H : qobj or list

Hamiltonian as a Qobj instance of a nested list of Qobjs and coefficients in the list-string or list-function format for time-dependent Hamiltonians (see description in qutip.mesolve).

t : float or array-like

Time or list of times for which to evaluate the propagator.

c_op_list : list

List of qobj collapse operators.

args : list/array/dictionary

Parameters to callback functions for time-dependent Hamiltonians and collapse operators.

options : qutip.Options

with options for the ODE solver.

Returns:

a : qobj

Instance representing the propagator \(U(t)\).

propagator_steadystate(U)

Find the steady state for successive applications of the propagator \(U\).

Parameters:

U : qobj

Operator representing the propagator.

Returns:

a : qobj

Instance representing the steady-state density matrix.

Time-dependent problems

rhs_generate(H, c_ops, args={}, options=<qutip.solver.Options instance at 0x2b11f5a5c950>, name=None, cleanup=True)

Generates the Cython functions needed for solving the dynamics of a given system using the mesolve function inside a parfor loop.

Parameters:

H : qobj

System Hamiltonian.

c_ops : list

list of collapse operators.

args : dict

Arguments for time-dependent Hamiltonian and collapse operator terms.

options : Options

Instance of ODE solver options.

name: str :

Name of generated RHS

cleanup: bool :

Whether the generated cython file should be automatically removed or not.

Notes

Using this function with any solver other than the mesolve function will result in an error.

rhs_clear()

Resets the string-format time-dependent Hamiltonian parameters.

Returns:Nothing, just clears data from internal config module. :

Visualization

Pseudoprobability Functions

qfunc(state, xvec, yvec, g=1.4142135623730951)

Q-function of a given 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.

g : float

Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2).

Returns:

Q : array

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

wigner(psi, xvec, yvec, method='iterative', g=1.4142135623730951, 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

Scaling factor for a = 0.5 * g * (x + iy), default g = sqrt(2).

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

Select method ‘iterative’, ‘laguerre’, or ‘fft’, where ‘iterative’ uses 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 ‘fft’ method is the preferred method for dealing with density matrices that have a large number of excitations (>~50).

parfor : bool {False, True}

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)

Graphs and Visualization

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

hinton(rho, xlabels=None, ylabels=None, title=None, ax=None)

Draws a Hinton diagram for visualizing a density matrix.

Parameters:

rho : qobj

Input density matrix.

xlabels : list of strings

list of x labels

ylabels : list of strings

list of y labels

title : string

title of the plot (optional)

ax : a matplotlib axes instance

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 a quantum object.

matrix_histogram(M, xlabels=None, ylabels=None, title=None, limits=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

xlabels : list of strings

list of x labels

ylabels : list of strings

list of y labels

title : string

title of the plot (optional)

limits : list/array with two float numbers

The z-axis limits [min, max] (optional)

ax : a matplotlib axes instance

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.

matrix_histogram_complex(M, xlabels=None, ylabels=None, title=None, limits=None, phase_limits=None, colorbar=True, fig=None, ax=None, threshold=None)

Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title.

Parameters:

M : Matrix of Qobj

The matrix to visualize

xlabels : list of strings

list of x labels

ylabels : list of strings

list of y labels

title : string

title of the plot (optional)

limits : list/array with two float numbers

The z-axis limits [min, max] (optional)

phase_limits : list/array with two float numbers

The phase-axis (colorbar) limits [min, max] (optional)

ax : a matplotlib axes instance

The axes context in which the plot will be drawn.

threshold: float (None) :

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.

Raises:

ValueError :

Input argument is not valid.

plot_energy_levels(H_list, N=0, labels=None, show_ylabels=False, figsize=(8, 12), 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.

labels : List of string

A list of labels for each Hamiltonian

show_ylabels : Bool (default False)

Show y labels to the left of energy levels of the initial Hamiltonian.

N : int

The number of energy levels to plot

figsize : tuple (int,int)

The size of the figure (width, height).

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

ax : a matplotlib axes instance

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.

wigner_cmap(W, levels=1024, shift=0, 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

Number of color levels to create.

shift : float

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

invert : bool

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.

plot_fock_distribution(rho, offset=0, fig=None, ax=None, figsize=(8, 6), title=None, unit_y_range=True)

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

Parameters:

rho : qutip.qobj.Qobj

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

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

ax : a matplotlib axes instance

The axes context in which the plot will be drawn.

title : string

An optional title for the figure.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

Returns:

fig, ax : tuple

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

plot_wigner_fock_distribution(rho, fig=None, axes=None, figsize=(8, 4), cmap=None, alpha_max=7.5, colorbar=False, method='iterative', projection='2d')

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

Parameters:

rho : qutip.qobj.Qobj

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

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

axes : a list of two matplotlib axes instances

The axes context in which the plot will be drawn.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

cmap : a matplotlib cmap instance

The colormap.

alpha_max : float

The span of the x and y coordinates (both [-alpha_max, alpha_max]).

colorbar : bool

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

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

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

projection: string {‘2d’, ‘3d’} :

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

Returns:

fig, ax : tuple

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

plot_wigner(rho, fig=None, ax=None, figsize=(8, 4), cmap=None, alpha_max=7.5, colorbar=False, method='iterative', projection='2d')

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

Parameters:

rho : qutip.qobj.Qobj

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

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

ax : a matplotlib axes instance

The axes context in which the plot will be drawn.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

cmap : a matplotlib cmap instance

The colormap.

alpha_max : float

The span of the x and y coordinates (both [-alpha_max, alpha_max]).

colorbar : bool

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

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

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

projection: string {‘2d’, ‘3d’} :

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

Returns:

fig, ax : tuple

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

sphereplot(theta, phi, values, fig=None, ax=None, save=False)

Plots a matrix of values on a sphere

Parameters:

theta : float

Angle with respect to z-axis

phi : float

Angle in x-y plane

values : array

Data set to be plotted

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

ax : a matplotlib axes instance

The axes context in which the plot will be drawn.

save : bool {False , True}

Whether to save the figure or not

Returns:

fig, ax : tuple

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

plot_schmidt(ket, splitting=None, labels_iteration=(3, 2), theme='light', fig=None, ax=None, figsize=(6, 6))

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.

Parameters:

ket : Qobj

Pure state for plotting.

splitting : int

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

theme : ‘light’ (default) or ‘dark’

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

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

The figure canvas on which the plot will be drawn.

ax : a matplotlib axis instance

The axis context in which the plot will be drawn.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

Returns:

fig, ax : tuple

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

plot_qubism(ket, theme='light', how='pairs', grid_iteration=1, legend_iteration=0, fig=None, ax=None, figsize=(6, 6))

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 2*k particles and the rest.

More information:
J. Rodriguez-Laguna, P. Migdal, M. Ibanez Berganza, M. Lewenstein, G. Sierra, “Qubism: self-similar visualization of many-body wavefunctions”, New J. Phys. 14 053028 (2012), arXiv:1112.3560, http://dx.doi.org/10.1088/1367-2630/14/5/053028 (open access)
Parameters:

ket : Qobj

Pure state for plotting.

theme : ‘light’ (default) or ‘dark’

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

how : ‘pairs’ (default), ‘pairs_skewed’ or ‘before_after’

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 (default 0) or ‘grid_iteration’ or ‘all’

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

The figure canvas on which the plot will be drawn.

ax : a matplotlib axis instance

The axis context in which the plot will be drawn.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

Returns:

fig, ax : tuple

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

plot_expectation_values(results, ylabels=, []title=None, show_legend=False, fig=None, axes=None, figsize=(8, 4))

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) qutip.solver.Result

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

ylabels : list of strings

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

title : string

The title of the figure.

show_legend : bool

Whether or not to show the legend.

fig : a matplotlib Figure instance

The Figure canvas in which the plot will be drawn.

axes : a matplotlib axes instance

The axes context in which the plot will be drawn.

figsize : (width, height)

The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).

Returns:

fig, ax : tuple

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

orbital(theta, phi, *args)

Calculates an angular wave function on a sphere. psi = orbital(theta,phi,ket1,ket2,...) calculates the angular wave function on a sphere at the mesh of points defined by theta and phi which is \(\sum_{lm} c_{lm} Y_{lm}(theta,phi)\) where \(C_{lm}\) are the coefficients specified by the list of kets. Each ket has 2l+1 components for some integer l.

Parameters:

theta : list/array

Polar angles

phi : list/array

Azimuthal angles

args : list/array

list of ket vectors.

Returns:

``array`` for angular wave function :

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 = vec2mat(U * mat2vec(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 : string

Plot title.

fig : figure instance

User defined figure instance used for generating QPT plot.

axes : list of figure axis instance

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 : string

Plot title.

fig : figure instance

User defined figure instance used for generating QPT plot.

ax : figure axis instance

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

threshold: float (None) :

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.

Quantum Information Processing

Gates

rx(phi, N=None, target=0)

Single-qubit rotation for operator sigmax with angle phi.

Returns:

result : qobj

Quantum object for operator describing the rotation.

ry(phi, N=None, target=0)

Single-qubit rotation for operator sigmay with angle phi.

Returns:

result : qobj

Quantum object for operator describing the rotation.

rz(phi, N=None, target=0)

Single-qubit rotation for operator sigmaz with angle phi.

Returns:

result : qobj

Quantum object for operator describing the rotation.

sqrtnot(N=None, target=0)

Single-qubit square root NOT gate.

Returns:

result : qobj

Quantum object for operator describing the square root NOT gate.

snot(N=None, target=0)

Quantum object representing the SNOT (Hadamard) gate.

Returns:

snot_gate : qobj

Quantum object representation of SNOT gate.

Examples

>>> snot()
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = True
Qobj data =
[[ 0.70710678+0.j  0.70710678+0.j]
 [ 0.70710678+0.j -0.70710678+0.j]]
phasegate(theta, N=None, target=0)

Returns quantum object representing the phase shift gate.

Parameters:

theta : float

Phase rotation angle.

Returns:

phase_gate : qobj

Quantum object representation of phase shift gate.

Examples

>>> phasegate(pi/4)
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 1.00000000+0.j          0.00000000+0.j        ]
 [ 0.00000000+0.j          0.70710678+0.70710678j]]
cphase(theta, N=2, control=0, target=1)

Returns quantum object representing the phase shift gate.

Parameters:

theta : float

Phase rotation angle.

N : integer

The number of qubits in the target space.

control : integer

The index of the control qubit.

target : integer

The index of the target qubit.

Returns:

U : qobj

Quantum object representation of controlled phase gate.

cnot(N=None, control=0, target=1)

Quantum object representing the CNOT gate.

Returns:

cnot_gate : qobj

Quantum object representation of CNOT gate

Examples

>>> cnot()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
    [[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]
     [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j]]
csign(N=None, control=0, target=1)

Quantum object representing the CSIGN gate.

Returns:

csign_gate : qobj

Quantum object representation of CSIGN gate

Examples

>>> csign()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
    [[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  -1.+0.j]]
berkeley(N=None, targets=[0, 1])

Quantum object representing the Berkeley gate.

Returns:

berkeley_gate : qobj

Quantum object representation of Berkeley gate

Examples

>>> berkeley()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
    [[ cos(pi/8).+0.j  0.+0.j           0.+0.j           0.+sin(pi/8).j]
     [ 0.+0.j          cos(3pi/8).+0.j  0.+sin(3pi/8).j  0.+0.j]
     [ 0.+0.j          0.+sin(3pi/8).j  cos(3pi/8).+0.j  0.+0.j]
     [ 0.+sin(pi/8).j  0.+0.j           0.+0.j           cos(pi/8).+0.j]]
swapalpha(alpha, N=None, targets=[0, 1])

Quantum object representing the SWAPalpha gate.

Returns:

swapalpha_gate : qobj

Quantum object representation of SWAPalpha gate

Examples

>>> swapalpha(alpha)
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j  0.+0.j                    0.+0.j                    0.+0.j]
 [ 0.+0.j  0.5*(1 + exp(j*pi*alpha)  0.5*(1 - exp(j*pi*alpha)  0.+0.j]
 [ 0.+0.j  0.5*(1 - exp(j*pi*alpha)  0.5*(1 + exp(j*pi*alpha)  0.+0.j]
 [ 0.+0.j  0.+0.j                    0.+0.j                    1.+0.j]]
swap(N=None, targets=[0, 1])

Quantum object representing the SWAP gate.

Returns:

swap_gate : qobj

Quantum object representation of SWAP gate

Examples

>>> swap()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = True
Qobj data =
[[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j]
 [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]]
iswap(N=None, targets=[0, 1])

Quantum object representing the iSWAP gate.

Returns:

iswap_gate : qobj

Quantum object representation of iSWAP gate

Examples

>>> iswap()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+1.j  0.+0.j]
 [ 0.+0.j  0.+1.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]]
sqrtswap(N=None, targets=[0, 1])

Quantum object representing the square root SWAP gate.

Returns:

sqrtswap_gate : qobj

Quantum object representation of square root SWAP gate

sqrtiswap(N=None, targets=[0, 1])

Quantum object representing the square root iSWAP gate.

Returns:

sqrtiswap_gate : qobj

Quantum object representation of square root iSWAP gate

Examples

>>> sqrtiswap()
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isHerm = False
Qobj data =
[[ 1.00000000+0.j   0.00000000+0.j          0.00000000+0.j          0.00000000+0.j]
 [ 0.00000000+0.j   0.70710678+0.j          0.00000000-0.70710678j  0.00000000+0.j]
 [ 0.00000000+0.j   0.00000000-0.70710678j       0.70710678+0.j          0.00000000+0.j]
 [ 0.00000000+0.j   0.00000000+0.j          0.00000000+0.j          1.00000000+0.j]]
fredkin(N=None, control=0, targets=[1, 2])

Quantum object representing the Fredkin gate.

Returns:

fredkin_gate : qobj

Quantum object representation of Fredkin gate.

Examples

>>> fredkin()
Quantum object: dims = [[2, 2, 2], [2, 2, 2]], shape = [8, 8], type = oper, isHerm = True
Qobj data =
    [[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j]]
toffoli(N=None, controls=[0, 1], target=2)

Quantum object representing the Toffoli gate.

Returns:

toff_gate : qobj

Quantum object representation of Toffoli gate.

Examples

>>> toffoli()
Quantum object: dims = [[2, 2, 2], [2, 2, 2]], shape = [8, 8], type = oper, isHerm = True
Qobj data =
    [[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j]
     [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j]]
rotation(op, phi, N=None, target=0)

Single-qubit rotation for operator op with angle phi.

Returns:

result : qobj

Quantum object for operator describing the rotation.

controlled_gate(U, N=2, control=0, target=1, control_value=1)

Create an N-qubit controlled gate from a single-qubit gate U with the given control and target qubits.

Parameters:

U : Qobj

Arbitrary single-qubit gate.

N : integer

The number of qubits in the target space.

control : integer

The index of the first control qubit.

target : integer

The index of the target qubit.

control_value : integer (1)

The state of the control qubit that activates the gate U.

Returns:

result : qobj

Quantum object representing the controlled-U gate.

globalphase(theta, N=1)

Returns quantum object representing the global phase shift gate.

Parameters:

theta : float

Phase rotation angle.

Returns:

phase_gate : qobj

Quantum object representation of global phase shift gate.

Examples

>>> phasegate(pi/4)
Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isHerm = False
Qobj data =
[[ 0.70710678+0.70710678j          0.00000000+0.j]
 [ 0.00000000+0.j          0.70710678+0.70710678j]]
hadamard_transform(N=1)

Quantum object representing the N-qubit Hadamard gate.

Returns:

q : qobj

Quantum object representation of the N-qubit Hadamard gate.

gate_sequence_product(U_list, left_to_right=True)

Calculate the overall unitary matrix for a given list of unitary operations

Parameters:

U_list : list

List of gates implementing the quantum circuit.

left_to_right: Boolean :

Check if multiplication is to be done from left to right.

Returns:

U_overall: qobj :

Overall unitary matrix of a given quantum circuit.

gate_expand_1toN(U, N, target)

Create a Qobj representing a one-qubit gate that act on a system with N qubits.

Parameters:

U : Qobj

The one-qubit gate

N : integer

The number of qubits in the target space.

target : integer

The index of the target qubit.

Returns:

gate : qobj

Quantum object representation of N-qubit gate.

gate_expand_2toN(U, N, control=None, target=None, targets=None)

Create a Qobj representing a two-qubit gate that act on a system with N qubits.

Parameters:

U : Qobj

The two-qubit gate

N : integer

The number of qubits in the target space.

control : integer

The index of the control qubit.

target : integer

The index of the target qubit.

targets : list

List of target qubits.

Returns:

gate : qobj

Quantum object representation of N-qubit gate.

gate_expand_3toN(U, N, controls=[0, 1], target=2)

Create a Qobj representing a three-qubit gate that act on a system with N qubits.

Parameters:

U : Qobj

The three-qubit gate

N : integer

The number of qubits in the target space.

controls : list

The list of the control qubits.

target : integer

The index of the target qubit.

Returns:

gate : qobj

Quantum object representation of N-qubit gate.

Qubits

qubit_states(N=1, states=[0])

Function to define initial state of the qubits.

Parameters:

N: Integer :

Number of qubits in the register.

states: List :

Initial state of each qubit.

Returns:

qstates: Qobj :

List of qubits.

Algorithms

qft(N=1)

Quantum Fourier Transform operator on N qubits.

Parameters:

N : int

Number of qubits.

Returns:

QFT: qobj :

Quantum Fourier transform operator.

qft_steps(N=1, swapping=True)

Quantum Fourier Transform operator on N qubits returning the individual steps as unitary matrices operating from left to right.

Parameters:

N: int :

Number of qubits.

swap: boolean :

Flag indicating sequence of swap gates to be applied at the end or not.

Returns:

U_step_list: list of qobj :

List of Hadamard and controlled rotation gates implementing QFT.

qft_gate_sequence(N=1, swapping=True)

Quantum Fourier Transform operator on N qubits returning the gate sequence.

Parameters:

N: int :

Number of qubits.

swap: boolean :

Flag indicating sequence of swap gates to be applied at the end or not.

Returns:

qc: instance of QubitCircuit :

Gate sequence of Hadamard and controlled rotation gates implementing QFT.

Utilitiy Functions

Graph Theory Routines

This module contains a collection of graph theory routines used mainly to reorder matrices for iterative steady state solvers.

Breadth-First-Search (BFS) of a graph in CSR or CSC matrix format starting from a given node (row). Takes Qobjs and CSR or CSC matrices as inputs.

This function requires a matrix with symmetric structure. Use A+trans(A) if original matrix is not symmetric or not sure.

Parameters:

A : csc_matrix, csr_matrix

Input graph in CSC or CSR matrix format

start : int

Staring node for BFS traversal.

Returns:

order : array

Order in which nodes are traversed from starting node.

levels : array

Level of the nodes in the order that they are traversed.

graph_degree(A)

Returns the degree for the nodes (rows) of a symmetric graph in sparse CSR or CSC format, or a qobj.

Parameters:

A : qobj, csr_matrix, csc_matrix

Input quantum object or csr_matrix.

Returns:

degree : array

Array of integers giving the degree for each node (row).

Utility Functions

This module contains utility functions that are commonly needed in other qutip modules.

n_thermal(w, w_th)

Return the number of photons in thermal equilibrium for an harmonic oscillator mode with frequency ‘w’, at the temperature described by ‘w_th’ where \(\omega_{\rm th} = k_BT/\hbar\).

Parameters:

w : float or array

Frequency of the oscillator.

w_th : float

The temperature in units of frequency (or the same units as w).

Returns:

n_avg : float or array

Return the number of average photons in thermal equilibrium for a an oscillator with the given frequency and temperature.

linspace_with(start, stop, num=50, elems=[])

Return an array of numbers sampled over specified interval with additional elements added.

Returns num spaced array with elements from elems inserted if not already included in set.

Returned sample array is not evenly spaced if addtional elements are added.

Parameters:

start : int

The starting value of the sequence.

stop : int

The stoping values of the sequence.

num : int, optional

Number of samples to generate.

elems : list/ndarray, optional

Requested elements to include in array

Returns:

samples : ndadrray

Original equally spaced sample array with additional elements added.

clebsch(j1, j2, j3, m1, m2, m3)

Calculates the Clebsch-Gordon coefficient for coupling (j1,m1) and (j2,m2) to give (j3,m3).

Parameters:

j1 : float

Total angular momentum 1.

j2 : float

Total angular momentum 2.

j3 : float

Total angular momentum 3.

m1 : float

z-component of angular momentum 1.

m2 : float

z-component of angular momentum 2.

m3 : float

z-component of angular momentum 3.

Returns:

cg_coeff : float

Requested Clebsch-Gordan coefficient.

convert_unit(value, orig='meV', to='GHz')

Convert an energy from unit orig to unit to.

Parameters:

value : float / array

The energy in the old unit.

orig : string

The name of the original unit (“J”, “eV”, “meV”, “GHz”, “mK”)

to : string

The name of the new unit (“J”, “eV”, “meV”, “GHz”, “mK”)

Returns:

value_new_unit : float / array

The energy in the new unit.

File I/O Functions

file_data_read(filename, sep=None)

Retrieves an array of data from the requested file.

Parameters:

filename : str

Name of file containing reqested data.

sep : str

Seperator used to store data.

Returns:

data : array_like

Data from selected file.

file_data_store(filename, data, numtype='complex', numformat='decimal', sep=', ')

Stores a matrix of data to a file to be read by an external program.

Parameters:

filename : str

Name of data file to be stored, including extension.

data: array_like :

Data to be written to file.

numtype : str {‘complex, ‘real’}

Type of numerical data.

numformat : str {‘decimal’,’exp’}

Format for written data.

sep : str

Single-character field seperator. Usually a tab, space, comma, or semicolon.

qload(name)

Loads data file from file named ‘filename.qu’ in current directory.

Parameters:

name : str

Name of data file to be loaded.

Returns:

qobject : instance / array_like

Object retrieved from requested file.

qsave(data, name='qutip_data')

Saves given data to file named ‘filename.qu’ in current directory.

Parameters:

data : instance/array_like

Input Python object to be stored.

filename : str

Name of output data file.

IPython Notebook Tools

This module contains utility functions for using QuTiP with IPython notebooks.

parfor(task, task_vec, args=None, client=None, view=None, show_scheduling=False, show_progressbar=False)

Call the function tast for each value in task_vec using a cluster of IPython engines. The function task should have the signature task(value, args) or task(value) if args=None.

The client and view are the IPython.parallel client and load-balanced view that will be used in the parfor execution. If these are None, new instances will be created.

Parameters:

task: a Python function :

The function that is to be called for each value in task_vec.

task_vec: array / list :

The list or array of values for which the task function is to be evaluated.

args: list / dictionary :

The optional additional argument to the task function. For example a dictionary with parameter values.

client: IPython.parallel.Client :

The IPython.parallel Client instance that will be used in the parfor execution.

view: a IPython.parallel.Client view :

The view that is to be used in scheduling the tasks on the IPython cluster. Preferably a load-balanced view, which is obtained from the IPython.parallel.Client instance client by calling, view = client.load_balanced_view().

show_scheduling: bool {False, True}, default False :

Display a graph showing how the tasks (the evaluation of task for for the value in task_vec1) was scheduled on the IPython engine cluster.

show_progressbar: bool {False, True}, default False :

Display a HTML-based progress bar duing the execution of the parfor loop.

Returns:

result : list

The result list contains the value of task(value, args) for each value in task_vec, that is, it should be equivalent to [task(v, args) for v in task_vec].

version_table()

Print an HTML-formatted table with version numbers for QuTiP and its dependencies. Use it in a IPython notebook to show which versions of different packages that were used to run the notebook. This should make it possible to reproduce the environment and the calculation later on.

Returns:

version_table: string :

Return an HTML-formatted string containing version information for QuTiP dependencies.

Miscellaneous

parfor(func, *args, **kwargs)

Executes a multi-variable function in parallel on the local machine.

Parallel execution of a for-loop over function func for multiple input arguments and keyword arguments.

Parameters:

func : function_type

A function to run in parallel on the local machine. The function ‘func’ accepts a series of arguments that are passed to the function as variables. In general, the function can have multiple input variables, and these arguments must be passed in the same order as they are defined in the function definition. In addition, the user can pass multiple keyword arguments to the function.

The following keyword argument is reserved: :

num_cpus : int

Number of CPU’s to use. Default uses maximum number of CPU’s. Performance degrades if num_cpus is larger than the physical CPU count of your machine.

Returns:

result : list

A list with length equal to number of input parameters containing the output from func.

about()

About box for qutip. Gives version numbers for QuTiP, NumPy, SciPy, Cython, and MatPlotLib.

simdiag(ops, evals=True)

Simulateous diagonalization of communting Hermitian matrices..

Parameters:

ops : list/array

list or array of qobjs representing commuting Hermitian operators.

Returns:

eigs : tuple

Tuple of arrays representing eigvecs and eigvals of quantum objects corresponding to simultaneous eigenvectors and eigenvalues for each operator.