Functions

Manipulation and Creation of States and Operators

Quantum States

basis(dimensions, n=None, offset=None, *, dtype=None)[source]

Generates the vector representation of a Fock state.

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

nint or list of ints, optional (default 0 for all dimensions)

Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match dimensions, e.g. if dimensions is a list, then n must either be omitted or a list of equal length.

offsetint or list of ints, optional (default 0 for all dimensions)

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

dtypetype or str, optional

storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateQobj

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]]
>>> basis([2,2,2], [0,1,0]) 
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = (8, 1), type = ket
Qobj data =
[[0.]
 [0.]
 [1.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]]
bell_state(state='00', *, dtype=None)[source]

Returns the selected Bell state:

\[\begin{split}\begin{aligned} \lvert B_{00}\rangle &= \frac1{\sqrt2}(\lvert00\rangle+\lvert11\rangle)\\ \lvert B_{01}\rangle &= \frac1{\sqrt2}(\lvert00\rangle-\lvert11\rangle)\\ \lvert B_{10}\rangle &= \frac1{\sqrt2}(\lvert01\rangle+\lvert10\rangle)\\ \lvert B_{11}\rangle &= \frac1{\sqrt2}(\lvert01\rangle-\lvert10\rangle)\\ \end{aligned}\end{split}\]
Parameters:
statestr [‘00’, ‘01’, ‘10’, ‘11’]

Which bell state to return

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
Bell_stateqobj

Bell state

bra(seq, dim=2, *, dtype=None)[source]

Produces a multiparticle bra state for a list or string, where each element stands for state of the respective particle.

Parameters:
seqstr / list of ints or characters

Each element defines state of the respective particle. (e.g. [1,1,0,1] or a string “1101”). For qubits it is also possible to use the following conventions:

  • ‘g’/’e’ (ground and excited state)

  • ‘u’/’d’ (spin up and down)

  • ‘H’/’V’ (horizontal and vertical polarization)

Note: for dimension > 9 you need to use a list.

dimint (default: 2) / list of ints

Space dimension for each particle: int if there are the same, list if they are different.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
braqobj

Examples

>>> bra("10") 
Quantum object: dims = [[1, 1], [2, 2]], shape = [1, 4], type = bra
Qobj data =
[[ 0.  0.  1.  0.]]
>>> bra("Hue") 
Quantum object: dims = [[1, 1, 1], [2, 2, 2]], shape = [1, 8], type = bra
Qobj data =
[[ 0.  1.  0.  0.  0.  0.  0.  0.]]
>>> bra("12", 3) 
Quantum object: dims = [[1, 1], [3, 3]], shape = [1, 9], type = bra
Qobj data =
[[ 0.  0.  0.  0.  0.  1.  0.  0.  0.]]
>>> bra("31", [5, 2]) 
Quantum object: dims = [[1, 1], [5, 2]], shape = [1, 10], type = bra
Qobj data =
[[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]]
coherent(N, alpha, offset=0, method=None, *, dtype=None)[source]

Generates a coherent state with eigenvalue alpha.

Constructed using displacement operator on vacuum state.

Parameters:
Nint

Number of Fock states in Hilbert space.

alphafloat/complex

Eigenvalue of coherent state.

offsetint, 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’.

methodstring {‘operator’, ‘analytic’}, optional

Method for generating coherent state.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateqobj

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', *, dtype=None)[source]

Density matrix representation of a coherent state.

Constructed via outer product of coherent

Parameters:
Nint

Number of basis states in Hilbert space.

alphafloat/complex

Eigenvalue for coherent state.

offsetint, default: 0

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

methodstring {‘operator’, ‘analytic’}, optional

Method for generating coherent density matrix.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
dmqobj

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(dimensions, n=None, offset=None, *, dtype=None)[source]

Bosonic Fock (number) state.

Same as basis.

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

nint or list of ints, default: 0 for all dimensions

Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match dimensions, e.g. if dimensions is a list, then n must either be omitted or a list of equal length.

offsetint or list of ints, default: 0 for all dimensions

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
Requested number state \(\left|n\right>\).

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(dimensions, n=None, offset=None, *, dtype=None)[source]

Density matrix representation of a Fock state

Constructed via outer product of basis.

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

nint or list of ints, default: 0 for all dimensions

Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match dimensions, e.g. if dimensions is a list, then n must either be omitted or a list of equal length.

offsetint or list of ints, default: 0 for all dimensions

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
dmqobj

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]]
ghz_state(N_qubit, *, dtype=None)[source]
Returns the N-qubit GHZ-state:

[ |00...00> + |11...11> ] / sqrt(2)

Parameters:
N_qubitint

Number of qubits in state

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
Gqobj

N-qubit GHZ-state

ket(seq, dim=2, *, dtype=None)[source]

Produces a multiparticle ket state for a list or string, where each element stands for state of the respective particle.

Parameters:
seqstr / list of ints or characters

Each element defines state of the respective particle. (e.g. [1,1,0,1] or a string “1101”). For qubits it is also possible to use the following conventions: - ‘g’/’e’ (ground and excited state) - ‘u’/’d’ (spin up and down) - ‘H’/’V’ (horizontal and vertical polarization) Note: for dimension > 9 you need to use a list.

dimint or list of ints, default: 2

Space dimension for each particle: int if there are the same, list if they are different.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
ketqobj

Examples

>>> ket("10") 
Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket
Qobj data =
[[ 0.]
 [ 0.]
 [ 1.]
 [ 0.]]
>>> ket("Hue") 
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
Qobj data =
[[ 0.]
 [ 1.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]]
>>> ket("12", 3) 
Quantum object: dims = [[3, 3], [1, 1]], shape = [9, 1], type = ket
Qobj data =
[[ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 1.]
 [ 0.]
 [ 0.]
 [ 0.]]
>>> ket("31", [5, 2]) 
Quantum object: dims = [[5, 2], [1, 1]], shape = [10, 1], type = ket
Qobj data =
[[ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 1.]
 [ 0.]
 [ 0.]]
ket2dm(Q)[source]

Takes input ket or bra vector and returns density matrix formed by outer product. This is completely identical to calling Q.proj().

Parameters:
QQobj

Ket or bra type quantum object.

Returns:
dmQobj

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]]
maximally_mixed_dm(dimensions, *, dtype=None)[source]

Returns the maximally mixed density matrix for a Hilbert space of dimension N.

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
dmQobj

Thermal state density matrix.

phase_basis(N, m, phi0=0, *, dtype=None)[source]

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

Parameters:
Nint

Number of basis states in Hilbert space.

mint

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

phi0float, default: 0

Reference phase angle.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateqobj

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.

projection(dimensions, n, m, offset=None, *, dtype=None)[source]

The projection operator that projects state \(\lvert m\rangle\) on state \(\lvert n\rangle\).

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

n, mint

The number states in the projection.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Requested projection operator.

qutrit_basis(*, dtype=None)[source]

Basis states for a three level system (qutrit)

dtypetype or str, optional

storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
qstatesarray

Array of qutrit basis vectors

singlet_state(*, dtype=None)[source]

Returns the two particle singlet-state:

\[\lvert S\rangle = \frac1{\sqrt2}(\lvert01\rangle-\lvert10\rangle)\]

that is identical to the fourth bell state.

Parameters:
dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
Bell_stateqobj

\(\lvert B_{11}\rangle\) Bell state

spin_coherent(j, theta, phi, type='ket', *, dtype=None)[source]

Generate the coherent spin state \(\lvert \theta, \phi\rangle\).

Parameters:
jfloat

The spin of the state.

thetafloat

Angle from z axis.

phifloat

Angle from x axis.

typestring {‘ket’, ‘bra’, ‘dm’}, default: ‘ket’

Type of state to generate.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateqobj

Qobj quantum object for spin coherent state

spin_state(j, m, type='ket', *, dtype=None)[source]

Generates the spin state \(\lvert j, m\rangle\), i.e. the eigenstate of the spin-j Sz operator with eigenvalue m.

Parameters:
jfloat

The spin of the state ().

mint

Eigenvalue of the spin-j Sz operator.

typestring {‘ket’, ‘bra’, ‘dm’}, default: ‘ket’

Type of state to generate.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateqobj

Qobj quantum object for spin state

state_index_number(dims, index)[source]

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:
dimslist or array

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

indexinteger

The index of the state in standard enumeration ordering.

Returns:
statetuple

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

state_number_enumerate(dims, excitations=None)[source]

An iterator that enumerates all the state number tuples (quantum numbers of 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:
dimslist or array

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

excitationsinteger, optional

Restrict state space to states with excitation numbers below or equal to this value.

Returns:
state_numbertuple

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

state_number_index(dims, state)[source]

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
Parameters:
dimslist or array

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

statelist

State number array.

Returns:
idxint

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

state_number_qobj(dims, state, *, dtype=None)[source]

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

Note

Deprecated in QuTiP 5.0, use basis instead.

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:
dimslist or array

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

statelist

State number array.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
stateQobj

The state as a Qobj instance.

thermal_dm(N, n, method='operator', *, dtype=None)[source]

Density matrix for a thermal state of n particles

Parameters:
Nint

Number of basis states in Hilbert space.

nfloat

Expectation value for number of particles in thermal state.

methodstring {‘operator’, ‘analytic’}, default: ‘operator’

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
dmqobj

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]]
triplet_states(*, dtype=None)[source]

Returns a list of the two particle triplet-states:

\[\lvert T_1\rangle = \lvert11\rangle \lvert T_2\rangle = \frac1{\sqrt2}(\lvert01\rangle + \lvert10\rangle) \lvert T_3\rangle = \lvert00\rangle\]
Parameters:
dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
trip_stateslist

2 particle triplet states

w_state(N_qubit, *, dtype=None)[source]
Returns the N-qubit W-state:

[ |100..0> + |010..0> + |001..0> + ... |000..1> ] / sqrt(n)

Parameters:
N_qubitint

Number of qubits in state

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
WQobj

N-qubit W-state

zero_ket(dimensions, *, dtype=None)[source]

Creates the zero ket vector with shape Nx1 and dimensions dims.

Parameters:
dimensionsint or list of ints, Space

Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
zero_ketqobj

Zero ket on given Hilbert space.

Quantum Operators

This module contains functions for generating Qobj representation of a variety of commonly occuring quantum operators.

charge(Nmax, Nmin=None, frac=1, *, dtype=None)[source]

Generate the diagonal charge operator over charge states from Nmin to Nmax.

Parameters:
Nmaxint

Maximum charge state to consider.

Nminint, default: -Nmax

Lowest charge state to consider.

fracfloat, default: 1

Specify fractional charge if needed.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
CQobj

Charge operator over [Nmin, Nmax].

Notes

New in version 3.2.

commutator(A, B, kind='normal')[source]

Return the commutator of kind kind (normal, anti) of the two operators A and B.

Parameters:
A, BQobj, QobjEvo

The operators to compute the commutator of.

kind: str {“normal”, “anti”}, default: “anti”

Which kind of commutator to compute.

create(N, offset=0, *, dtype=None)[source]

Creation (raising) operator.

Parameters:
Nint

Number of basis states in the Hilbert space.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Qobj for raising 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, *, dtype=None)[source]

Destruction (lowering) operator.

Parameters:
Nint

Number of basis states in the Hilbert space.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

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, *, dtype=None)[source]

Single-mode displacement operator.

Parameters:
Nint

Number of basis states in the Hilbert space.

alphafloat/complex

Displacement amplitude.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

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]]
fcreate(n_sites, site, dtype=None)[source]

Fermionic creation operator. We use the Jordan-Wigner transformation, making use of the Jordan-Wigner ZZ..Z strings, to construct this as follows:

\[a_j = \sigma_z^{\otimes j} \otimes (\frac{\sigma_x - i \sigma_y}{2}) \otimes I^{\otimes N-j-1}\]
Parameters:
n_sitesint

Number of sites in Fock space.

siteint

The site in Fock space to add a fermion to. Corresponds to j in the above JW transform.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Qobj for raising operator.

Examples

>>> fcreate(2) 
Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4),     type = oper, isherm = False
Qobj data =
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]]
fdestroy(n_sites, site, dtype=None)[source]

Fermionic destruction operator. We use the Jordan-Wigner transformation, making use of the Jordan-Wigner ZZ..Z strings, to construct this as follows:

\[a_j = \sigma_z^{\otimes j} \otimes (\frac{\sigma_x + i \sigma_y}{2}) \otimes I^{\otimes N-j-1}\]
Parameters:
n_sitesint

Number of sites in Fock space.

siteint, default: 0

The site in Fock space to add a fermion to. Corresponds to j in the above JW transform.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Qobj for destruction operator.

Examples

>>> fdestroy(2) 
Quantum object: dims=[[2 2], [2 2]], shape=(4, 4),     type='oper', isherm=False
Qobj data =
[[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
identity(dimensions, *, dtype=None)

Identity operator.

Parameters:
dimensions(int) or (list of int) or (list of list of int), Space

Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

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.]]
>>> qeye([2,2]) 
Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4), type = oper, isherm = True
Qobj data =
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
jmat(j, which=None, *, dtype=None)[source]

Higher-order spin operators:

Parameters:
jfloat

Spin of operator

whichstr, optional

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
jmatQobj or tuple of Qobj

qobj for requested spin operator(s).

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.]]]
momentum(N, offset=0, *, dtype=None)[source]

Momentum operator p=-1j/sqrt(2)*(a-a.dag())

Parameters:
Nint

Number of basis states in the Hilbert space.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Momentum operator as Qobj.

num(N, offset=0, *, dtype=None)[source]

Quantum object for number operator.

Parameters:
Nint

Number of basis states in the Hilbert space.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

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]]
phase(N, phi0=0, *, dtype=None)[source]

Single-mode Pegg-Barnett phase operator.

Parameters:
Nint

Number of basis states in the Hilbert space.

phi0float, default: 0

Reference phase.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Phase operator with respect to reference phase.

Notes

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

position(N, offset=0, *, dtype=None)[source]

Position operator \(x = 1 / sqrt(2) * (a + a.dag())\)

Parameters:
Nint

Number of basis states in the Hilbert space.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Position operator as Qobj.

qdiags(diagonals, offsets=None, dims=None, shape=None, *, dtype=None)[source]

Constructs an operator from an array of diagonals.

Parameters:
diagonalssequence of array_like

Array of elements to place along the selected diagonals.

offsetssequence of ints, optional
Sequence for diagonals to be set:
  • k=0 main diagonal

  • k>0 kth upper diagonal

  • k<0 kth lower diagonal

dimslist, optional

Dimensions for operator

shapelist, tuple, optional

Shape of operator. If omitted, a square operator large enough to contain the diagonals is generated.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Examples

>>> qdiags(sqrt(range(1, 4)), 1) 
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isherm = False
Qobj data =
[[ 0.          1.          0.          0.        ]
 [ 0.          0.          1.41421356  0.        ]
 [ 0.          0.          0.          1.73205081]
 [ 0.          0.          0.          0.        ]]
qeye(dimensions, *, dtype=None)[source]

Identity operator.

Parameters:
dimensions(int) or (list of int) or (list of list of int), Space

Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

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.]]
>>> qeye([2,2]) 
Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4), type = oper, isherm = True
Qobj data =
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
qeye_like(qobj)[source]

Identity operator with the same dims and type as the reference quantum object.

Parameters:
qobjQobj, QobjEvo

Reference quantum object to copy the dims from.

Returns:
operqobj

Identity operator Qobj.

qutrit_ops(*, dtype=None)[source]

Operators for a three level system (qutrit).

Parameters:
dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opers: array

array of qutrit operators.

qzero(dimensions, dims_right=None, *, dtype=None)[source]

Zero operator.

Parameters:
dimensionsint, list of int, list of list of int, Space

Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

dims_rightint, list of int, list of list of int, Space, optional

Number of basis states in the right Hilbert space when the operator is rectangular.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
qzeroqobj

Zero operator Qobj.

qzero_like(qobj)[source]

Zero operator of the same dims and type as the reference.

Parameters:
qobjQobj, QobjEvo

Reference quantum object to copy the dims from.

Returns:
qzeroqobj

Zero operator Qobj.

sigmam()[source]

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()[source]

Creation operator for Pauli spins.

Examples

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

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()[source]

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()[source]

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.]]
spin_Jm(j, *, dtype=None)[source]

Spin-j annihilation operator

Parameters:
jfloat

Spin of operator

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

qobj representation of the operator.

spin_Jp(j, *, dtype=None)[source]

Spin-j creation operator

Parameters:
jfloat

Spin of operator

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

qobj representation of the operator.

spin_Jx(j, *, dtype=None)[source]

Spin-j x operator

Parameters:
jfloat

Spin of operator

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

qobj representation of the operator.

spin_Jy(j, *, dtype=None)[source]

Spin-j y operator

Parameters:
jfloat

Spin of operator

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

qobj representation of the operator.

spin_Jz(j, *, dtype=None)[source]

Spin-j z operator

Parameters:
jfloat

Spin of operator

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

qobj representation of the operator.

squeeze(N, z, offset=0, *, dtype=None)[source]

Single-mode squeezing operator.

Parameters:
Nint

Dimension of hilbert space.

zfloat/complex

Squeezing parameter.

offsetint, default: 0

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

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operQobj

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)[source]

Generalized squeezing operator.

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

Operator 1.

a2Qobj

Operator 2.

zfloat/complex

Squeezing parameter.

Returns:
operQobj

Squeezing operator.

tunneling(N, m=1, *, dtype=None)[source]

Tunneling operator with elements of the form \(\\sum |N><N+m| + |N+m><N|\).

Parameters:
Nint

Number of basis states in the Hilbert space.

mint, default: 1

Number of excitations in tunneling event.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
TQobj

Tunneling operator.

Energy Restricted Operators

enr_destroy(dims, excitations, *, dtype=None)[source]

Generate annilation operators for modes in a excitation-number-restricted state space. For example, consider a system consisting of 4 modes, each with 5 states. The total hilbert space size is 5**4 = 625. If we are only interested in states that contain up to 2 excitations, we only need to include states such as

(0, 0, 0, 0) (0, 0, 0, 1) (0, 0, 0, 2) (0, 0, 1, 0) (0, 0, 1, 1) (0, 0, 2, 0) …

This function creates annihilation operators for the 4 modes that act within this state space:

a1, a2, a3, a4 = enr_destroy([5, 5, 5, 5], excitations=2)

From this point onwards, the annihiltion operators a1, …, a4 can be used to setup a Hamiltonian, collapse operators and expectation-value operators, etc., following the usual pattern.

Parameters:
dimslist

A list of the dimensions of each subsystem of a composite quantum system.

excitationsinteger

The maximum number of excitations that are to be included in the state space.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
a_opslist of qobj

A list of annihilation operators for each mode in the composite quantum system described by dims.

enr_fock(dims, excitations, state, *, dtype=None)[source]

Generate the Fock state representation in a excitation-number restricted state space. The dims argument is a list of integers that define the number of quantums states of each component of a composite quantum system, and the excitations specifies the maximum number of excitations for the basis states that are to be included in the state space. The state argument is a tuple of integers that specifies the state (in the number basis representation) for which to generate the Fock state representation.

Parameters:
dimslist

A list of the dimensions of each subsystem of a composite quantum system.

excitationsinteger

The maximum number of excitations that are to be included in the state space.

statelist of integers

The state in the number basis representation.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
ketQobj

A Qobj instance that represent a Fock state in the exication-number- restricted state space defined by dims and exciations.

enr_identity(dims, excitations, *, dtype=None)[source]

Generate the identity operator for the excitation-number restricted state space defined by the dims and exciations arguments. See the docstring for enr_fock for a more detailed description of these arguments.

Parameters:
dimslist

A list of the dimensions of each subsystem of a composite quantum system.

excitationsinteger

The maximum number of excitations that are to be included in the state space.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
opQobj

A Qobj instance that represent the identity operator in the exication-number-restricted state space defined by dims and exciations.

enr_state_dictionaries(dims, excitations)[source]

Return the number of states, and lookup-dictionaries for translating a state tuple to a state index, and vice versa, for a system with a given number of components and maximum number of excitations.

Parameters:
dims: list

A list with the number of states in each sub-system.

excitationsinteger

The maximum numbers of dimension

Returns:
nstates, state2idx, idx2state: integer, dict, dict

The number of states nstates, a dictionary for looking up state indices from a state tuple, and a dictionary for looking up state state tuples from state indices. state2idx and idx2state are reverses of each other, i.e., state2idx[idx2state[idx]] = idx and idx2state[state2idx[state]] = state.

enr_thermal_dm(dims, excitations, n, *, dtype=None)[source]

Generate the density operator for a thermal state in the excitation-number- restricted state space defined by the dims and exciations arguments. See the documentation for enr_fock for a more detailed description of these arguments. The temperature of each mode in dims is specified by the average number of excitatons n.

Parameters:
dimslist

A list of the dimensions of each subsystem of a composite quantum system.

excitationsinteger

The maximum number of excitations that are to be included in the state space.

ninteger

The average number of exciations in the thermal state. n can be a float (which then applies to each mode), or a list/array of the same length as dims, in which each element corresponds specifies the temperature of the corresponding mode.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
dmQobj

Thermal state density matrix.

Quantum Objects

The Quantum Object (Qobj) class, for representing quantum states and operators, and related functions.

ptrace(Q, sel)[source]

Partial trace of the Qobj with selected components remaining.

Parameters:
QQobj

Composite quantum object.

selint/list

An int or list of components to keep after partial trace.

Returns:
operQobj

Quantum object representing partial trace with selected components remaining.

Notes

This function is for legacy compatibility only. It is recommended to use the ptrace() Qobj method.

Random Operators and States

This module is a collection of random state and operator generators.

rand_dm(dimensions, density=0.75, distribution='ginibre', *, eigenvalues=(), rank=None, seed=None, dtype=None)[source]

Creates a random density matrix of the desired dimensions.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

densityfloat, default: 0.75

Density between [0,1] of output density matrix. Used by the “pure”, “eigen” and “herm”.

distribution : str {“ginibre”, “hs”, “pure”, “eigen”, “uniform”},

default: “ginibre”

Method used to obtain the density matrices.

  • “ginibre” : Ginibre random density operator of rank rank by using the algorithm of [BCSZ08].

  • “hs” : Hilbert-Schmidt ensemble, equivalent to a full rank ginibre operator.

  • “pure” : Density matrix created from a random ket.

  • “eigen” : A density matrix with the given eigenvalues.

  • “herm” : Build from a random hermitian matrix using rand_herm.

eigenvaluesarray_like, optional

Eigenvalues of the output Hermitian matrix. The len must match the shape of the matrix.

rankint, optional

When using the “ginibre” distribution, rank of the density matrix. Will default to a full rank operator when not provided.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Density matrix quantum operator.

rand_herm(dimensions, density=0.3, distribution='fill', *, eigenvalues=(), seed=None, dtype=None)[source]

Creates a random sparse Hermitian quantum object.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

densityfloat, default: 0.30

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

distributionstr {“fill”, “pos_def”, “eigen”}, default: “fill”

Method used to obtain the density matrices.

  • “fill” : Uses \(H=0.5*(X+X^{+})\) where \(X\) is a randomly generated quantum operator with elements uniformly distributed between [-1, 1] + [-1j, 1j].

  • “eigen” : A density matrix with the given eigenvalues. It uses random complex Jacobi rotations to shuffle the operator.

  • “pos_def” : Return a positive semi-definite matrix by diagonal dominance.

eigenvaluesarray_like, optional

Eigenvalues of the output Hermitian matrix. The len must match the shape of the matrix.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operQobj

Hermitian quantum operator.

Notes

If given a list of eigenvalues the object is created using complex Jacobi rotations. While this method is fast for small matrices, it should not be repeatedly used for generating matrices larger than ~1000x1000.

rand_ket(dimensions, density=1, distribution='haar', *, seed=None, dtype=None)[source]

Creates a random ket vector.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

densityfloat, default: 1

Density between [0,1] of output ket state when using the fill method.

distributionstr {“haar”, “fill”}, default: “haar”

Method used to obtain the kets.

  • haar : Haar random pure state obtained by applying a Haar random unitary to a fixed pure state.

  • fill : Fill the ket with uniformly distributed random complex number.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Ket quantum state vector.

rand_kraus_map(dimensions, *, seed=None, dtype=None)[source]

Creates a random CPTP map on an N-dimensional Hilbert space in Kraus form.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
oper_listlist of qobj

N^2 x N x N qobj operators.

rand_stochastic(dimensions, density=0.75, kind='left', *, seed=None, dtype=None)[source]

Generates a random stochastic matrix.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

densityfloat, default: 0.75

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

kindstr {“left”, “right”}, default: “left”

Generate ‘left’ or ‘right’ stochastic matrix.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Quantum operator form of stochastic matrix.

rand_super(dimensions, *, superrep='super', seed=None, dtype=None)[source]

Returns a randomly drawn superoperator acting on operators acting on N dimensions.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

superropstr, default: “super”

Representation of the super operator

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

rand_super_bcsz(dimensions, enforce_tp=True, rank=None, *, superrep='super', seed=None, dtype=None)[source]

Returns a random superoperator drawn from the Bruzda et al ensemble for CPTP maps [BCSZ08]. Note that due to finite numerical precision, for ranks less than full-rank, zero eigenvalues may become slightly negative, such that the returned operator is not actually completely positive.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If an int is provided, it is understood as the Square root of the dimension of the superoperator to be returned, with the corresponding dims as [[[N],[N]], [[N],[N]]]. If provided as a list of ints, then the dimensions is understood as the space of density matrices this superoperator is applied to: dimensions=[2,2] dims=[[[2,2],[2,2]], [[2,2],[2,2]]].

enforce_tpbool, default: True

If True, the trace-preserving condition of [BCSZ08] is enforced; otherwise only complete positivity is enforced.

rankint, optional

Rank of the sampled superoperator. If None, a full-rank superoperator is generated.

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

superropstr, default: “super”

representation of the

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
rhoQobj

A superoperator acting on vectorized dim × dim density operators, sampled from the BCSZ distribution.

rand_unitary(dimensions, density=1, distribution='haar', *, seed=None, dtype=None)[source]

Creates a random sparse unitary quantum object.

Parameters:
dimensions(int) or (list of int) or (list of list of int)

Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the dims property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

densityfloat, default: 1

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

distributionstr {“haar”, “exp”}, default: “haar”

Method used to obtain the unitary matrices.

  • haar : Haar random unitary matrix using the algorithm of [Mez07].

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

seedint, SeedSequence, Generator, optional

Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

dtypetype or str, optional

Storage representation. Any data-layer known to qutip.data.to is accepted.

Returns:
operqobj

Unitary quantum operator.

Superoperators and Liouvillians

lindblad_dissipator(a, b=None, data_only=False, chi=None)[source]

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:
aQobj or QobjEvo

Left part of collapse operator.

bQobj or QobjEvo, optional

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

chifloat, optional

In some systems it is possible to determine the statistical moments (mean, variance, etc) of the probability distribution of the occupation numbers of states by numerically evaluating the derivatives of the steady state occupation probability as a function of an artificial phase parameter chi which multiplies the a \rho a^dagger term of the dissipator by e ^ (i * chi). The factor e ^ (i * chi) is introduced via the generating function of the statistical moments. For examples of the technique, see Full counting statistics of nano-electromechanical systems and Photon-mediated electron transport in hybrid circuit-QED. This parameter is deprecated and may be removed in QuTiP 5.

data_onlybool, default: False

Return the data object instead of a Qobj

Returns:
Dqobj, QobjEvo

Lindblad dissipator superoperator.

liouvillian(H=None, c_ops=None, data_only=False, chi=None)[source]

Assembles the Liouvillian superoperator from a Hamiltonian and a list of collapse operators.

Parameters:
HQobj or QobjEvo, optional

System Hamiltonian or Hamiltonian component of a Liouvillian. Considered 0 if not given.

c_opsarray_like of Qobj or QobjEvo, optional

A list or array of collapse operators.

data_onlybool, default: False

Return the data object instead of a Qobj

chiarray_like of float, optional

In some systems it is possible to determine the statistical moments (mean, variance, etc) of the probability distributions of occupation of various states by numerically evaluating the derivatives of the steady state occupation probability as a function of artificial phase parameters chi which are included in the lindblad_dissipator for each collapse operator. See the documentation of lindblad_dissipator for references and further details. This parameter is deprecated and may be removed in QuTiP 5.

Returns:
LQobj or QobjEvo

Liouvillian superoperator.

operator_to_vector(op)[source]

Create a vector representation given a quantum operator in matrix form. The passed object should have a Qobj.type of ‘oper’ or ‘super’; this function is not designed for general-purpose matrix reshaping.

Parameters:
opQobj or QobjEvo

Quantum operator in matrix form. This must have a type of ‘oper’ or ‘super’.

Returns:
Qobj or QobjEvo

The same object, but re-cast into a column-stacked-vector form of type ‘operator-ket’. The output is the same type as the passed object.

spost(A)[source]

Superoperator formed from post-multiplication by operator A

Parameters:
AQobj or QobjEvo

Quantum operator for post multiplication.

Returns:
superQobj or QobjEvo

Superoperator formed from input qauntum object.

spre(A)[source]

Superoperator formed from pre-multiplication by operator A.

Parameters:
AQobj or QobjEvo

Quantum operator for pre-multiplication.

Returns:
super :Qobj or QobjEvo

Superoperator formed from input quantum object.

sprepost(A, B)[source]

Superoperator formed from pre-multiplication by A and post-multiplication by B.

Parameters:
AQobj or QobjEvo

Quantum operator for pre-multiplication.

BQobj or QobjEvo

Quantum operator for post-multiplication.

Returns:
superQobj or QobjEvo

Superoperator formed from input quantum objects.

vector_to_operator(op)[source]

Create a matrix representation given a quantum operator in vector form. The passed object should have a Qobj.type of ‘operator-ket’; this function is not designed for general-purpose matrix reshaping.

Parameters:
opQobj or QobjEvo

Quantum operator in column-stacked-vector form. This must have a type of ‘operator-ket’.

Returns:
Qobj or QobjEvo

The same object, but re-cast into “standard” operator form. The output is the same type as the passed object.

Superoperator Representations

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

kraus_to_choi(kraus_ops)[source]

Convert a list of Kraus operators into Choi representation of the channel.

Essentially, kraus operators are a decomposition of a Choi matrix, and its reconstruction from them should go as \(E = \sum_{i} |K_i\rangle\rangle \langle\langle K_i|\), where we use vector representation of Kraus operators.

Parameters:
kraus_opslist[Qobj]

The list of Kraus operators to be converted to Choi representation.

Returns:
choiQobj

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

kraus_to_super(kraus_list)[source]

Convert a list of Kraus operators to a superoperator.

Parameters:
kraus_listlist of Qobj

The list of Kraus super operators to convert.

to_chi(q_oper)[source]

Converts a Qobj representing a quantum map to a representation as a chi (process) matrix in the Pauli basis, such that the trace of the returned operator is equal to the dimension of the system.

Parameters:
q_operQobj

Superoperator to be converted to Chi representation. If q_oper is type="oper", then it is taken to act by conjugation, such that to_chi(A) == to_chi(sprepost(A, A.dag())).

Returns:
chiQobj

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

Raises:
TypeError:

If the given quantum object is not a map, or cannot be converted to Chi representation.

to_choi(q_oper)[source]

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_operQobj

Superoperator to be converted to Choi representation. If q_oper is type="oper", then it is taken to act by conjugation, such that to_choi(A) == to_choi(sprepost(A, A.dag())).

Returns:
choiQobj

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_kraus(q_oper, tol=1e-09)[source]

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_operQobj

Superoperator to be converted to Kraus representation. If q_oper is type="oper", then it is taken to act by conjugation, such that to_kraus(A) == to_kraus(sprepost(A, A.dag())) == [A].

tolFloat, default: 1e-9

Optional threshold parameter for eigenvalues/Kraus ops to be discarded.

Returns:
kraus_opslist 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.

to_stinespring(q_oper, threshold=1e-10)[source]

Converts a Qobj representing a quantum map \(\Lambda\) to a pair of partial isometries A and B such that \(\Lambda(X) = \Tr_2(A X B^\dagger)\) for all inputs X, where the partial trace is taken over a a new index on the output dimensions of A and B.

For completely positive inputs, A will always equal B up to precision errors.

Parameters:
q_operQobj

Superoperator to be converted to a Stinespring pair.

thresholdfloat, default: 1e-10

Threshold parameter for eigenvalues/Kraus ops to be discarded.

Returns:
A, BQobj

Quantum objects representing each of the Stinespring matrices for the input Qobj.

to_super(q_oper)[source]

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

Parameters:
q_operQobj

Superoperator to be converted to supermatrix representation. If q_oper is type="oper", then it is taken to act by conjugation, such that to_super(A) == sprepost(A, A.dag()).

Returns:
superopQobj

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.

Operators and Superoperator Dimensions

Internal use module for manipulating dims specifications.

from_tensor_rep(tensorrep, dims)[source]

Reverse operator of to_tensor_rep. Create a Qobj From a N-dimensions numpy array and dimensions with N indices.

Parameters:
tensorrep: ndarray

Numpy array with one dimension for each index in dims.

dims: list of list, Dimensions

Dimensions of the Qobj.

Returns:
Qobj

Re constructed Qobj

to_tensor_rep(q_oper)[source]

Transform a Qobj to a numpy array whose shape is the flattened dimensions.

Parameters:
q_oper: Qobj

Object to reshape

Returns:
ndarray:

Numpy array with one dimension for each index in dims.

Examples

>>> ket.dims
[[2, 3], [1]]
>>> to_tensor_rep(ket).shape
(2, 3, 1)
>>> oper.dims
[[2, 3], [2, 3]]
>>> to_tensor_rep(oper).shape
(2, 3, 2, 3)
>>> super_oper.dims
[[[2, 3], [2, 3]], [[2, 3], [2, 3]]]
>>> to_tensor_rep(super_oper).shape
(2, 3, 2, 3, 2, 3, 2, 3)

Functions acting on states and operators

Expectation Values

expect(oper, state)[source]

Calculate the expectation value for operator(s) and state(s). The expectation of state k on operator A is defined as k.dag() @ A @ k, and for density matrix R on operator A it is trace(A @ R).

Parameters:
operqobj/array-like

A single or a list of operators for expectation value.

stateqobj/array-like

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

Returns:
exptfloat/complex/array-like

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

Examples

>>> expect(num(4), basis(4, 3)) == 3 
    True
variance(oper, state)[source]

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

Parameters:
operqobj

Operator for expectation value.

stateqobj/list

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

Returns:
varfloat

Variance of operator ‘oper’ for given state.

Tensor

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

composite(*args)[source]

Given two or more operators, kets or bras, returns the Qobj corresponding to a composite system over each argument. For ordinary operators and vectors, this is the tensor product, while for superoperators and vectorized operators, this is the column-reshuffled tensor product.

If a mix of Qobjs supported on Hilbert and Liouville spaces are passed in, the former are promoted. Ordinary operators are assumed to be unitaries, and are promoted using to_super, while kets and bras are promoted by taking their projectors and using operator_to_vector(ket2dm(arg)).

super_tensor(*args)[source]

Calculate the tensor product of input superoperators, by tensoring together the underlying Hilbert spaces on which each vectorized operator acts.

Parameters:
argsarray_like

list or array of quantum objects with type="super".

Returns:
objqobj

A composite quantum object.

tensor(*args)[source]

Calculates the tensor product of input operators.

Parameters:
argsarray_like

list or array of quantum objects for tensor product.

Returns:
objqobj

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]]
tensor_contract(qobj, *pairs)[source]

Contracts a qobj along one or more index pairs. Note that this uses dense representations and thus should not be used for very large Qobjs.

Parameters:
qobj: Qobj

Operator to contract subspaces on.

pairstuple

One or more tuples (i, j) indicating that the i and j dimensions of the original qobj should be contracted.

Returns:
cqobjQobj

The original Qobj with all named index pairs contracted away.

Partial Transpose

partial_transpose(rho, mask, method='dense')[source]

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

A density matrix.

masklist / array

A mask that selects which subsystems should be transposed.

methodstr {“dense”, “sparse”}, default: “dense”

Choice of method. The “sparse” implementation can be faster for large and sparse systems (hundreds of quantum states).

Returns:
rho_pr: Qobj

A density matrix with the selected subsystems transposed.

Entropy Functions

concurrence(rho)[source]

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

Parameters:
stateqobj

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

Returns:
concurfloat

Concurrence

References

[1]

https://en.wikipedia.org/wiki/Concurrence_(quantum_computing)

entropy_conditional(rho, selB, base=2.718281828459045, sparse=False)[source]

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

Parameters:
rhoqobj

Density matrix of composite object

selBint/list

Selected components for density matrix B

base{e, 2}, default: e

Base of logarithm.

sparsebool, default: False

Use sparse eigensolver.

Returns:
ent_condfloat

Value of conditional entropy

entropy_linear(rho)[source]

Linear entropy of a density matrix.

Parameters:
rhoqobj

sensity matrix or ket/bra vector.

Returns:
entropyfloat

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)[source]

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

Parameters:
rhoqobj

Density matrix for composite quantum systems

selAint/list

int or list of first selected density matrix components.

selBint/list

int or list of second selected density matrix components.

base{e, 2}, default: e

Base of logarithm.

sparsebool, default: False

Use sparse eigensolver.

Returns:
ent_mutfloat

Mutual information between selected components.

entropy_relative(rho, sigma, base=2.718281828459045, sparse=False, tol=1e-12)[source]

Calculates the relative entropy S(rho||sigma) between two density matrices.

Parameters:
rhoQobj

First density matrix (or ket which will be converted to a density matrix).

sigmaQobj

Second density matrix (or ket which will be converted to a density matrix).

base{e, 2}, default: e

Base of logarithm. Defaults to e.

sparsebool, default: False

Flag to use sparse solver when determining the eigenvectors of the density matrices. Defaults to False.

tolfloat, default: 1e-12

Tolerance to use to detect 0 eigenvalues or dot producted between eigenvectors. Defaults to 1e-12.

Returns:
rel_entfloat

Value of relative entropy. Guaranteed to be greater than zero and should equal zero only when rho and sigma are identical.

References

See Nielsen & Chuang, “Quantum Computation and Quantum Information”, Section 11.3.1, pg. 511 for a detailed explanation of quantum relative entropy.

Examples

First we define two density matrices:

>>> rho = qutip.ket2dm(qutip.ket("00"))
>>> sigma = rho + qutip.ket2dm(qutip.ket("01"))
>>> sigma = sigma.unit()

Then we calculate their relative entropy using base 2 (i.e. log2) and base e (i.e. log).

>>> qutip.entropy_relative(rho, sigma, base=2)
1.0
>>> qutip.entropy_relative(rho, sigma)
0.6931471805599453
entropy_vn(rho, base=2.718281828459045, sparse=False)[source]

Von-Neumann entropy of density matrix

Parameters:
rhoqobj

Density matrix.

base{e, 2}, default: e

Base of logarithm.

sparsebool, default: False

Use sparse eigensolver.

Returns:
entropyfloat

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.

average_gate_fidelity(oper, target=None)[source]

Returns the average gate fidelity of a quantum channel to the target channel, or to the identity channel if no target is given.

Parameters:
operQobj/list

A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

targetQobj

A unitary operator

Returns:
fidfloat

Average gate fidelity between oper and target, or between oper and identity.

Notes

The average gate fidelity is defined for example in: A. Gilchrist, N.K. Langford, M.A. Nielsen, Phys. Rev. A 71, 062310 (2005). The definition of state fidelity that the average gate fidelity is based on is the one from R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994). It is the square of the fidelity implemented in qutip.core.metrics.fidelity which follows Nielsen & Chuang, “Quantum Computation and Quantum Information”

bures_angle(A, B)[source]

Returns the Bures Angle between two density matrices A & B.

The Bures angle ranges from 0, for states with unit fidelity, to pi/2.

Parameters:
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

Returns:
anglefloat

Bures angle between density matrices.

bures_dist(A, B)[source]

Returns the Bures distance between two density matrices A & B.

The Bures distance ranges from 0, for states with unit fidelity, to sqrt(2).

Parameters:
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

Returns:
distfloat

Bures distance between density matrices.

dnorm(A, B=None, solver='CVXOPT', verbose=False, force_solve=False, sparse=True)[source]

Calculates the diamond norm of the quantum map q_oper, using the simplified semidefinite program of [Wat13].

The diamond norm SDP is solved by using CVXPY.

Parameters:
AQobj

Quantum map to take the diamond norm of.

BQobj or None

If provided, the diamond norm of \(A - B\) is taken instead.

solverstr {“CVXOPT”, “SCS”}, default: “CVXOPT”

Solver to use with CVXPY. “SCS” tends to be significantly faster, but somewhat less accurate.

verbosebool, default: False

If True, prints additional information about the solution.

force_solvebool, default: False

If True, forces dnorm to solve the associated SDP, even if a special case is known for the argument.

sparsebool, default: True

Whether to use sparse matrices in the convex optimisation problem. Default True.

Returns:
dnfloat

Diamond norm of q_oper.

Raises:
ImportError

If CVXPY cannot be imported.

fidelity(A, B)[source]

Calculates the fidelity (pseudo-metric) between two density matrices.

Parameters:
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

Returns:
fidfloat

Fidelity pseudo-metric between A and B.

Notes

Uses the definition from Nielsen & Chuang, “Quantum Computation and Quantum Information”. It is the square root of the fidelity defined in R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994), used in qutip.core.metrics.process_fidelity.

Examples

>>> x = fock_dm(5,3)
>>> y = coherent_dm(5,1)
>>> np.testing.assert_almost_equal(fidelity(x,y), 0.24104350624628332)
hellinger_dist(A, B, sparse=False, tol=0)[source]

Calculates the quantum Hellinger distance between two density matrices.

Formula:

hellinger_dist(A, B) = sqrt(2 - 2 * tr(sqrt(A) * sqrt(B)))

See: D. Spehner, F. Illuminati, M. Orszag, and W. Roga, “Geometric measures of quantum correlations with Bures and Hellinger distances” arXiv:1611.03449

Parameters:
AQobj

Density matrix or state vector.

BQobj

Density matrix or state vector with same dimensions as A.

tolfloat, default: 0

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

sparsebool, default: False

Use sparse eigensolver.

Returns:
hellinger_distfloat

Quantum Hellinger distance between A and B. Ranges from 0 to sqrt(2).

Examples

>>> x = fock_dm(5,3)
>>> y = coherent_dm(5,1)
>>> np.allclose(hellinger_dist(x, y), 1.3725145002591095)
    True
hilbert_dist(A, B)[source]

Returns the Hilbert-Schmidt distance between two density matrices A & B.

Parameters:
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

Returns:
distfloat

Hilbert-Schmidt distance between density matrices.

Notes

See V. Vedral and M. B. Plenio, Phys. Rev. A 57, 1619 (1998).

process_fidelity(oper, target=None)[source]

Returns the process fidelity of a quantum channel to the target channel, or to the identity channel if no target is given. The process fidelity between two channels is defined as the state fidelity between their normalized Choi matrices.

Parameters:
operQobj/list

A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

targetQobj/list, optional

A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

Returns:
fidfloat

Process fidelity between oper and target, or between oper and identity.

Notes

Since Qutip 5.0, this function computes the process fidelity as defined for example in: A. Gilchrist, N.K. Langford, M.A. Nielsen, Phys. Rev. A 71, 062310 (2005). Previously, it computed a function that is now implemented as get_fidelity in qutip-qtrl.

The definition of state fidelity that the process fidelity is based on is the one from R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994). It is the square of the one implemented in qutip.core.metrics.fidelity which follows Nielsen & Chuang, “Quantum Computation and Quantum Information”

tracedist(A, B, sparse=False, tol=0)[source]

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

Parameters:
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

tolfloat, default: 0

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

sparsebool, default: False

Use sparse eigensolver.

Returns:
tracedistfloat

Trace distance between A and B.

Examples

>>> x=fock_dm(5,3)
>>> y=coherent_dm(5,1)
>>> np.testing.assert_almost_equal(tracedist(x,y), 0.9705143161472971)
unitarity(oper)[source]

Returns the unitarity of a quantum map, defined as the Frobenius norm of the unital block of that map’s superoperator representation.

Parameters:
operQobj

Quantum map under consideration.

Returns:
ufloat

Unitarity of oper.

Continuous 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)[source]

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

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

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

rhoQobj, optional

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_matndarray

A 2-dimensional array of correlation values or operators.

correlation_matrix_field(a1, a2, rho=None)[source]

Calculates 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:
a1Qobj

Field operator for mode 1.

a2Qobj

Field operator for mode 2.

rhoQobj, optional

Density matrix for which to calculate the covariance matrix.

Returns:
cov_matndarray

Array of complex numbers or Qobj’s A 2-dimensional array of covariance values, or, if rho=0, a matrix of operators.

correlation_matrix_quadrature(a1, a2, rho=None, g=1.4142135623730951)[source]

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

Field operator for mode 1.

a2Qobj

Field operator for mode 2.

rhoQobj, optional

Density matrix for which to calculate the covariance matrix.

gfloat, default: sqrt(2)

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

Returns:
corr_matndarray

Array of complex numbers or Qobj’s A 2-dimensional array of covariance values for the field quadratures, or, if rho=0, a matrix of operators.

covariance_matrix(basis, rho, symmetrized=True)[source]

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

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

rhoQobj

Density matrix for which to calculate the covariance matrix.

symmetrizedbool, default: True

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

Returns:
corr_matndarray

A 2-dimensional array of covariance values.

logarithmic_negativity(V, g=1.4142135623730951)[source]

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

Parameters:
Vndarray

The covariance matrix.

gfloat, default: sqrt(2)

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

Returns:
Nfloat

The logarithmic negativity for the two-mode Gaussian state that is described by the the Wigner covariance matrix V.

wigner_covariance_matrix(a1=None, a2=None, R=None, rho=None, g=1.4142135623730951)[source]

Calculates 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:
a1Qobj, optional

Field operator for mode 1.

a2Qobj, optional

Field operator for mode 2.

Rndarray, optional

The quadrature correlation matrix.

rhoQobj, optional

Density matrix for which to calculate the covariance matrix.

gfloat, default: sqrt(2)

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

Returns:
cov_matndarray

A 2-dimensional array of covariance values.

Measurement

Measurement of quantum states

Module for measuring quantum objects.

measure(state, ops, tol=None)[source]

A dispatch method that provides measurement results handling both observable style measurements and projector style measurements (POVMs and PVMs).

For return signatures, please check:

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opsQobj or list of Qobj
  • measurement observable (Qobj); or

  • list of measurement operators \(M_i\) or kets (list of Qobj) Either:

    1. specifying a POVM s.t. \(E_i = M_i^\dagger M_i\)

    2. projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))

    3. kets (transformed to projectors)

tolfloat, optional

Smallest value for the probabilities. Default is qutip’s core settings’ atol.

measure_observable(state, op, tol=None)[source]

Perform a measurement specified by an operator on the given state.

This function simulates the classic quantum measurement described in many introductory texts on quantum mechanics. The measurement collapses the state to one of the eigenstates of the given operator and the result of the measurement is the corresponding eigenvalue.

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opQobj

The measurement operator.

tolfloat, optional

Smallest value for the probabilities. Default is qutip’s core settings’ atol.

Returns:
measured_valuefloat

The result of the measurement (one of the eigenvalues of op).

stateQobj

The new state (a ket if a ket was given, otherwise a density matrix).

Examples

Measure the z-component of the spin of the spin-up basis state:

>>> measure_observable(basis(2, 0), sigmaz())
(1.0, Quantum object: dims = [[2], [1]], shape = (2, 1), type = ket
Qobj data =
[[-1.]
 [ 0.]])

Since the spin-up basis is an eigenstate of sigmaz, this measurement always returns 1 as the measurement result (the eigenvalue of the spin-up basis) and the original state (up to a global phase).

Measure the x-component of the spin of the spin-down basis state:

>>> measure_observable(basis(2, 1), sigmax())
(-1.0, Quantum object: dims = [[2], [1]], shape = (2, 1), type = ket
Qobj data =
[[-0.70710678]
 [ 0.70710678]])

This measurement returns 1 fifty percent of the time and -1 the other fifty percent of the time. The new state returned is the corresponding eigenstate of sigmax.

One may also perform a measurement on a density matrix. Below we perform the same measurement as above, but on the density matrix representing the pure spin-down state:

>>> measure_observable(ket2dm(basis(2, 1)), sigmax())
(-1.0, Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper
Qobj data =
[[ 0.5 -0.5]
 [-0.5  0.5]])

The measurement result is the same, but the new state is returned as a density matrix.

measure_povm(state, ops, tol=None)[source]

Perform a measurement specified by list of POVMs.

This function simulates a POVM measurement. The measurement collapses the state to one of the resultant states of the measurement and returns the index of the operator corresponding to the collapsed state as well as the collapsed state.

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opslist of Qobj

List of measurement operators \(M_i\) or kets. Either:

  1. specifying a POVM s.t. \(E_i = M_i^\dagger M_i\)

  2. projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))

  3. kets (transformed to projectors)

tolfloat, optional

Smallest value for the probabilities. Default is qutip’s core settings’ atol.

Returns:
indexfloat

The resultant index of the measurement.

stateQobj

The new state (a ket if a ket was given, otherwise a density matrix).

measurement_statistics(state, ops, tol=None)[source]

A dispatch method that provides measurement statistics handling both observable style measurements and projector style measurements(POVMs and PVMs).

For return signatures, please check:

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opsQobj or list of Qobj
  • measurement observable (:class:.Qobj); or

  • list of measurement operators \(M_i\) or kets (list of Qobj) Either:

    1. specifying a POVM s.t. \(E_i = M_i^\dagger * M_i\)

    2. projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))

    3. kets (transformed to projectors)

tolfloat, optional

Smallest value for the probabilities. Default is qutip’s core settings’ atol.

measurement_statistics_observable(state, op, tol=None)[source]

Return the measurement eigenvalues, eigenstates (or projectors) and measurement probabilities for the given state and measurement operator.

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opQobj

The measurement operator.

tolfloat, optional

Smallest value for the probabilities. Default is qutip’s core settings’ atol.

Returns:
eigenvalues: list of float

The list of eigenvalues of the measurement operator.

projectors: list of Qobj

Return the projectors onto the eigenstates.

probabilities: list of float

The probability of measuring the state as being in the corresponding eigenstate (and the measurement result being the corresponding eigenvalue).

measurement_statistics_povm(state, ops, tol=None)[source]

Returns measurement statistics (resultant states and probabilities) for a measurement specified by a set of positive operator valued measurements on a specified ket or density matrix.

Parameters:
stateQobj

The ket or density matrix specifying the state to measure.

opslist of Qobj

List of measurement operators \(M_i\) or kets. Either:

  1. specifying a POVM s.t. \(E_i = M_i^\dagger M_i\)

  2. projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))

  3. kets (transformed to projectors)

tolfloat, optional

Smallest value for the probabilities. Smaller probabilities will be rounded to 0. Default is qutip’s core settings’ atol.

Returns:
collapsed_stateslist of Qobj

The collapsed states obtained after measuring the qubits and obtaining the qubit specified by the target in the state specified by the index.

probabilitieslist of floats

The probability of measuring a state in a the state specified by the index.

Dynamics and Time-Evolution

Schrödinger Equation

This module provides solvers for the unitary Schrodinger equation.

sesolve(H, psi0, tlist, e_ops=None, args=None, options=None, **kwargs)[source]

Schrodinger equation evolution of a state vector or unitary matrix for a given Hamiltonian.

Evolve the state vector (psi0) using a given Hamiltonian (H), by integrating the set of ordinary differential equations that define the system. Alternatively evolve a unitary matrix in solving the Schrodinger operator equation.

The output is either the state vector or unitary matrix 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. e_ops cannot be used in conjunction with solving the Schrodinger operator equation

Time-dependent operators

For time-dependent problems, H and c_ops can be a QobjEvo or object that can be interpreted as QobjEvo such as a list of (Qobj, Coefficient) pairs or a function.

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

System Hamiltonian as a Qobj or QobjEvo for time-dependent Hamiltonians. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

psi0Qobj

initial state vector (ket) or initial unitary operator psi0 = U

tlistlist / array

list of times for \(t\).

e_opsQobj, callable, or list, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

argsdict, optional

dictionary of parameters for time-dependent Hamiltonians

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float
    Maximum lenght of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.

Other options could be supported depending on the integration method, see Integrator.

Returns:
result: Result

An instance of the class Result, which contains a list of array result.expect of expectation values for the times specified by tlist, and/or a list result.states of state vectors or density matrices corresponding to the times in tlist [if e_ops is an empty list of store_states=True in options].

Master Equation

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

mesolve(H, rho0, tlist, c_ops=None, e_ops=None, args=None, options=None, **kwargs)[source]

Master equation evolution of a density matrix for a given Hamiltonian and set of collapse operators, or a Liouvillian.

Evolve the state vector or density matrix (rho0) using a given Hamiltonian or Liouvillian (H) and an optional set of collapse operators (c_ops), 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.

If either H or the Qobj elements in c_ops are superoperators, they will be treated as direct contributions to the total system Liouvillian. This allows the solution of master equations that are not in standard Lindblad form.

Time-dependent operators

For time-dependent problems, H and c_ops can be a QobjEvo or object that can be interpreted as QobjEvo such as a list of (Qobj, Coefficient) pairs or a function.

Additional options

Additional options to mesolve can be set via the options argument. Many ODE integration options can be set this way, and the store_states and store_final_state options can be used to store states even though expectation values are requested via the e_ops argument.

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

Possibly time-dependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

rho0Qobj

initial density matrix or state vector (ket).

tlistlist / array

list of times for \(t\).

c_opslist of (QobjEvo, QobjEvo compatible format)

Single collapse operator, or list of collapse operators, or a list of Liouvillian superoperators. None is equivalent to an empty list.

e_opslist of Qobj / callback function, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

argsdict, optional

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

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float
    Maximum lenght of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.

Other options could be supported depending on the integration method, see Integrator.

Returns:
result: Result

An instance of the class Result, which contains a list of array result.expect of expectation values for the times specified by tlist, and/or a list result.states of state vectors or density matrices corresponding to the times in tlist [if e_ops is an empty list of store_states=True in options].

Notes

When no collapse operator are given and the H is not a superoperator, it will defer to sesolve.

Monte Carlo Evolution

mcsolve(H, state, tlist, c_ops=(), e_ops=None, ntraj=500, *, args=None, options=None, seeds=None, target_tol=None, timeout=None, **kwargs)[source]

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

Parameters:
HQobj, QobjEvo, list, callable.

System Hamiltonian as a Qobj, QobjEvo. It can also be any input type that QobjEvo accepts (see QobjEvo’s documentation). H can also be a superoperator (liouvillian) if some collapse operators are to be treated deterministically.

stateQobj

Initial state vector.

tlistarray_like

Times at which results are recorded.

c_opslist

A list of collapse operators in any input type that QobjEvo accepts (see QobjEvo’s documentation). They must be operators even if H is a superoperator. If none are given, the solver will defer to sesolve or mesolve.

e_opslist, optional

A list of operator as Qobj, QobjEvo or callable with signature of (t, state: Qobj) for calculating expectation values. When no e_ops are given, the solver will default to save the states.

ntrajint, default: 500

Maximum number of trajectories to run. Can be cut short if a time limit is passed with the timeout keyword or if the target tolerance is reached, see target_tol.

argsdict, optional

Arguments for time-dependent Hamiltonian and collapse operator terms.

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float
    Maximum length of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.
  • keep_runs_results : bool, [False]
    Whether to store results from all trajectories or just store the averages.
  • map : str {“serial”, “parallel”, “loky”, “mpi”}
    How to run the trajectories. “parallel” uses the multiprocessing module to run in parallel while “loky” and “mpi” use the “loky” and “mpi4py” modules to do so.
  • num_cpus : int
    Number of cpus to use when running in parallel. None detect the number of available cpus.
  • norm_t_tol, norm_tol, norm_steps : float, float, int
    Parameters used to find the collapse location. norm_t_tol and norm_tol are the tolerance in time and norm respectively. An error will be raised if the collapse could not be found within norm_steps tries.
  • mc_corr_eps : float
    Small number used to detect non-physical collapse caused by numerical imprecision.
  • improved_sampling : Bool
    Whether to use the improved sampling algorithm from Abdelhafez et al. PRA (2019)

Additional options are listed under options. More options may be available depending on the selected differential equation integration method, see Integrator.

seedsint, SeedSequence, list, optional

Seed for the random number generator. It can be a single seed used to spawn seeds for each trajectory or a list of seeds, one for each trajectory. Seeds are saved in the result and they can be reused with:

seeds=prev_result.seeds
target_tolfloat, tuple, list, optional

Target tolerance of the evolution. The evolution will compute trajectories until the error on the expectation values is lower than this tolerance. The maximum number of trajectories employed is given by ntraj. The error is computed using jackknife resampling. target_tol can be an absolute tolerance or a pair of absolute and relative tolerance, in that order. Lastly, it can be a list of pairs of (atol, rtol) for each e_ops.

timeoutfloat, optional

Maximum time for the evolution in second. When reached, no more trajectories will be computed.

Returns:
resultsMcResult

Object storing all results from the simulation. Which results is saved depends on the presence of e_ops and the options used. collapse and photocurrent is available to Monte Carlo simulation results.

Notes

The simulation will end when the first end condition is reached between ntraj, timeout and target_tol.

nm_mcsolve(H, state, tlist, ops_and_rates=(), e_ops=None, ntraj=500, *, args=None, options=None, seeds=None, target_tol=None, timeout=None)[source]

Monte-Carlo evolution corresponding to a Lindblad equation with “rates” that may be negative. Usage of this function is analogous to mcsolve, but the c_ops parameter is replaced by an ops_and_rates parameter to allow for negative rates. Options for the underlying ODE solver are given by the Options class.

Parameters:
HQobj, QobjEvo, list, callable.

System Hamiltonian as a Qobj, QobjEvo. It can also be any input type that QobjEvo accepts (see QobjEvo’s documentation). H can also be a superoperator (liouvillian) if some collapse operators are to be treated deterministically.

stateQobj

Initial state vector.

tlistarray_like

Times at which results are recorded.

ops_and_rateslist

A list of tuples (L, Gamma), where the Lindblad operator L is a Qobj and Gamma represents the corresponding rate, which is allowed to be negative. The Lindblad operators must be operators even if H is a superoperator. If none are given, the solver will defer to sesolve or mesolve. Each rate Gamma may be just a number (in the case of a constant rate) or, otherwise, specified using any format accepted by coefficient.

e_opslist, optional

A list of operator as Qobj, QobjEvo or callable with signature of (t, state: Qobj) for calculating expectation values. When no e_ops are given, the solver will default to save the states.

ntrajint, default: 500

Maximum number of trajectories to run. Can be cut short if a time limit is passed with the timeout keyword or if the target tolerance is reached, see target_tol.

argsdict, optional

Arguments for time-dependent Hamiltonian and collapse operator terms.

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float
    Maximum length of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.
  • keep_runs_results : bool, [False]
    Whether to store results from all trajectories or just store the averages.
  • map : str {“serial”, “parallel”, “loky”, “mpi”}
    How to run the trajectories. “parallel” uses the multiprocessing module to run in parallel while “loky” and “mpi” use the “loky” and “mpi4py” modules to do so.
  • num_cpus : int
    Number of cpus to use when running in parallel. None detect the number of available cpus.
  • norm_t_tol, norm_tol, norm_steps : float, float, int
    Parameters used to find the collapse location. norm_t_tol and norm_tol are the tolerance in time and norm respectively. An error will be raised if the collapse could not be found within norm_steps tries.
  • mc_corr_eps : float
    Small number used to detect non-physical collapse caused by numerical imprecision.
  • completeness_rtol, completeness_atol : float, float
    Parameters used in determining whether the given Lindblad operators satisfy a certain completeness relation. If they do not, an additional Lindblad operator is added automatically (with zero rate).
  • martingale_quad_limit : float or int
    An upper bound on the number of subintervals used in the adaptive integration of the martingale.

Note that the ‘improved_sampling’ option is not currently supported. Additional options are listed under options. More options may be available depending on the selected differential equation integration method, see Integrator.

seedsint, SeedSequence, list, optional

Seed for the random number generator. It can be a single seed used to spawn seeds for each trajectory or a list of seeds, one for each trajectory. Seeds are saved in the result and they can be reused with:

seeds=prev_result.seeds
target_tolfloat, tuple, list, optional

Target tolerance of the evolution. The evolution will compute trajectories until the error on the expectation values is lower than this tolerance. The maximum number of trajectories employed is given by ntraj. The error is computed using jackknife resampling. target_tol can be an absolute tolerance or a pair of absolute and relative tolerance, in that order. Lastly, it can be a list of pairs of (atol, rtol) for each e_ops.

timeoutfloat, optional

Maximum time for the evolution in seconds. When reached, no more trajectories will be computed.

Returns:
resultsNmmcResult

Object storing all results from the simulation. Compared to a result returned by mcsolve, this result contains the additional field trace (and runs_trace if store_final_state is set). Note that the states on the individual trajectories are not normalized. This field contains the average of their trace, which will converge to one in the limit of sufficiently many trajectories.

Krylov Subspace Solver

krylovsolve(H, psi0, tlist, krylov_dim, e_ops=None, args=None, options=None)[source]

Schrodinger equation evolution of a state vector for time independent Hamiltonians using Krylov method.

Evolve the state vector (“psi0”) finding an approximation for the time evolution operator of Hamiltonian (“H”) by obtaining the projection of the time evolution operator on a set of small dimensional Krylov subspaces (m << dim(H)).

The output is either the state vector or unitary matrix 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. e_ops cannot be used in conjunction with solving the Schrodinger operator equation

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

System Hamiltonian as a Qobj or QobjEvo for time-dependent Hamiltonians. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

psi0Qobj

Initial state vector (ket)

tlistlist / array

list of times for \(t\).

krylov_dim: int

Dimension of Krylov approximation subspaces used for the time evolution approximation.

e_opsQobj, callable, or list, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

argsdict, optional

dictionary of parameters for time-dependent Hamiltonians

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • atol: float
    Absolute tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • min_step, max_step : float
    Miniumum and maximum lenght of one internal step.
  • always_compute_step: bool
    If True, the step lenght is computed each time a new Krylov subspace is computed. Otherwise it is computed only once when creating the integrator.
  • sub_system_tol: float
    Tolerance to detect an happy breakdown. An happy breakdown happens when the initial ket is in a subspace of the Hamiltonian smaller than krylov_dim.
Returns:
result: Result

An instance of the class Result, which contains a list of array result.expect of expectation values for the times specified by tlist, and/or a list result.states of state vectors or density matrices corresponding to the times in tlist [if e_ops is an empty list of store_states=True in options].

Bloch-Redfield Master Equation

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

brmesolve(H, psi0, tlist, a_ops=(), e_ops=(), c_ops=(), args=None, sec_cutoff=0.1, options=None, **kwargs)[source]

Solves for the dynamics of a system using the Bloch-Redfield master equation, given an input Hamiltonian, Hermitian bath-coupling terms and their associated spectral functions, as well as possible Lindblad collapse operators.

Parameters:
HQobj, QobjEvo

Possibly time-dependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. list of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

psi0: Qobj

Initial density matrix or state vector (ket).

tlistarray_like

List of times for evaluating evolution

a_opslist of (a_op, spectra)

Nested list of system operators that couple to the environment, and the corresponding bath spectra.

a_opQobj, QobjEvo

The operator coupling to the environment. Must be hermitian.

spectraCoefficient, str, func

The corresponding bath spectral responce. Can be a Coefficient using an ‘w’ args, a function of the frequence or a string. Coefficient build from a numpy array are understood as a function of w instead of t. Function are expected to be of the signature f(w) or f(t, w, **args).

The spectra function can depend on t if the corresponding a_op is a QobjEvo.

Example:

a_ops = [
    (a+a.dag(), ('w>0', args={"w": 0})),
    (QobjEvo(a+a.dag()), 'w > exp(-t)'),
    (QobjEvo([b+b.dag(), lambda t: ...]), lambda w: ...)),
    (c+c.dag(), SpectraCoefficient(coefficient(array, tlist=ws))),
]
e_opslist of Qobj / callback function, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation

c_opslist of (QobjEvo, QobjEvo compatible format), optional

List of collapse operators.

argsdict, optional

Dictionary of parameters for time-dependent Hamiltonians and collapse operators. The key w is reserved for the spectra function.

sec_cutofffloat, default: 0.1

Cutoff for secular approximation. Use -1 if secular approximation is not used when evaluating bath-coupling terms.

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • tensor_type : str [‘sparse’, ‘dense’, ‘data’]
    Which data type to use when computing the brtensor. With a cutoff ‘sparse’ is usually the most efficient.
  • sparse_eigensolver : bool {False} Whether to use the sparse eigensolver
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.] Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float, 0
    Maximum lenght of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.

Other options could be supported depending on the integration method, see Integrator.

Returns:
result: Result

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

Floquet States and Floquet-Markov Master Equation

floquet_tensor(H, c_ops, spectra_cb, T=0, w_th=0.0, kmax=5, nT=100)[source]

Construct a tensor that represents the master equation in the floquet basis.

Simplest RWA approximation [Grifoni et al, Phys.Rep. 304 229 (1998)]

Parameters:
HQobjEvo, FloquetBasis

Periodic Hamiltonian a floquet basis system.

Tfloat, optional

The period of the time-dependence of the hamiltonian. Optional if H is a FloquetBasis object.

c_opslist of Qobj

list of collapse operators.

spectra_cblist callback functions

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

w_thfloat, default: 0.0

The temperature in units of frequency.

kmaxint, default: 5

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

nTint, default: 100

The number of integration steps (for calculating X) within one period.

Returns:
outputarray

The Floquet-Markov master equation tensor R.

fmmesolve(H, rho0, tlist, c_ops=None, e_ops=None, spectra_cb=None, T=0, w_th=0.0, args=None, options=None)[source]

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

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

Periodic system Hamiltonian as QobjEvo. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

rho0 / psi0Qobj

Initial density matrix or state vector (ket).

tlistlist / array

List of times for \(t\).

c_opslist of Qobj, optional

List of collapse operators. Time dependent collapse operators are not supported. Fall back on fsesolve if not provided.

e_opslist of Qobj / callback function, optional

List of operators for which to evaluate expectation values. The states are reverted to the lab basis before applying the

spectra_cblist callback functions, default: lambda w: (w > 0)

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

Tfloat, default=tlist[-1]

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

w_thfloat, default: 0.0

The temperature of the environment in units of frequency. 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

argsdict, optional

Dictionary of parameters for time-dependent Hamiltonian

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • store_floquet_states : bool
    Whether or not to store the density matrices in the floquet basis in result.floquet_states.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float
    Maximum lenght of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.

Other options could be supported depending on the integration method, see Integrator.

Returns:
result: Result

An instance of the class Result, which contains the expectation values for the times specified by tlist, and/or the state density matrices corresponding to the times.

fsesolve(H, psi0, tlist, e_ops=None, T=0.0, args=None, options=None)[source]

Solve the Schrodinger equation using the Floquet formalism.

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

Periodic system Hamiltonian as QobjEvo. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

psi0Qobj

Initial state vector (ket). If an operator is provided,

tlistlist / array

List of times for \(t\).

e_opslist of Qobj / callback function, optional

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.

Tfloat, default=tlist[-1]

The period of the time-dependence of the hamiltonian.

argsdictionary, optional

Dictionary with variables required to evaluate H.

optionsdict, optional

Options for the results.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
Returns:
outputResult

An instance of the class 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

smesolve(H, rho0, tlist, c_ops=(), sc_ops=(), heterodyne=False, *, e_ops=(), args={}, ntraj=500, options=None, seeds=None, target_tol=None, timeout=None, **kwargs)[source]

Solve stochastic master equation.

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

System Hamiltonian as a Qobj or QobjEvo for time-dependent Hamiltonians. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

rho0Qobj

Initial density matrix or state vector (ket).

tlistlist / array

List of times for \(t\).

c_opslist of (QobjEvo, QobjEvo compatible format), optional

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

sc_opslist of (QobjEvo, QobjEvo compatible format)

List of stochastic collapse operators.

e_ops: qobj, callable, or list, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

argsdict, optional

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

ntrajint, default: 500

Number of trajectories to compute.

heterodynebool, default: False

Whether to use heterodyne or homodyne detection.

seedsint, SeedSequence, list, optional

Seed for the random number generator. It can be a single seed used to spawn seeds for each trajectory or a list of seeds, one for each trajectory. Seeds are saved in the result and they can be reused with:

seeds=prev_result.seeds

When using a parallel map, the trajectories can be re-ordered.

target_tol{float, tuple, list}, optional

Target tolerance of the evolution. The evolution will compute trajectories until the error on the expectation values is lower than this tolerance. The maximum number of trajectories employed is given by ntraj. The error is computed using jackknife resampling. target_tol can be an absolute tolerance or a pair of absolute and relative tolerance, in that order. Lastly, it can be a list of pairs of (atol, rtol) for each e_ops.

timeoutfloat, optional

Maximum time for the evolution in second. When reached, no more trajectories will be computed. Overwrite the option of the same name.

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • store_measurement: bool
    Whether to store the measurement and wiener process for each trajectories.
  • keep_runs_results : bool
    Whether to store results from all trajectories or just store the averages.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str
    Which stochastic differential equation integration method to use. Main ones are {“euler”, “rouchon”, “platen”, “taylor1.5_imp”}
  • map : str {“serial”, “parallel”, “loky”, “mpi”}
    How to run the trajectories. “parallel” uses the multiprocessing module to run in parallel while “loky” and “mpi” use the “loky” and “mpi4py” modules to do so.
  • num_cpus : NoneType, int
    Number of cpus to use when running in parallel. None detect the number of available cpus.
  • dt : float
    The finite steps lenght for the Stochastic integration method. Default change depending on the integrator.

Additional options are listed under options. More options may be available depending on the selected differential equation integration method, see SIntegrator.

Returns:
output: Result

An instance of the class Result.

ssesolve(H, psi0, tlist, sc_ops=(), heterodyne=False, *, e_ops=(), args={}, ntraj=500, options=None, seeds=None, target_tol=None, timeout=None, **kwargs)[source]

Solve stochastic Schrodinger equation.

Parameters:
HQobj, QobjEvo, QobjEvo compatible format.

System Hamiltonian as a Qobj or QobjEvo for time-dependent Hamiltonians. List of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

psi0Qobj

Initial state vector (ket).

tlistlist / array

List of times for \(t\).

sc_opslist of (QobjEvo, QobjEvo compatible format)

List of stochastic collapse operators.

e_opsqobj, callable, or list, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

argsdict, optional

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

ntrajint, default: 500

Number of trajectories to compute.

heterodynebool, default: False

Whether to use heterodyne or homodyne detection.

seedsint, SeedSequence, list, optional

Seed for the random number generator. It can be a single seed used to spawn seeds for each trajectory or a list of seeds, one for each trajectory. Seeds are saved in the result and they can be reused with:

seeds=prev_result.seeds
target_tol{float, tuple, list}, optional

Target tolerance of the evolution. The evolution will compute trajectories until the error on the expectation values is lower than this tolerance. The maximum number of trajectories employed is given by ntraj. The error is computed using jackknife resampling. target_tol can be an absolute tolerance or a pair of absolute and relative tolerance, in that order. Lastly, it can be a list of pairs of (atol, rtol) for each e_ops.

timeoutfloat, optional

Maximum time for the evolution in second. When reached, no more trajectories will be computed. Overwrite the option of the same name.

optionsdict, optional

Dictionary of options for the solver.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • store_measurement: bool Whether to store the measurement and wiener process, or brownian noise for each trajectories.
  • keep_runs_results : bool
    Whether to store results from all trajectories or just store the averages.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • method : str
    Which stochastic differential equation integration method to use. Main ones are {“euler”, “rouchon”, “platen”, “taylor1.5_imp”}
  • map : str {“serial”, “parallel”, “loky”, “mpi”}
    How to run the trajectories. “parallel” uses the multiprocessing module to run in parallel while “loky” and “mpi” use the “loky” and “mpi4py” modules to do so.
  • num_cpus : NoneType, int
    Number of cpus to use when running in parallel. None detect the number of available cpus.
  • dt : float
    The finite steps lenght for the Stochastic integration method. Default change depending on the integrator.

Additional options are listed under options. More options may be available depending on the selected differential equation integration method, see SIntegrator.

Returns:
output: Result

An instance of the class Result.

Constructing time dependent systems

coefficient(base, *, tlist=None, args={}, args_ctypes={}, order=3, compile_opt=None, function_style=None, boundary_conditions=None, **kwargs)[source]

Build Coefficient for time dependent systems:

` QobjEvo = Qobj + Qobj * Coefficient + Qobj * Coefficient + ... `

The coefficients can be a function, a string or a numpy array. Other packages may add support for other kind of coefficients.

For function based coefficients, the function signature must be either:

  • f(t, ...) where the other arguments are supplied as ordinary “pythonic” arguments (e.g. f(t, w, a=5))

  • f(t, args) where the arguments are supplied in a “dict” named args

By default the signature style is controlled by the qutip.settings.core["function_coefficient_style"] setting, but it may be overriden here by specifying either function_style="pythonic" or function_style="dict".

Examples:

  • pythonic style function signature:

    def f1_t(t, w):
        return np.exp(-1j * t * w)
    
    coeff1 = coefficient(f1_t, args={"w": 1.})
    
  • dict style function signature:

    def f2_t(t, args):
        return np.exp(-1j * t * args["w"])
    
    coeff2 = coefficient(f2_t, args={"w": 1.})
    

For string based coeffients, the string must be a compilable python code resulting in a complex. The following symbols are defined:

sin, cos, tan, asin, acos, atan, pi, sinh, cosh, tanh, asinh, acosh, atanh, exp, log, log10, erf, zerf, sqrt, real, imag, conj, abs, norm, arg, proj, numpy as np, scipy.special as spe (python interface) and cython_special (scipy cython interface)

Examples:

coeff = coefficient('exp(-1j*w1*t)', args={"w1":1.})

‘args’ is needed for string coefficient at compilation. It is a dict of (name:object). The keys must be a valid variables string.

Compilation options can be passed as “compile_opt=CompilationOptions(…)”.

For numpy array format, the array must be an 1d of dtype float or complex. A list of times (float64) at which the coeffients must be given (tlist). The coeffients array must have the same len as the tlist. The time of the tlist do not need to be equidistant, but must be sorted. By default, a cubic spline interpolation will be used to compute the coefficient at time t. The keyword order sets the order of the interpolation. When order = 0, the interpolation is step function that evaluates to the most recent value.

Examples:

tlist = np.logspace(-5,0,100)
H = QobjEvo(np.exp(-1j*tlist), tlist=tlist)

scipy.interpolate’s CubicSpline, PPoly and Bspline are also converted to interpolated coefficients (the same kind of coefficient created from ndarray). Other interpolation methods from scipy are converted to a function-based coefficient (the same kind of coefficient created from callables).

Parameters:
baseobject

Base object to make into a Coefficient.

argsdict, optional

Dictionary of arguments to pass to the function or string coefficient.

orderint, default=3

Order of the spline for array based coefficient.

tlistiterable, optional

Times for each element of an array based coefficient.

function_stylestr {“dict”, “pythonic”, None}, optional

Function signature of function based coefficients.

args_ctypesdict, optional

C type for the args when compiling array based coefficients.

compile_optCompilationOptions, optional

Sets of options for the compilation of string based coefficients.

boundary_conditions: 2-tupule, str or None, optional

Specify boundary conditions for spline interpolation.

**kwargs

Extra arguments to pass the the coefficients.

Hierarchical Equations of Motion

This module provides solvers for system-bath evoluation using the HEOM (hierarchy equations of motion).

See https://en.wikipedia.org/wiki/Hierarchical_equations_of_motion for a very basic introduction to the technique.

The implementation is derived from the BoFiN library (see https://github.com/tehruhn/bofin) which was itself derived from an earlier implementation in QuTiP itself.

For backwards compatibility with QuTiP 4.6 and below, a new version of HSolverDL (the Drude-Lorentz specific HEOM solver) is provided. It is implemented on top of the new HEOMSolver but should largely be a drop-in replacement for the old HSolverDL.

heomsolve(H, bath, max_depth, state0, tlist, *, e_ops=None, args=None, options=None)[source]

Hierarchical Equations of Motion (HEOM) solver that supports multiple baths.

The baths must be all either bosonic or fermionic baths.

If you need to run many evolutions of the same system and bath, consider using HEOMSolver directly to avoid having to continually reconstruct the equation hierarchy for every evolution.

Parameters:
HQobj, QobjEvo

Possibly time-dependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. list of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

bathBath or list of Bath

A Bath containing the exponents of the expansion of the bath correlation funcion and their associated coefficients and coupling operators, or a list of baths.

If multiple baths are given, they must all be either fermionic or bosonic baths.

max_depthint

The maximum depth of the heirarchy (i.e. the maximum number of bath exponent “excitations” to retain).

state0Qobj or HierarchyADOsState or array-like

If rho0 is a Qobj the it is the initial state of the system (i.e. a Qobj density matrix).

If it is a HierarchyADOsState or array-like, then rho0 gives the initial state of all ADOs.

Usually the state of the ADOs would be determine from a previous call to .run(...) with the solver results option store_ados set to True. For example, result = solver.run(...) could be followed by solver.run(result.ado_states[-1], tlist).

If a numpy array-like is passed its shape must be (number_of_ados, n, n) where (n, n) is the system shape (i.e. shape of the system density matrix) and the ADOs must be in the same order as in .ados.labels.

tlistlist

An ordered list of times at which to return the value of the state.

e_opsQobj / QobjEvo / callable / list / dict / None, optional

A list or dictionary of operators as Qobj, QobjEvo and/or callable functions (they can be mixed) or a single operator or callable function. For an operator op, the result will be computed using (state * op).tr() and the state at each time t. For callable functions, f, the result is computed using f(t, ado_state). The values are stored in the expect and e_data attributes of the result (see the return section below).

argsdict, optional

Change the args of the RHS for the evolution.

optionsdict, optional

Generic solver options.

  • store_final_state : bool
    Whether or not to store the final state of the evolution in the result class.
  • store_states : bool, None
    Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.
  • store_ados : bool
    Whether or not to store the HEOM ADOs.
  • normalize_output : bool
    Normalize output state to hide ODE numerical errors.
  • progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}
    How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.
  • progress_kwargs : dict
    kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
  • state_data_type: str {‘dense’, ‘CSR’, ‘Dia’, }
    Name of the data type of the state used during the ODE evolution. Use an empty string to keep the input state type. Many integrator can only work with Dense.
  • method : str [“adams”, “bdf”, “lsoda”, “dop853”, “vern9”, etc.]
    Which differential equation integration method to use.
  • atol, rtol : float
    Absolute and relative tolerance of the ODE integrator.
  • nsteps : int
    Maximum number of (internally defined) steps allowed in one tlist step.
  • max_step : float,
    Maximum lenght of one internal step. When using pulses, it should be less than half the width of the thinnest pulse.
Returns:
HEOMResult

The results of the simulation run, with the following important attributes:

  • times: the times t (i.e. the tlist).

  • states: the system state at each time t (only available if e_ops was None or if the solver option store_states was set to True).

  • ado_states: the full ADO state at each time (only available if the results option ado_return was set to True). Each element is an instance of HierarchyADOsState. The state of a particular ADO may be extracted from result.ado_states[i] by calling extract.

  • expect: a list containing the values of each e_ops at time t.

  • e_data: a dictionary containing the values of each e_ops at tme t. The keys are those given by e_ops if it was a dict, otherwise they are the indexes of the supplied e_ops.

See HEOMResult and Result for the complete list of attributes.

Correlation Functions

coherence_function_g1(H, state0, taulist, c_ops, a_op, solver='me', args=None, options=None)[source]

Calculate the normalized 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}}\]

using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist of {Qobj, QobjEvo}

List of collapse operators

a_opQobj, QobjEvo

Operator A.

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

argsdict, optional

dictionary of parameters for time-dependent Hamiltonians

optionsdict, optional

Options for the solver.

Returns:
g1, G1tuple

The normalized and unnormalized second-order coherence function.

coherence_function_g2(H, state0, taulist, c_ops, a_op, solver='me', args=None, options=None)[source]

Calculate the normalized 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}\]

using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist

List of collapse operators, may be time-dependent for solver choice of me.

a_opQobj

Operator A.

argsdict, optional

Dictionary of arguments to be passed to solver.

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

optionsdict, optional

Options for the solver.

Returns:
g2, G2tuple

The normalized and unnormalized second-order coherence function.

correlation_2op_1t(H, state0, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args=None, options=None)[source]

Calculate the two-operator one-time correlation function: \(\left<A(\tau)B(0)\right>\) along one time axis using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist of {Qobj, QobjEvo}

List of collapse operators

a_opQobj, QobjEvo

Operator A.

b_opQobj, QobjEvo

Operator B.

reversebool, default: False

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

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

optionsdict, optional

Options for the solver.

Returns:
corr_vecndarray

An array of correlation values for the times specified by taulist.

See also

correlation_3op

Similar function supporting various solver types.

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_2op_2t(H, state0, tlist, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args=None, options=None)[source]

Calculate the two-operator two-time correlation function: \(\left<A(t+\tau)B(t)\right>\) along two time axes using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

tlistarray_like

List of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\). If tlist is None, tlist=[0] is assumed.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist of {Qobj, QobjEvo}

List of collapse operators

a_opQobj, QobjEvo

Operator A.

b_opQobj, QobjEvo

Operator B.

reversebool, default: False

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

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

optionsdict, optional

Options for the solver.

Returns:
corr_matndarray

An 2-dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index).

See also

correlation_3op

Similar function supporting various solver types.

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_3op(solver, state0, tlist, taulist, A=None, B=None, C=None)[source]

Calculate the three-operator two-time correlation function:

\(\left<A(t)B(t+\tau)C(t)\right>\).

from a open system Solver.

Note: it is not possible to calculate a physically meaningful correlation where \(\tau<0\).

Parameters:
solverMESolver, BRSolver

Qutip solver for an open system.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\).

tlistarray_like

List of times for \(t\). tlist must be positive and contain the element 0.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

A, B, CQobj, QobjEvo, optional, default=None

Operators A, B, C from the equation <A(t)B(t+\tau)C(t)> in the Schrodinger picture. They do not need to be all provided. For exemple, if A is not provided, <B(t+\tau)C(t)> is computed.

Returns:
corr_matarray

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_3op_1t(H, state0, taulist, c_ops, a_op, b_op, c_op, solver='me', args=None, options=None)[source]

Calculate the three-operator two-time correlation function: \(\left<A(0)B(\tau)C(0)\right>\) along one time axis using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Note: it is not possibly to calculate a physically meaningful correlation of this form where \(\tau<0\).

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist of {Qobj, QobjEvo}

List of collapse operators

a_opQobj, QobjEvo

Operator A.

b_opQobj, QobjEvo

Operator B.

c_opQobj, QobjEvo

Operator C.

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

optionsdict, optional

Options for the solver.

Returns:
corr_vecarray

An array of correlation values for the times specified by taulist.

See also

correlation_3op

Similar function supporting various solver types.

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_3op_2t(H, state0, tlist, taulist, c_ops, a_op, b_op, c_op, solver='me', args=None, options=None)[source]

Calculate the three-operator two-time correlation function: \(\left<A(t)B(t+\tau)C(t)\right>\) along two time axes using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Note: it is not possibly to calculate a physically meaningful correlation of this form where \(\tau<0\).

Parameters:
HQobj, QobjEvo

System Hamiltonian, may be time-dependent for solver choice of me.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented if c_ops are provided and the Hamiltonian is constant.

tlistarray_like

List of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\). If tlist is None, tlist=[0] is assumed.

taulistarray_like

List of times for \(\tau\). taulist must be positive and contain the element 0.

c_opslist of {Qobj, QobjEvo}

List of collapse operators

a_opQobj, QobjEvo

Operator A.

b_opQobj, QobjEvo

Operator B.

c_opQobj, QobjEvo

Operator C.

solverstr {‘me’, ‘es’}, default: ‘me’

Choice of solver, me for master-equation, and es for exponential series. es is equivalent to me with options={"method": "diag"}.

optionsdict, optional

Options for the solver. Only used with me solver.

Returns:
corr_matarray

An 2-dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index).

See also

correlation_3op

Similar function supporting various solver types.

References

See, Gardiner, Quantum Noise, Section 5.2.

spectrum(H, wlist, c_ops, a_op, b_op, solver='es')[source]

Calculate the spectrum of the correlation function \(\lim_{t \to \infty} \left<A(t+\tau)B(t)\right>\), i.e., the Fourier transform of the correlation function:

\[S(\omega) = \int_{-\infty}^{\infty} \lim_{t \to \infty} \left<A(t+\tau)B(t)\right> e^{-i\omega\tau} d\tau.\]

using the solver indicated by the solver parameter. Note: this spectrum is only defined for stationary statistics (uses steady state rho0)

Parameters:
Hqobj

system Hamiltonian.

wlistarray_like

List of frequencies for \(\omega\).

c_opslist

List of collapse operators.

a_opQobj

Operator A.

b_opQobj

Operator B.

solverstr, {‘es’, ‘pi’, ‘solve’}, default: ‘es’

Choice of solver, es for exponential series and pi for psuedo-inverse, solve for generic solver.

Returns:
spectrumarray

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

spectrum_correlation_fft(tlist, y, inverse=False)[source]

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

Parameters:
tlistarray_like

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

yarray_like

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

inverse: bool, default: False

boolean parameter for using a positive exponent in the Fourier Transform instead. Default is False.

Returns:
w, Stuple

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

Steady-state Solvers

pseudo_inverse(L, rhoss=None, w=None, method='splu', *, use_rcm=False, **kwargs)[source]

Compute the pseudo inverse for a Liouvillian superoperator, optionally given its steady state density matrix (which will be computed if not given).

Parameters:
LQobj

A Liouvillian superoperator for which to compute the pseudo inverse.

rhossQobj, optional

A steadystate density matrix as Qobj instance, for the Liouvillian superoperator L.

wdouble, optional

frequency at which to evaluate pseudo-inverse. Can be zero for dense systems and large sparse systems. Small sparse systems can fail for zero frequencies.

sparsebool, optional

Flag that indicate whether to use sparse or dense matrix methods when computing the pseudo inverse.

methodstr, optional

Method used to compte matrix inverse. Choice are ‘pinv’ to use scipy’s function of the same name, or a linear system solver. Default supported solver are:

  • “solve”, “lstsq” dense solver from numpy.linalg

  • “spsolve”, “gmres”, “lgmres”, “bicgstab”, “splu” sparse solver from scipy.sparse.linalg

  • “mkl_spsolve”, sparse solver by mkl.

Extension to qutip, such as qutip-tensorflow, can use come with their own solver. When L use these data backends, see the corresponding libraries linalg for available solver.

use_rcmbool, default: False

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

kwargsdictionary

Additional keyword arguments for setting parameters for solver methods.

Returns:
RQobj

Returns a Qobj instance representing the pseudo inverse of L.

Notes

In general the inverse of a sparse matrix will be dense. If you are applying the inverse to a density matrix then it is better to cast the problem as an Ax=b type problem where the explicit calculation of the inverse is not required. See page 67 of “Electrons in nanostructures” C. Flindt, PhD Thesis available online: https://orbit.dtu.dk/en/publications/electrons-in-nanostructures-coherent-manipulation-and-counting-st

Note also that the definition of the pseudo-inverse herein is different from numpys pinv() alone, as it includes pre and post projection onto the subspace defined by the projector Q.

steadystate(A, c_ops=[], *, method='direct', solver=None, **kwargs)[source]

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

A Hamiltonian or Liouvillian operator.

c_op_listlist

A list of collapse operators.

methodstr, {“direct”, “eigen”, “svd”, “power”}, default: “direct”

The allowed methods are composed of 2 parts, the steadystate method: - “direct”: Solving L(rho_ss) = 0 - “eigen” : Eigenvalue problem - “svd” : Singular value decomposition - “power” : Inverse-power method

solverstr, optional

‘direct’ and ‘power’ methods only. Solver to use when solving the L(rho_ss) = 0 equation. Default supported solver are:

  • “solve”, “lstsq” dense solver from numpy.linalg

  • “spsolve”, “gmres”, “lgmres”, “bicgstab” sparse solver from scipy.sparse.linalg

  • “mkl_spsolve” sparse solver by mkl.

Extension to qutip, such as qutip-tensorflow, can use come with their own solver. When A and c_ops use these data backends, see the corresponding libraries linalg for available solver.

Extra options for these solver can be passed in **kw.

use_rcmbool, default: False

Use reverse Cuthill-Mckee reordering to minimize fill-in in the LU factorization of the Liouvillian. Used with ‘direct’ or ‘power’ method.

use_wbmbool, default: False

Use Weighted Bipartite Matching reordering to make the Liouvillian diagonally dominant. This is useful for iterative preconditioners only. Used with ‘direct’ or ‘power’ method.

weightfloat, 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. Used with ‘direct’ method.

power_tolfloat, default: 1e-12

Tolerance for the solution when using the ‘power’ method.

power_maxiterint, default: 10

Maximum number of iteration to use when looking for a solution when using the ‘power’ method.

power_eps: double, default: 1e-15

Small weight used in the “power” method.

sparse: bool, default: True

Whether to use the sparse eigen solver with the “eigen” method (default sparse). With “direct” and “power” method, when the solver is not specified, it is used to set whether “solve” or “spsolve” is used as default solver.

**kwargs

Extra options to pass to the linear system solver. See the documentation of the used solver in numpy.linalg or scipy.sparse.linalg to see what extra arguments are supported.

Returns:
dmqobj

Steady state density matrix.

infodict, optional

Dictionary containing solver-specific information about the solution.

Notes

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

steadystate_floquet(H_0, c_ops, Op_t, w_d=1.0, n_it=3, sparse=False, solver=None, **kwargs)[source]
Calculates the effective steady state for a driven

system with a time-dependent cosinusoidal term:

\[\mathcal{\hat{H}}(t) = \hat{H}_0 + \mathcal{\hat{O}} \cos(\omega_d t)\]
Parameters:
H_0Qobj

A Hamiltonian or Liouvillian operator.

c_opslist

A list of collapse operators.

Op_tQobj

The the interaction operator which is multiplied by the cosine

w_dfloat, default: 1.0

The frequency of the drive

n_itint, default: 3

The number of iterations for the solver

sparsebool, default: False

Solve for the steady state using sparse algorithms.

solverstr, optional

Solver to use when solving the linear system. Default supported solver are:

  • “solve”, “lstsq” dense solver from numpy.linalg

  • “spsolve”, “gmres”, “lgmres”, “bicgstab” sparse solver from scipy.sparse.linalg

  • “mkl_spsolve” sparse solver by mkl.

Extensions to qutip, such as qutip-tensorflow, may provide their own solvers. When H_0 and c_ops use these data backends, see their documentation for the names and details of additional solvers they may provide.

**kwargs:

Extra options to pass to the linear system solver. See the documentation of the used solver in numpy.linalg or scipy.sparse.linalg to see what extra arguments are supported.

Returns:
dmqobj

Steady state density matrix.

Notes

See: Sze Meng Tan, https://copilot.caltech.edu/documents/16743/qousersguide.pdf, Section (10.16)

Propagators

propagator(H, t, c_ops=(), args=None, options=None, **kwargs)[source]

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:
HQobj, QobjEvo, QobjEvo compatible format

Possibly time-dependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. list of [Qobj, Coefficient] or callable that can be made into QobjEvo are also accepted.

tfloat or array-like

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

c_opslist, optional

List of Qobj or QobjEvo collapse operators.

argsdictionary, optional

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

optionsdict, optional

Options for the solver.

**kwargs

Extra parameters to use when creating the QobjEvo from a list format H.

Returns:
UQobj, list

Instance representing the propagator(s) \(U(t)\). Return a single Qobj when t is a number or a list when t is a list.

propagator_steadystate(U)[source]

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

Parameters:
UQobj

Operator representing the propagator.

Returns:
aQobj

Instance representing the steady-state density matrix.

Scattering in Quantum Optical Systems

Photon scattering in quantum optical systems

This module includes a collection of functions for numerically computing photon scattering in driven arbitrary systems coupled to some configuration of output waveguides. The implementation of these functions closely follows the mathematical treatment given in K.A. Fischer, et. al., Scattering of Coherent Pulses from Quantum Optical Systems (2017, arXiv:1710.02875).

scattering_probability(H, psi0, n_emissions, c_ops, tlist, system_zero_state=None, construct_effective_hamiltonian=True)[source]

Compute the integrated probability of scattering n photons in an arbitrary system. This function accepts a nonlinearly spaced array of times.

Parameters:
HQobj or list

System-waveguide(s) Hamiltonian or effective Hamiltonian in Qobj or list-callback format. If construct_effective_hamiltonian is not specified, an effective Hamiltonian is constructed from H and c_ops.

psi0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\).

n_emissionsint

Number of photons emitted by the system (into any combination of waveguides).

c_opslist

List of collapse operators for each waveguide; these are assumed to include spontaneous decay rates, e.g. \(\sigma = \sqrt \gamma \cdot a\).

tlistarray_like

List of times for \(\tau_i\). tlist should contain 0 and exceed the pulse duration / temporal region of interest; tlist need not be linearly spaced.

system_zero_stateQobj, optional

State representing zero excitations in the system. Defaults to basis(systemDims, 0).

construct_effective_hamiltonianbool, default: True

Whether an effective Hamiltonian should be constructed from H and c_ops: \(H_{eff} = H - \frac{i}{2} \sum_n \sigma_n^\dagger \sigma_n\) Default: True.

Returns:
scattering_probfloat

The probability of scattering n photons from the system over the time range specified.

temporal_basis_vector(waveguide_emission_indices, n_time_bins)[source]

Generate a temporal basis vector for emissions at specified time bins into specified waveguides.

Parameters:
waveguide_emission_indiceslist or tuple

List of indices where photon emission occurs for each waveguide, e.g. [[t1_wg1], [t1_wg2, t2_wg2], [], [t1_wg4, t2_wg4, t3_wg4]].

n_time_binsint

Number of time bins; the range over which each index can vary.

Returns:
temporal_basis_vectorQobj

A basis vector representing photon scattering at the specified indices. If there are W waveguides, T times, and N photon emissions, then the basis vector has dimensionality (W*T)^N.

temporal_scattered_state(H, psi0, n_emissions, c_ops, tlist, system_zero_state=None, construct_effective_hamiltonian=True)[source]

Compute the scattered n-photon state projected onto the temporal basis.

Parameters:
HQobj or list

System-waveguide(s) Hamiltonian or effective Hamiltonian in Qobj or list-callback format. If construct_effective_hamiltonian is not specified, an effective Hamiltonian is constructed from H and c_ops.

psi0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\).

n_emissionsint

Number of photon emissions to calculate.

c_opslist

List of collapse operators for each waveguide; these are assumed to include spontaneous decay rates, e.g. \(\sigma = \sqrt \gamma \cdot a\)

tlistarray_like

List of times for \(\tau_i\). tlist should contain 0 and exceed the pulse duration / temporal region of interest.

system_zero_stateQobj, optional

State representing zero excitations in the system. Defaults to \(\psi(t_0)\)

construct_effective_hamiltonianbool, default: True

Whether an effective Hamiltonian should be constructed from H and c_ops: \(H_{eff} = H - \frac{i}{2} \sum_n \sigma_n^\dagger \sigma_n\) Default: True.

Returns:
phi_nQobj

The scattered bath state projected onto the temporal basis given by tlist. If there are W waveguides, T times, and N photon emissions, then the state is a tensor product state with dimensionality T^(W*N).

Permutational Invariance

Permutational Invariant Quantum Solver (PIQS)

This module calculates the Liouvillian for the dynamics of ensembles of identical two-level systems (TLS) in the presence of local and collective processes by exploiting permutational symmetry and using the Dicke basis. It also allows to characterize nonlinear functions of the density matrix.

am(j, m)[source]

Calculate the operator am used later.

The action of ap is given by: \(J_{-}\lvert j,m\rangle = A_{-}(jm)\lvert j,m-1\rangle\)

Parameters:
j: float

The value for j.

m: float

The value for m.

Returns:
a_minus: float

The value of \(a_{-}\).

ap(j, m)[source]

Calculate the coefficient ap by applying \(J_+\lvert j,m\rangle\).

The action of ap is given by: \(J_{+}\lvert j, m\rangle = A_{+}(j, m) \lvert j, m+1\rangle\)

Parameters:
j, m: float

The value for j and m in the dicke basis \(\lvert j, m\rangle\).

Returns:
a_plus: float

The value of \(a_{+}\).

block_matrix(N, elements='ones')[source]

Construct the block-diagonal matrix for the Dicke basis.

Parameters:
Nint

Number of two-level systems.

elementsstr {‘ones’, ‘degeneracy’}, default: ‘ones’
Returns:
block_matrndarray

A 2D block-diagonal matrix with dimension (nds,nds), where nds is the number of Dicke states for N two-level systems. Filled with ones or the value of degeneracy at each matrix element.

collapse_uncoupled(N, emission=0.0, dephasing=0.0, pumping=0.0, collective_emission=0.0, collective_dephasing=0.0, collective_pumping=0.0)[source]

Create the collapse operators (c_ops) of the Lindbladian in the uncoupled basis

These operators are in the uncoupled basis of the two-level system (TLS) SU(2) Pauli matrices.

Parameters:
N: int

The number of two-level systems.

emission: float, default: 0.0

Incoherent emission coefficient (also nonradiative emission).

dephasing: float, default: 0.0

Local dephasing coefficient.

pumping: float, default: 0.0

Incoherent pumping coefficient.

collective_emission: float, default: 0.0

Collective (superradiant) emmission coefficient.

collective_pumping: float, default: 0.0

Collective pumping coefficient.

collective_dephasing: float, default: 0.0

Collective dephasing coefficient.

Returns:
c_ops: list

The list of collapse operators as Qobj for the system.

Notes

The collapse operator list can be given to qutip.mesolve. Notice that the operators are placed in a Hilbert space of dimension \(2^N\). Thus the method is suitable only for small N (of the order of 10).

css(N, x=0.7071067811865475, y=0.7071067811865475, basis='dicke', coordinates='cartesian')[source]

Generate the density matrix of the Coherent Spin State (CSS).

It can be defined as, \(\lvert CSS\rangle = \prod_i^N(a\lvert1\rangle_i+b\lvert0\rangle_i)\) with \(a = sin(\frac{\theta}{2})\), \(b = e^{i \phi}\cos(\frac{\theta}{2})\). The default basis is that of Dicke space \(\lvert j, m\rangle \langle j, m'\rvert\). The default state is the symmetric CSS, \(\lvert CSS\rangle = \lvert+\rangle\).

Parameters:
N: int

The number of two-level systems.

x, y: float, default: sqrt(1/2)

The coefficients of the CSS state.

basis: str {“dicke”, “uncoupled”}, default: “dicke”

The basis to use.

coordinates: str {“cartesian”, “polar”}, default: “cartesian”

If polar then the coefficients are constructed as \(sin(x/2), cos(x/2)e^(iy)`\).

Returns:
rho: Qobj

The CSS state density matrix.

dicke(N, j, m)[source]

Generate a Dicke state as a pure density matrix in the Dicke basis.

For instance, the superradiant state given by \(\lvert j, m\rangle = \lvert 1, 0\rangle\) for N = 2, and the state is represented as a density matrix of size (nds, nds) or (4, 4), with the (1, 1) element set to 1.

Parameters:
N: int

The number of two-level systems.

j: float

The eigenvalue j of the Dicke state (j, m).

m: float

The eigenvalue m of the Dicke state (j, m).

Returns:
rho: Qobj

The density matrix.

dicke_basis(N, jmm1)[source]

Initialize the density matrix of a Dicke state for several (j, m, m1).

This function can be used to build arbitrary states in the Dicke basis \(\lvert j, m\rangle\langle j, m'\rvert\). We create coefficients for each (j, m, m1) value in the dictionary jmm1. The mapping for the (i, k) index of the density matrix to the \(\lvert j, m\rangle\) values is given by the cythonized function jmm1_dictionary. A density matrix is created from the given dictionary of coefficients for each (j, m, m1).

Parameters:
N: int

The number of two-level systems.

jmm1: dict

A dictionary of {(j, m, m1): p} that gives a density p for the (j, m, m1) matrix element.

Returns:
rho: Qobj

The density matrix in the Dicke basis.

dicke_blocks(rho)[source]

Create the list of blocks for block-diagonal density matrix in the Dicke basis.

Parameters:
rhoQobj

A 2D block-diagonal matrix of ones with dimension (nds,nds), where nds is the number of Dicke states for N two-level systems.

Returns:
square_blocks: list of np.ndarray

Give back the blocks list.

dicke_blocks_full(rho)[source]

Give the full (2^N-dimensional) list of blocks for a Dicke-basis matrix.

Parameters:
rhoQobj

A 2D block-diagonal matrix of ones with dimension (nds,nds), where nds is the number of Dicke states for N two-level systems.

Returns:
full_blockslist

The list of blocks expanded in the 2^N space for N qubits.

dicke_function_trace(f, rho)[source]

Calculate the trace of a function on a Dicke density matrix. :param f: A Taylor-expandable function of rho. :type f: function :param rho: A density matrix in the Dicke basis. :type rho: Qobj

Returns:
resfloat

Trace of a nonlinear function on rho.

energy_degeneracy(N, m)[source]

Calculate the number of Dicke states with same energy.

The use of the Decimals class allows to explore N > 1000, unlike the built-in function scipy.special.binom.

Parameters:
N: int

The number of two-level systems.

m: float

Total spin z-axis projection eigenvalue. This is proportional to the total energy.

Returns:
degeneracy: int

The energy degeneracy

entropy_vn_dicke(rho)[source]

Von Neumann Entropy of a Dicke-basis density matrix.

Parameters:
rhoQobj

A 2D block-diagonal matrix of ones with dimension (nds, nds), where nds is the number of Dicke states for N two-level systems.

Returns:
entropy_dm: float

Entropy. Use degeneracy to multiply each block.

excited(N, basis='dicke')[source]

Generate the density matrix for the excited state.

This state is given by (N/2, N/2) in the default Dicke basis. If the argument basis is “uncoupled” then it generates the state in a 2**N dim Hilbert space.

Parameters:
N: int

The number of two-level systems.

basis: str, {“dicke”, “uncoupled”}, default: “dicke”

The basis to use.

Returns:
state: Qobj

The excited state density matrix in the requested basis.

ghz(N, basis='dicke')[source]

Generate the density matrix of the GHZ state.

If the argument basis is “uncoupled” then it generates the state in a \(2^N\)-dimensional Hilbert space.

Parameters:
N: int

The number of two-level systems.

basis: str, {“dicke”, “uncoupled”}, default: “dicke”

The basis to use.

Returns:
state: Qobj

The GHZ state density matrix in the requested basis.

ground(N, basis='dicke')[source]

Generate the density matrix of the ground state.

This state is given by (N/2, -N/2) in the Dicke basis. If the argument basis is “uncoupled” then it generates the state in a \(2^N\)-dimensional Hilbert space.

Parameters:
N: int

The number of two-level systems.

basis: str, {“dicke”, “uncoupled”}, default: “dicke”

The basis to use.

Returns:
state: Qobj

The ground state density matrix in the requested basis.

identity_uncoupled(N)[source]

Generate the identity in a \(2^N\)-dimensional Hilbert space.

The identity matrix is formed from the tensor product of N TLSs.

Parameters:
N: int

The number of two-level systems.

Returns:
identity: Qobj

The identity matrix.

isdiagonal(mat)[source]

Check if the input matrix is diagonal.

Parameters:
mat: ndarray/Qobj

A 2D numpy array

Returns:
diag: bool

True/False depending on whether the input matrix is diagonal.

jspin(N, op=None, basis='dicke')[source]

Calculate the list of collective operators of the total algebra.

The Dicke basis \(\lvert j,m\rangle\langle j,m'\rvert\) is used by default. Otherwise with “uncoupled” the operators are in a \(2^N\) space.

Parameters:
N: int

Number of two-level systems.

op: str {‘x’, ‘y’, ‘z’, ‘+’, ‘-‘}, optional

The operator to return ‘x’,’y’,’z’,’+’,’-‘. If no operator given, then output is the list of operators for [‘x’,’y’,’z’].

basis: str {“dicke”, “uncoupled”}, default: “dicke”

The basis of the operators.

Returns:
j_alg: list or Qobj

A list of qutip.Qobj representing all the operators in the “dicke” or “uncoupled” basis or a single operator requested.

m_degeneracy(N, m)[source]

Calculate the number of Dicke states \(\lvert j, m\rangle\) with same energy.

Parameters:
N: int

The number of two-level systems.

m: float

Total spin z-axis projection eigenvalue (proportional to the total energy).

Returns:
degeneracy: int

The m-degeneracy.

num_dicke_ladders(N)[source]

Calculate the total number of ladders in the Dicke space.

For a collection of N two-level systems it counts how many different “j” exist or the number of blocks in the block-diagonal matrix.

Parameters:
N: int

The number of two-level systems.

Returns:
Nj: int

The number of Dicke ladders.

num_dicke_states(N)[source]

Calculate the number of Dicke states.

Parameters:
N: int

The number of two-level systems.

Returns:
nds: int

The number of Dicke states.

num_tls(nds)[source]

Calculate the number of two-level systems.

Parameters:
nds: int

The number of Dicke states.

Returns:
N: int

The number of two-level systems.

purity_dicke(rho)[source]

Calculate purity of a density matrix in the Dicke basis. It accounts for the degenerate blocks in the density matrix.

Parameters:
rhoQobj

Density matrix in the Dicke basis of qutip.piqs.jspin(N), for N spins.

Returns:
purityfloat

The purity of the quantum state. It’s 1 for pure states, 0<=purity<1 for mixed states.

spin_algebra(N, op=None)[source]

Create the list [sx, sy, sz] with the spin operators.

The operators are constructed for a collection of N two-level systems (TLSs). Each element of the list, i.e., sx, is a vector of qutip.Qobj objects (spin matrices), as it cointains the list of the SU(2) Pauli matrices for the N TLSs. Each TLS operator sx[i], with i = 0, …, (N-1), is placed in a \(2^N\)-dimensional Hilbert space.

Parameters:
N: int

The number of two-level systems.

Returns:
spin_operators: list or Qobj

A list of qutip.Qobj operators - [sx, sy, sz] or the requested operator.

Notes

sx[i] is \(\frac{\sigma_x}{2}\) in the composite Hilbert space.

state_degeneracy(N, j)[source]

Calculate the degeneracy of the Dicke state.

Each state \(\lvert j, m\rangle\) includes D(N,j) irreducible representations \(\lvert j, m, \alpha\rangle\).

Uses Decimals to calculate higher numerator and denominators numbers.

Parameters:
N: int

The number of two-level systems.

j: float

Total spin eigenvalue (cooperativity).

Returns:
degeneracy: int

The state degeneracy.

superradiant(N, basis='dicke')[source]

Generate the density matrix of the superradiant state.

This state is given by (N/2, 0) or (N/2, 0.5) in the Dicke basis. If the argument basis is “uncoupled” then it generates the state in a 2**N dim Hilbert space.

Parameters:
N: int

The number of two-level systems.

basis: str, {“dicke”, “uncoupled”}, default: “dicke”

The basis to use.

Returns:
state: Qobj

The superradiant state density matrix in the requested basis.

tau_column(tau, k, j)[source]

Determine the column index for the non-zero elements of the matrix for a particular row k and the value of j from the Dicke space.

Parameters:
tau: str

The tau function to check for this k and j.

k: int

The row of the matrix M for which the non zero elements have to be calculated.

j: float

The value of j for this row.

Visualization

Pseudoprobability Functions

qfunc(state: Qobj, xvec, yvec, g: float = 1.4142135623730951, precompute_memory: float = 1024)[source]

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

Parameters:
stateQobj

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

xvec, yvecarray_like

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

gfloat, default: sqrt(2)

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

precompute_memoryreal, default: 1024

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

Returns:
ndarray

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

See also

QFunc

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

spin_q_function(rho, theta, phi)[source]

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

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

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

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

thetaarray_like

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

phiarray_like

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

Returns:
Q, THETA, PHI2d-array

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

References

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

spin_wigner(rho, theta, phi)[source]

Wigner function for a spin-j system.

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

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

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

thetaarray_like

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

phiarray_like

Azimuthal angle at which to calculate the W function.

Returns:
W, THETA, PHI2d-array

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

References

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

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

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

wigner(psi, xvec, yvec=None, method='clenshaw', g=1.4142135623730951, sparse=False, parfor=False)[source]

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

Parameters:
stateqobj

A state vector or density matrix.

xvecarray_like

x-coordinates at which to calculate the Wigner function.

yvecarray_like

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

gfloat, default: sqrt(2)

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

methodstring {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

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

sparsebool, optional

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

parforbool, optional

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

Returns:
Warray

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

yvexarray

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

Notes

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

References

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

Graphs and Visualization

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

hinton(rho, x_basis=None, y_basis=None, color_style='scaled', label_top=True, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

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

Parameters:
rhoqobj

Input density matrix or superoperator.

Note

Hinton plots of superoperators are currently only supported for qubits.

x_basislist of strings, optional

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

y_basislist of strings, optional

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

color_stylestr, {“scaled”, “threshold”, “phase”}, default: “scaled”

Determines how colors are assigned to each square:

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

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

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

label_topbool, default: True

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The ax context in which the plot will be drawn.

Returns:
fig, outputtuple

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

Raises:
ValueError

Input argument is not a quantum object.

Examples

>>> import qutip
>>> dm = qutip.rand_dm(4)
>>> fig, ax = qutip.hinton(dm)
>>> fig.show()
>>> qutip.settings.colorblind_safe = True
>>> fig, ax = qutip.hinton(dm, color_style="threshold")
>>> fig.show()
>>> qutip.settings.colorblind_safe = False
>>> fig, ax = qutip.hinton(dm, color_style="phase")
>>> fig.show()
matrix_histogram(M, x_basis=None, y_basis=None, limits=None, bar_style='real', color_limits=None, color_style='real', options=None, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

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

Parameters:
MMatrix of Qobj

The matrix to visualize

x_basislist of strings, optional

list of x ticklabels

y_basislist of strings, optional

list of y ticklabels

limitslist/array with two float numbers, optional

The z-axis limits [min, max]

bar_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”
  • If set to "real" (default), each bar is plotted as the real part of the corresponding matrix element

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

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

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

color_limitslist/array with two float numbers, optional

The limits of colorbar [min, max]

color_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”

Determines how colors are assigned to each square:

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

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

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

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

show colorbar

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

optionsdict, optional

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

‘zticks’list of numbers, optional

A list of z-axis tick locations.

‘bars_spacing’float, default: 0.1

spacing between bars.

‘bars_alpha’float, default: 1.

transparency of bars, should be in range 0 - 1

‘bars_lw’float, default: 0.5

linewidth of bars’ edges.

‘bars_edgecolor’color, default: ‘k’

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

‘shade’bool, default: True

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

‘azim’float, default: -35

The azimuthal viewing angle.

‘elev’float, default: 35

The elevation viewing angle.

‘stick’bool, default: False

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

‘cbar_pad’float, default: 0.04

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

‘cbar_to_z’bool, default: False

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

‘threshold’: float, optional

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

Returns:
fig, outputtuple

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

Raises:
ValueError

Input argument is not valid.

plot_energy_levels(H_list, h_labels=None, energy_levels=None, N=0, *, fig=None, ax=None)[source]

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

Parameters:
H_listList of Qobj

A list of Hamiltonians.

h_lablesList of string, optional

A list of xticklabels for each Hamiltonian

energy_levelsList of string, optional

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

Nint, default: 0

The number of energy levels to plot

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, axtuple

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

Raises:
ValueError

Input argument is not valid.

plot_expectation_values(results, ylabels=None, *, fig=None, axes=None)[source]

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

Parameters:
results(list of) Result

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

ylabelslist of strings, optional

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axes(list of) axes instances, optional

The axes context in which the plot will be drawn.

Returns:
fig, axestuple

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

plot_fock_distribution(rho, fock_numbers=None, color='green', unit_y_range=True, *, fig=None, ax=None)[source]

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

Parameters:
rhoQobj

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

fock_numberslist of strings, optional

list of x ticklabels to represent fock numbers

colorcolor or list of colors, default: “green”

The colors of the bar faces.

unit_y_rangebool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, outputtuple

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

plot_qubism(ket, theme='light', how='pairs', grid_iteration=1, legend_iteration=0, *, fig=None, ax=None)[source]

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

Note

colorblind_safe does not apply because of its unique colormap

Parameters:
ketQobj

Pure state for plotting.

themestr {‘light’, ‘dark’}, default: ‘light’

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

howstr {‘pairs’, ‘pairs_skewed’ or ‘before_after’}, default: ‘pairs’

Type of Qubism plotting. Options:

  • ‘pairs’ - typical coordinates,

  • ‘pairs_skewed’ - for ferromagnetic/antriferromagnetic plots,

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

grid_iterationint, default: 1

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

legend_iterationint or ‘grid_iteration’ or ‘all’, default: 0

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, outputtuple

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

Notes

See also [1].

References

[1]

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

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

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

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

Note

colorblind_safe does not apply because of its unique colormap

Parameters:
ketQobj

Pure state for plotting.

themestr {‘light’, ‘dark’}, default: ‘light’

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

splittingint, optional

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

labels_iterationint or pair of ints, default: (3, 2)

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, outputtuple

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

plot_spin_distribution(P, THETA, PHI, projection='2d', *, cmap=None, colorbar=False, fig=None, ax=None)[source]

Plots a spin distribution (given as meshgrid data).

Parameters:
Pmatrix

Distribution values as a meshgrid matrix.

THETAmatrix

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

PHImatrix

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

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

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

cmapa matplotlib cmap instance, optional

The colormap.

colorbarbool, default: False

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, outputtuple

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

plot_wigner(rho, xvec=None, yvec=None, method='clenshaw', projection='2d', g=1.4142135623730951, sparse=False, parfor=False, *, cmap=None, colorbar=False, fig=None, ax=None)[source]

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

Parameters:
rhoQobj

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

xvecarray_like, optional

x-coordinates at which to calculate the Wigner function.

yvecarray_like, optional

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

methodstr {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

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

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

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

gfloat

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

sparsebool {False, True}

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

parforbool {False, True}

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

cmapa matplotlib cmap instance, optional

The colormap.

colorbarbool, default: False

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, outputtuple

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

plot_wigner_sphere(wigner, reflections=False, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

Plots a coloured Bloch sphere.

Parameters:
wignera wigner transformation

The wigner transformation at steps different theta and phi.

reflectionsbool, default: False

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The ax context in which the plot will be drawn.

Returns:
fig, outputtuple

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

Notes

Special thanks to Russell P Rundle for writing this function.

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

Plots a matrix of values on a sphere

Parameters:
valuesarray

Data set to be plotted

thetafloat

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

phifloat

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, outputtuple

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

Functions to animate results of quantum dynamics simulations,

anim_fock_distribution(rhos, fock_numbers=None, color='green', unit_y_range=True, *, fig=None, ax=None)[source]

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

Parameters:
rhosResult or list of Qobj

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

fock_numberslist of strings, optional

list of x ticklabels to represent fock numbers

colorcolor or list of colors, default: “green”

The colors of the bar faces.

unit_y_rangebool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, anituple

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

anim_hinton(rhos, x_basis=None, y_basis=None, color_style='scaled', label_top=True, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

Draws an animation of Hinton diagram.

Parameters:
rhosResult or list of Qobj

Input density matrix or superoperator.

Note

Hinton plots of superoperators are currently only supported for qubits.

x_basislist of strings, optional

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

y_basislist of strings, optional

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

color_stylestr, {“scaled”, “threshold”, “phase”}, default: “scaled”

Determines how colors are assigned to each square:

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

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

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

label_topbool, default: True

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The ax context in which the plot will be drawn.

Returns:
fig, anituple

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

Raises:
ValueError

Input argument is not a quantum object.

anim_matrix_histogram(Ms, x_basis=None, y_basis=None, limits=None, bar_style='real', color_limits=None, color_style='real', options=None, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

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

Parameters:
Mslist of matrices or Result

The matrix to visualize

x_basislist of strings, optional

list of x ticklabels

y_basislist of strings, optional

list of y ticklabels

limitslist/array with two float numbers, optional

The z-axis limits [min, max]

bar_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”
  • If set to "real" (default), each bar is plotted as the real part of the corresponding matrix element

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

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

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

color_limitslist/array with two float numbers, optional

The limits of colorbar [min, max]

color_stylestr, {“real”, “img”, “abs”, “phase”}, default: “real”

Determines how colors are assigned to each square:

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

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

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

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

show colorbar

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

optionsdict, optional

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

‘zticks’list of numbers, optional

A list of z-axis tick locations.

‘bars_spacing’float, default: 0.1

spacing between bars.

‘bars_alpha’float, default: 1.

transparency of bars, should be in range 0 - 1

‘bars_lw’float, default: 0.5

linewidth of bars’ edges.

‘bars_edgecolor’color, default: ‘k’

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

‘shade’bool, default: True

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

‘azim’float, default: -35

The azimuthal viewing angle.

‘elev’float, default: 35

The elevation viewing angle.

‘stick’bool, default: False

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

‘cbar_pad’float, default: 0.04

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

‘cbar_to_z’bool, default: False

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

‘threshold’: float, optional

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

Returns:
fig, anituple

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

Raises:
ValueError

Input argument is not valid.

anim_qubism(kets, theme='light', how='pairs', grid_iteration=1, legend_iteration=0, *, fig=None, ax=None)[source]

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

Note

colorblind_safe does not apply because of its unique colormap

Parameters:
ketsResult or list of Qobj

Pure states for animation.

themestr {‘light’, ‘dark’}, default: ‘light’

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

howstr {‘pairs’, ‘pairs_skewed’, ‘before_after’}, default: ‘pairs’

Type of Qubism plotting. Options:

  • ‘pairs’ - typical coordinates,

  • ‘pairs_skewed’ - for ferromagnetic/antriferromagnetic plots,

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

grid_iterationint, default: 1

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

legend_iterationint or ‘grid_iteration’ or ‘all’, default: 0

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, anituple

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

Notes

See also [1].

References

[1]

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

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

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

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

Note

colorblind_safe does not apply because of its unique colormap

Parameters:
ketResult or list of Qobj

Pure states for animation.

themestr {‘light’, ‘dark’}, default: ‘light’

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

splittingint, optional

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

labels_iterationint or pair of ints, default: (3, 2)

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, anituple

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

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

animation of a matrices of values on a sphere

Parameters:
Vlist of array instances

Data set to be plotted

thetafloat

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

phifloat

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, anituple

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

anim_spin_distribution(Ps, THETA, PHI, projection='2d', *, cmap=None, colorbar=False, fig=None, ax=None)[source]

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

Parameters:
Pslist of matrices

Distribution values as a meshgrid matrix.

THETAmatrix

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

PHImatrix

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

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

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

cmapa matplotlib cmap instance, optional

The colormap.

colorbarbool, default: False

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

figa matplotlib figure instance, optional

The figure canvas on which the plot will be drawn.

axa matplotlib axis instance, optional

The axis context in which the plot will be drawn.

Returns:
fig, anituple

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

anim_wigner(rhos, xvec=None, yvec=None, method='clenshaw', projection='2d', g=1.4142135623730951, sparse=False, parfor=False, *, cmap=None, colorbar=False, fig=None, ax=None)[source]

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

Parameters:
rhosResult or list of Qobj

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

xvecarray_like, optional

x-coordinates at which to calculate the Wigner function.

yvecarray_like, optional

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

methodstr {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}, default: ‘clenshaw’

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

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

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

gfloat

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

sparsebool {False, True}

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

parforbool {False, True}

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

cmapa matplotlib cmap instance, optional

The colormap.

colorbarbool, default: False

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The axes context in which the plot will be drawn.

Returns:
fig, anituple

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

anim_wigner_sphere(wigners, reflections=False, *, cmap=None, colorbar=True, fig=None, ax=None)[source]

Animate a coloured Bloch sphere.

Parameters:
wignerslist of transformations

The wigner transformation at steps different theta and phi.

reflectionsbool, default: False

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

cmapa matplotlib colormap instance, optional

Color map to use when plotting.

colorbarbool, default: True

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

figa matplotlib Figure instance, optional

The Figure canvas in which the plot will be drawn.

axa matplotlib axes instance, optional

The ax context in which the plot will be drawn.

Returns:
fig, anituple

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

Notes

Special thanks to Russell P Rundle for writing this function.

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

complex_phase_cmap()[source]

Create a cyclic colormap for representing the phase of complex variables

Returns:
cmap

A matplotlib linear segmented colormap.

wigner_cmap(W, levels=1024, shift=0, max_color='#09224F', mid_color='#FFFFFF', min_color='#530017', neg_color='#FF97D4', invert=False)[source]

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

Parameters:
Warray

Wigner function array, or any array.

levelsint, default: 1024

Number of color levels to create.

shiftfloat, default: 0

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

max_colorstr, default: ‘#09224F’

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

mid_colorstr, default: ‘#FFFFFF’

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

min_colorstr, default: ‘#530017’

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

neg_colorstr, default: ‘#FF97D4’

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

invertbool, default: False

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

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

Notes

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

Quantum Process Tomography

qpt(U, op_basis_list)[source]

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

vec(rho) = U * vec(rho0)

or

rho = unstack_columns(U * stack_columns(rho0))

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

Parameters:
UQobj

Transformation operator. Can be calculated using QuTiP propagator function.

op_basis_listlist

A list of Qobj’s representing the basis states.

Returns:
chiarray

QPT chi matrix

qpt_plot(chi, lbls_list, title=None, fig=None, axes=None)[source]

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

Parameters:
chiarray

Input QPT chi matrix.

lbls_listlist

List of labels for QPT plot axes.

titlestr, optional

Plot title.

figfigure instance, optional

User defined figure instance used for generating QPT plot.

axeslist of figure axis instance, optional

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

Returns:
fig, axtuple

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

qpt_plot_combined(chi, lbls_list, title=None, fig=None, ax=None, figsize=(8, 6), threshold=None)[source]

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

Parameters:
chiarray

Input QPT chi matrix.

lbls_listlist

List of labels for QPT plot axes.

titlestr, optional

Plot title.

figfigure instance, optional

User defined figure instance used for generating QPT plot.

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

Size of the figure when the fig is not provided.

axfigure axis instance, optional

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

threshold: float, optional

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

Returns:
fig, axtuple

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

Non-Markovian Solvers

This module contains an implementation of the non-Markovian transfer tensor method (TTM), introduced in [1].

[1] Javier Cerrillo and Jianshu Cao, Phys. Rev. Lett 112, 110401 (2014)

ttmsolve(dynmaps, state0, times, e_ops=(), num_learning=0, options=None)[source]

Expand time-evolution using the Transfer Tensor Method [1], based on a set of precomputed dynamical maps.

Parameters:
dynmapslist of Qobj, callable

List of precomputed dynamical maps (superoperators) for the first times of times or a callback function that returns the superoperator at a given time.

state0Qobj

Initial density matrix or state vector (ket).

timesarray_like

List of times \(t_n\) at which to compute results. Must be uniformily spaced.

e_opsQobj, callable, or list, optional

Single operator or list of operators for which to evaluate expectation values or callable or list of callable. Callable signature must be, f(t: float, state: Qobj). See expect for more detail of operator expectation.

num_learningint, default: 0

Number of times used to construct the dynmaps operators when dynmaps is a callable.

optionsdictionary, optional

Dictionary of options for the solver.

  • store_final_state : bool Whether or not to store the final state of the evolution in the result class.

  • store_states : bool, None Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.

  • normalize_output : bool Normalize output state to hide ODE numerical errors.

  • threshold : float Threshold for halting. Halts if \(||T_{n}-T_{n-1}||\) is below treshold.

Returns:
output: Result

An instance of the class Result.

[1]

Javier Cerrillo and Jianshu Cao, Phys. Rev. Lett 112, 110401 (2014) ..

Utility Functions

Utility Functions

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

clebsch(j1, j2, j3, m1, m2, m3)[source]

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

Parameters:
j1float

Total angular momentum 1.

j2float

Total angular momentum 2.

j3float

Total angular momentum 3.

m1float

z-component of angular momentum 1.

m2float

z-component of angular momentum 2.

m3float

z-component of angular momentum 3.

Returns:
cg_coefffloat

Requested Clebsch-Gordan coefficient.

convert_unit(value, orig='meV', to='GHz')[source]

Convert an energy from unit orig to unit to.

Parameters:
valuefloat / array

The energy in the old unit.

origstr, {“J”, “eV”, “meV”, “GHz”, “mK”}, default: “meV”

The name of the original unit.

tostr, {“J”, “eV”, “meV”, “GHz”, “mK”}, default: “GHz”

The name of the new unit.

Returns:
value_new_unitfloat / array

The energy in the new unit.

n_thermal(w, w_th)[source]

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:
wfloat or ndarray

Frequency of the oscillator.

w_thfloat

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

Returns:
n_avgfloat or array

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

File I/O Functions

file_data_read(filename, sep=None)[source]

Retrieves an array of data from the requested file.

Parameters:
filenamestr or pathlib.Path

Name of file containing reqested data.

sepstr, optional

Seperator used to store data.

Returns:
dataarray_like

Data from selected file.

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

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

Parameters:
filenamestr or pathlib.Path

Name of data file to be stored, including extension.

data: array_like

Data to be written to file.

numtypestr {‘complex, ‘real’}, default: ‘complex’

Type of numerical data.

numformatstr {‘decimal’,’exp’}, default: ‘decimal’

Format for written data.

sepstr, default: ‘,’

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

qload(filename)[source]

Loads data file from file filename in current directory.

Parameters:
filenamestr or pathlib.Path

Name of data file to be loaded.

Returns:
qobjectinstance / array_like

Object retrieved from requested file.

qsave(data, name='qutip_data')[source]

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

Parameters:
datainstance/array_like

Input Python object to be stored.

filenamestr or pathlib.Path, default: “qutip_data”

Name of output data file.

Parallelization

This module provides functions for parallel execution of loops and function mappings, using the builtin Python module multiprocessing or the loky parallel execution library.

loky_pmap(task, values, task_args=None, task_kwargs=None, reduce_func=None, map_kw=None, progress_bar=None, progress_bar_kwargs={})[source]

Parallel execution of a mapping of values to the function task. This is functionally equivalent to:

result = [task(value, *task_args, **task_kwargs) for value in values]

Use the loky module instead of multiprocessing.

Parameters:
taska Python function

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

valuesarray / list

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

task_argslist, optional

The optional additional arguments to the task function.

task_kwargsdictionary, optional

The optional additional keyword arguments to the task function.

reduce_funcfunc, optional

If provided, it will be called with the output of each task instead of storing them in a list. Note that the order in which results are passed to reduce_func is not defined. It should return None or a number. When returning a number, it represents the estimation of the number of tasks left. On a return <= 0, the map will end early.

progress_barstr, optional

Progress bar options’s string for showing progress.

progress_bar_kwargsdict, optional

Options for the progress bar.

map_kw: dict, optional

Dictionary containing entry for: - timeout: float, Maximum time (sec) for the whole map. - num_cpus: int, Number of jobs to run at once. - fail_fast: bool, Abort at the first error.

Returns:
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values. If a reduce_func is provided, and empty list will be returned.

mpi_pmap(task, values, task_args=None, task_kwargs=None, reduce_func=None, map_kw=None, progress_bar=None, progress_bar_kwargs={})[source]

Parallel execution of a mapping of values to the function task. This is functionally equivalent to:

result = [task(value, *task_args, **task_kwargs) for value in values]

Uses the mpi4py module to execute the tasks asynchronously with MPI processes. For more information, consult the documentation of mpi4py and the mpi4py.MPIPoolExecutor class.

Note: in keeping consistent with the API of parallel_map, the parameter determining the number of requested worker processes is called num_cpus. The value of map_kw[‘num_cpus’] is passed to the MPIPoolExecutor as its max_workers argument. If this parameter is not provided, the environment variable QUTIP_NUM_PROCESSES is used instead. If this environment variable is not set either, QuTiP will use default values that might be unsuitable for MPI applications.

Parameters:
taska Python function

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

valuesarray / list

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

task_argslist, optional

The optional additional arguments to the task function.

task_kwargsdictionary, optional

The optional additional keyword arguments to the task function.

reduce_funcfunc, optional

If provided, it will be called with the output of each task instead of storing them in a list. Note that the order in which results are passed to reduce_func is not defined. It should return None or a number. When returning a number, it represents the estimation of the number of tasks left. On a return <= 0, the map will end early.

progress_barstr, optional

Progress bar options’s string for showing progress.

progress_bar_kwargsdict, optional

Options for the progress bar.

map_kw: dict, optional

Dictionary containing entry for: - timeout: float, Maximum time (sec) for the whole map. - num_cpus: int, Number of jobs to run at once. - fail_fast: bool, Abort at the first error. All remaining entries of map_kw will be passed to the mpi4py.MPIPoolExecutor constructor.

Returns:
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values. If a reduce_func is provided, and empty list will be returned.

parallel_map(task, values, task_args=None, task_kwargs=None, reduce_func=None, map_kw=None, progress_bar=None, progress_bar_kwargs={})[source]

Parallel execution of a mapping of values to the function task. This is functionally equivalent to:

result = [task(value, *task_args, **task_kwargs) for value in values]
Parameters:
taska Python function

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

valuesarray / list

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

task_argslist, optional

The optional additional arguments to the task function.

task_kwargsdictionary, optional

The optional additional keyword arguments to the task function.

reduce_funcfunc, optional

If provided, it will be called with the output of each task instead of storing them in a list. Note that the order in which results are passed to reduce_func is not defined. It should return None or a number. When returning a number, it represents the estimation of the number of tasks left. On a return <= 0, the map will end early.

progress_barstr, optional

Progress bar options’s string for showing progress.

progress_bar_kwargsdict, optional

Options for the progress bar.

map_kw: dict, optional

Dictionary containing entry for: - timeout: float, Maximum time (sec) for the whole map. - num_cpus: int, Number of jobs to run at once. - fail_fast: bool, Abort at the first error.

Returns:
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values. If a reduce_func is provided, and empty list will be returned.

serial_map(task, values, task_args=None, task_kwargs=None, reduce_func=None, map_kw=None, progress_bar=None, progress_bar_kwargs={})[source]

Serial mapping function with the same call signature as parallel_map, for easy switching between serial and parallel execution. This is functionally equivalent to:

result = [task(value, *task_args, **task_kwargs) for value in values]

This function work as a drop-in replacement of parallel_map.

Parameters:
taska Python function

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

valuesarray / list

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

task_argslist, optional

The optional additional argument to the task function.

task_kwargsdictionary, optional

The optional additional keyword argument to the task function.

reduce_funcfunc, optional

If provided, it will be called with the output of each tasks instead of storing a them in a list. It should return None or a number. When returning a number, it represent the estimation of the number of task left. On a return <= 0, the map will end early.

progress_barstr, optional

Progress bar options’s string for showing progress.

progress_bar_kwargsdict, optional

Options for the progress bar.

map_kw: dict, optional

Dictionary containing: - timeout: float, Maximum time (sec) for the whole map. - fail_fast: bool, Raise an error at the first.

Returns:
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values. If a reduce_func is provided, and empty list will be returned.

IPython Notebook Tools

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

version_table(verbose=False)[source]

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.

Parameters:
verbosebool, default: False

Add extra information about install location.

Returns:
version_table: str

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

Miscellaneous

about()[source]

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

simdiag(ops, evals: bool = True, *, tol: float = 1e-14, safe_mode: bool = True)[source]

Simultaneous diagonalization of commuting Hermitian matrices.

Parameters:
opslist, array

list or array of qobjs representing commuting Hermitian operators.

evalsbool, default: True

Whether to return the eigenvalues for each ops and eigenvectors or just the eigenvectors.

tolfloat, default: 1e-14

Tolerance for detecting degenerate eigenstates.

safe_modebool, default: True

Whether to check that all ops are Hermitian and commuting. If set to False and operators are not commuting, the eigenvectors returned will often be eigenvectors of only the first operator.

Returns:
eigstuple

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