Functions¶
Manipulation and Creation of States and Operators¶
Quantum States¶

basis
(dimensions, n=None, offset=None, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Generates the vector representation of a Fock state.
 Parameters
 dimensionsint or list of ints
Number of Fock 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. ifdimensions
is a list, thenn
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
storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 state
qutip.Qobj
Qobj representing the requested number state
n>
.
 state
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=<class 'qutip.core.data.dense.Dense'>)[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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 Bell_stateqobj
Bell state

bra
(seq, dim=2, *, dtype=<class 'qutip.core.data.dense.Dense'>)[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
Storage representation. Any datalayer 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=<class 'qutip.core.data.dense.Dense'>)[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 nonzero offset will make the default method ‘analytic’.
 methodstring {‘operator’, ‘analytic’}
Method for generating coherent state.
 dtypetype or str
Storage representation. Any datalayer 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.69233235e01+0.j ] [ 0.00000000e+00+0.24230831j] [ 4.28344935e02+0.j ] [ 0.00000000e+000.00618204j] [ 7.80904967e04+0.j ]]

coherent_dm
(N, alpha, offset=0, method='operator', *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Density matrix representation of a coherent state.
Constructed via outer product of
qutip.states.coherent
 Parameters
 Nint
Number of Fock 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’}
Method for generating coherent density matrix.
 dtypetype or str
Storage representation. Any datalayer 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.000000000.23480733j 0.04216943+0.j ] [ 0.00000000+0.23480733j 0.05869011+0.j 0.000000000.01054025j] [0.04216943+0.j 0.00000000+0.01054025j 0.00189294+0.j ]]

enr_fock
(dims, excitations, state, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Generate the Fock state representation in a excitationnumber 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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 ketQobj
A Qobj instance that represent a Fock state in the exicationnumber restricted state space defined by dims and exciations.

enr_state_dictionaries
(dims, excitations)[source]¶ Return the number of states, and lookupdictionaries 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 subsystem.
 excitationsinteger
The maximum numbers of dimension
 Returns
 nstates, state2idx, idx2state: integer, dict, list
The number of states nstates, a dictionary for looking up state indices from a state tuple, and a list containing the state tuples ordered by 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=<class 'qutip.core.data.csr.CSR'>)[source]¶ Generate the density operator for a thermal state in the excitationnumber 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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 dmQobj
Thermal state density matrix.

fock
(dimensions, n=None, offset=None, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Bosonic Fock (number) state.
Same as
qutip.states.basis
. Parameters
 dimensionsint or list of ints
Number of Fock 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. ifdimensions
is a list, thenn
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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 Requested number state \(\leftn\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=<class 'qutip.core.data.csr.CSR'>)[source]¶ Density matrix representation of a Fock state
Constructed via outer product of
qutip.states.fock
. Parameters
 dimensionsint or list of ints
Number of Fock 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. ifdimensions
is a list, thenn
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
Storage representation. Any datalayer 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=3, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶  Returns the Nqubit GHZstate:
[ 00...00> + 11...11> ] / sqrt(2)
 Parameters
 Nint (default=3)
Number of qubits in state
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 Gqobj
Nqubit GHZstate

ket
(seq, dim=2, *, dtype=<class 'qutip.core.data.dense.Dense'>)[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 (default: 2) / list of ints
Space dimension for each particle: int if there are the same, list if they are different.
 dtypetype or str
Storage representation. Any datalayer 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
(N, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Returns the maximally mixed density matrix for a Hilbert space of dimension N.
 Parameters
 Nint
Number of basis states in Hilbert space.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 dmqobj
Thermal state density matrix.

phase_basis
(N, m, phi0=0, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Basis vector for the mth phase of the PeggBarnett phase operator.
 Parameters
 Nint
Number of basis vectors 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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 stateqobj
Ket vector for mth PeggBarnett phase operator basis state.
Notes
The PeggBarnett basis states form a complete set over the truncated Hilbert space.

projection
(N, n, m, offset=None, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ The projection operator that projects state \(\lvert m\rangle\) on state \(\lvert n\rangle\).
 Parameters
 Nint
Number of basis states in Hilbert space.
 n, mfloat
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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Requested projection operator.

qutrit_basis
(*, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Basis states for a three level system (qutrit)
 dtypetype or str
storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 qstatesarray
Array of qutrit basis vectors

singlet_state
(*, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Returns the two particle singletstate:
\[\lvert S\rangle = \frac1{\sqrt2}(\lvert01\rangle\lvert10\rangle)\]that is identical to the fourth bell state.
 Parameters
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 Bell_stateqobj
\(\lvert B_{11}\rangle\) Bell state

spin_coherent
(j, theta, phi, type='ket', *, dtype=<class 'qutip.core.data.dense.Dense'>)[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’}
Type of state to generate.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 stateqobj
Qobj quantum object for spin coherent state

spin_state
(j, m, type='ket', *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Generates the spin state \(\lvert j, m\rangle\), i.e. the eigenstate of the spinj Sz operator with eigenvalue m.
 Parameters
 jfloat
The spin of the state ().
 mint
Eigenvalue of the spinj Sz operator.
 typestring {‘ket’, ‘bra’, ‘dm’}
Type of state to generate.
 dtypetype or str
Storage representation. Any datalayer 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 (None)
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=<class 'qutip.core.data.dense.Dense'>)[source]¶ Return a Qobj representation of a quantum state specified by the state array state.
Example
>>> state_number_qobj([2, 2, 2], [1, 0, 1]) Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket Qobj data = [[ 0.] [ 0.] [ 0.] [ 0.] [ 0.] [ 1.] [ 0.] [ 0.]]
 Parameters
 dimslist or array
The quantum state dimensions array, as it would appear in a Qobj.
 statelist
State number array.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 state
qutip.Qobj
The state as a
qutip.Qobj
instance.
Note
Deprecated in QuTiP 5.0, use
basis
instead. state

thermal_dm
(N, n, method='operator', *, dtype=<class 'qutip.core.data.csr.CSR'>)[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’}
string
that sets the method used to generate the thermal state probabilities dtypetype or str
Storage representation. Any datalayer 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=<class 'qutip.core.data.dense.Dense'>)[source]¶ Returns a list of the two particle tripletstates:
\[\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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 trip_stateslist
2 particle triplet states

w_state
(N=3, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶  Returns the Nqubit Wstate:
[ 100..0> + 010..0> + 001..0> + ... 000..1> ] / sqrt(n)
 Parameters
 Nint (default=3)
Number of qubits in state
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 W
Qobj
Nqubit Wstate
 W

zero_ket
(N, dims=None, *, dtype=<class 'qutip.core.data.dense.Dense'>)[source]¶ Creates the zero ket vector with shape Nx1 and dimensions dims.
 Parameters
 Nint
Hilbert space dimensionality
 dimslist
Optional dimensions if ket corresponds to a composite Hilbert space.
 dtypetype or str
Storage representation. Any datalayer 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=<class 'qutip.core.data.csr.CSR'>)[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
Storage representation. Any datalayer 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.

create
(N, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Creation (raising) operator.
 Parameters
 Nint
Dimension of Hilbert space.
 offsetint (default 0)
The lowest number state that is included in the finite number state representation of the operator.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Qobj for raising operator.
 offsetint (default 0)
The lowest number state that is included in the finite number state representation of the operator.
Examples
>>> create(4) Quantum object: dims=[[4], [4]], shape=(4, 4), type='oper', isherm=False Qobj data = [[ 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j] [ 1.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j] [ 0.00000000+0.j 1.41421356+0.j 0.00000000+0.j 0.00000000+0.j] [ 0.00000000+0.j 0.00000000+0.j 1.73205081+0.j 0.00000000+0.j]]

destroy
(N, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Destruction (lowering) operator.
 Parameters
 Nint
Dimension of Hilbert space.
 offsetint (default 0)
The lowest number state that is included in the finite number state representation of the operator.
 dtypetype or str
Storage representation. Any datalayer 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=<class 'qutip.core.data.dense.Dense'>)[source]¶ Singlemode displacement operator.
 Parameters
 Nint
Dimension of 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
Storage representation. Any datalayer 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]]

enr_destroy
(dims, excitations, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Generate annilation operators for modes in a excitationnumberrestricted 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 expectationvalue 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
Storage representation. Any datalayer 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_identity
(dims, excitations, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Generate the identity operator for the excitationnumber 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.
 statelist of integers
The state in the number basis representation.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
A Qobj instance that represent the identity operator in the exicationnumberrestricted state space defined by dims and exciations.

identity
(dimensions, *, dtype=<class 'qutip.core.data.csr.CSR'>)¶ Identity operator.
 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. dtypetype or str
Storage representation. Any datalayer 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=<class 'qutip.core.data.csr.CSR'>)[source]¶ Higherorder spin operators:
 Parameters
 jfloat
Spin of operator
 whichstr
Which operator to return ‘x’,’y’,’z’,’+’,’‘. If no args given, then output is [‘x’,’y’,’z’]
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 jmatQobj or tuple of Qobj
qobj
for requested spin operator(s).
Notes
If no ‘args’ input, then returns array of [‘x’,’y’,’z’] operators.
Examples
>>> jmat(1) [ Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 0. 0.70710678 0. ] [ 0.70710678 0. 0.70710678] [ 0. 0.70710678 0. ]] Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 0.+0.j 0.0.70710678j 0.+0.j ] [ 0.+0.70710678j 0.+0.j 0.0.70710678j] [ 0.+0.j 0.+0.70710678j 0.+0.j ]] Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 1. 0. 0.] [ 0. 0. 0.] [ 0. 0. 1.]]]

momentum
(N, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Momentum operator p=1j/sqrt(2)*(aa.dag())
 Parameters
 Nint
Number of Fock states in Hilbert space.
 offsetint (default 0)
The lowest number state that is included in the finite number state representation of the operator.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Momentum operator as Qobj.

num
(N, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Quantum object for number operator.
 Parameters
 Nint
The dimension of 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
Storage representation. Any datalayer 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=<class 'qutip.core.data.dense.Dense'>)[source]¶ Singlemode PeggBarnett phase operator.
 Parameters
 Nint
Number of basis states in Hilbert space.
 phi0float
Reference phase.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Phase operator with respect to reference phase.
Notes
The PeggBarnett phase operator is Hermitian on a truncated Hilbert space.

position
(N, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Position operator x=1/sqrt(2)*(a+a.dag())
 Parameters
 Nint
Number of Fock states in Hilbert space.
 offsetint (default 0)
The lowest number state that is included in the finite number state representation of the operator.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Position operator as Qobj.

qdiags
(diagonals, offsets=None, dims=None, shape=None, *, dtype=<class 'qutip.core.data.csr.CSR'>)[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
Storage representation. Any datalayer 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=<class 'qutip.core.data.csr.CSR'>)[source]¶ Identity operator.
 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. dtypetype or str
Storage representation. Any datalayer 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.]]

qutrit_ops
(*, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Operators for a three level system (qutrit).
 Parameters
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opers: array
array of qutrit operators.

qzero
(dimensions, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Zero operator.
 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. dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 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 sigmax 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 sigmay 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 sigmaz 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=<class 'qutip.core.data.csr.CSR'>)[source]¶ Spinj annihilation operator
 Parameters
 jfloat
Spin of operator
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
qobj
representation of the operator.

spin_Jp
(j, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Spinj creation operator
 Parameters
 jfloat
Spin of operator
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
qobj
representation of the operator.

spin_Jx
(j, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Spinj x operator
 Parameters
 jfloat
Spin of operator
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
qobj
representation of the operator.

spin_Jy
(j, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Spinj y operator
 Parameters
 jfloat
Spin of operator
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
qobj
representation of the operator.

spin_Jz
(j, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Spinj z operator
 Parameters
 jfloat
Spin of operator
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 opQobj
qobj
representation of the operator.

squeeze
(N, z, offset=0, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Singlemode 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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 oper
qutip.Qobj
Squeezing operator.
 oper
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
 a1
qutip.Qobj
Operator 1.
 a2
qutip.Qobj
Operator 2.
 zfloat/complex
Squeezing parameter.
 a1
 Returns
 oper
qutip.Qobj
Squeezing operator.
 oper

tunneling
(N, m=1, *, dtype=<class 'qutip.core.data.csr.CSR'>)[source]¶ Tunneling operator with elements of the form \(\\sum N><N+m + N+m><N\).
 Parameters
 Nint
Number of basis states in Hilbert space.
 mint (default = 1)
Number of excitations in tunneling event.
 dtypetype or str
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 TQobj
Tunneling operator.
Notes
New in version 3.2.
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
 Q
qutip.Qobj
Composite quantum object.
 selint/list
An
int
orlist
of components to keep after partial trace.
 Q
 Returns
 oper
qutip.Qobj
Quantum object representing partial trace with selected components remaining.
 oper
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=<class 'qutip.core.data.csr.CSR'>)[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 eitheroper
orsuper
depending on the passeddimensions
. densityfloat
Density between [0,1] of output density matrix. Used by the “pure”, “eigen” and “herm”.
 distributionstr {“ginibre”, “hs”, “pure”, “eigen”, “uniform”}
Method used to obtain the density matrices.
“ginibre” : Ginibre random density operator of rank
rank
by using the algorithm of [BCSZ08].“hs” : HilbertSchmidt 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
Storage representation. Any datalayer 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=<class 'qutip.core.data.csr.CSR'>)[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, [0.30]
Density between [0,1] of output Hermitian operator.
 distributionstr {“fill”, “pos_def”, “eigen”}
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 semidefinite 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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 oper
qobj
Hermitian quantum operator.
 oper
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=<class 'qutip.core.data.dense.Dense'>)[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, [1]
Density between [0,1] of output ket state when using the
fill
method. distributionstr {“haar”, “fill”}
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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Ket quantum state vector.

rand_stochastic
(dimensions, density=0.75, kind='left', *, seed=None, dtype=<class 'qutip.core.data.csr.CSR'>)[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, [0.75]
Density between [0,1] of output density matrix.
 kindstr (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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Quantum operator form of stochastic matrix.

rand_super
(dimensions, *, superrep='super', seed=None, dtype=<class 'qutip.core.data.dense.Dense'>)[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, optional, {“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
Storage representation. Any datalayer known to qutip.data.to is accepted.

rand_super_bcsz
(dimensions, enforce_tp=True, rank=None, *, superrep='super', seed=None, dtype=<class 'qutip.core.data.csr.CSR'>)[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 fullrank, 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
If True, the tracepreserving condition of [BCSZ08] is enforced; otherwise only complete positivity is enforced.
 rankint or None
Rank of the sampled superoperator. If None, a fullrank 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, optional, {“super”}
representation of the
 dtypetype or str
Storage representation. Any datalayer 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=<class 'qutip.core.data.dense.Dense'>)[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, [1]
Density between [0,1] of output unitary operator.
 distribution[“haar”, “exp”]
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
Storage representation. Any datalayer known to qutip.data.to is accepted.
 Returns
 operqobj
Unitary quantum operator.
ThreeLevel Atoms¶
This module provides functions that are useful for simulating the three level atom with QuTiP. A three level atom (qutrit) has three states, which are linked by dipole transitions so that 1 <> 2 <> 3. Depending on there relative energies they are in the ladder, lambda or vee configuration. The structure of the relevant operators is the same for any of the three configurations:
Ladder: Lambda: Vee:
two> three>
three>  
 / \ one> /
 / \  /
 / \ \ /
two> / \ \ /
 / \ \ /
 / \ \ /
 /  \ /
one>  three> 
one> two>
References
The naming of qutip operators follows the convention in [1] .
 1
Shore, B. W., “The Theory of Coherent Atomic Excitation”, Wiley, 1990.
Notes
Contributed by Markus Baden, Oct. 07, 2011
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 [None]
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 thea \rho a^dagger
term of the dissipator bye ^ (i * chi)
. The factore ^ (i * chi)
is introduced via the generating function of the statistical moments. For examples of the technique, see Full counting statistics of nanoelectromechanical systems and Photonmediated electron transport in hybrid circuitQED. This parameter is deprecated and may be removed in QuTiP 5. data_onlybool [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
A
list
orarray
of collapse operators. data_onlybool [False]
Return the data object instead of a Qobj
 chiarray_like of float [None]
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 thelindblad_dissipator
for each collapse operator. See the documentation oflindblad_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 generalpurpose 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 recast into a columnstackedvector form of type ‘operatorket’. The output is the same type as the passed object.

spost
(A)[source]¶ Superoperator formed from postmultiplication 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 premultiplication by operator A.
 Parameters
 AQobj or QobjEvo
Quantum operator for premultiplication.
 Returns
 super :Qobj or QobjEvo
Superoperator formed from input quantum object.

sprepost
(A, B)[source]¶ Superoperator formed from premultiplication by A and postmultiplication by B.
 Parameters
 AQobj or QobjEvo
Quantum operator for premultiplication.
 BQobj or QobjEvo
Quantum operator for postmultiplication.
 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 ‘operatorket’; this function is not designed for generalpurpose matrix reshaping. Parameters
 opQobj or QobjEvo
Quantum operator in columnstackedvector form. This must have a type of ‘operatorket’.
 Returns
 Qobj or QobjEvo
The same object, but recast 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_list)[source]¶ Take a list of Kraus operators and returns the Choi matrix for the channel represented by the Kraus operators in kraus_list

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
istype="oper"
, then it is taken to act by conjugation, such thatto_chi(A) == to_chi(sprepost(A, A.dag()))
.
 Returns
 chiQobj
A quantum object representing the same map as
q_oper
, such thatchi.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
istype="oper"
, then it is taken to act by conjugation, such thatto_choi(A) == to_choi(sprepost(A, A.dag()))
.
 Returns
 choiQobj
A quantum object representing the same map as
q_oper
, such thatchoi.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=1e09)[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
istype="oper"
, then it is taken to act by conjugation, such thatto_kraus(A) == to_kraus(sprepost(A, A.dag())) == [A]
. tolFloat
Optional threshold parameter for eigenvalues/Kraus ops to be discarded. The default is to=1e9.
 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=1e10)[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.
 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
istype="oper"
, then it is taken to act by conjugation, such thatto_super(A) == sprepost(A, A.dag())
.
 Returns
 superopQobj
A quantum object representing the same map as
q_oper
, such thatsuperop.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.

collapse_dims_oper
(dims)[source]¶ Given the dimensions specifications for a ket, bra or opertype Qobj, returns a dimensions specification describing the same shape by collapsing all composite systems. For instance, the bratype dimensions specification
[[2, 3], [1]]
collapses to[[6], [1]]
. Parameters
 dimslist of lists of ints
Dimensions specifications to be collapsed.
 Returns
 collapsed_dimslist of lists of ints
Collapsed dimensions specification describing the same shape such that
len(collapsed_dims[0]) == len(collapsed_dims[1]) == 1
.

collapse_dims_super
(dims)[source]¶ Given the dimensions specifications for an operatorket, operatorbra or supertype Qobj, returns a dimensions specification describing the same shape by collapsing all composite systems. For instance, the supertype dimensions specification
[[[2, 3], [2, 3]], [[2, 3], [2, 3]]]
collapses to[[[6], [6]], [[6], [6]]]
. Parameters
 dimslist of lists of ints
Dimensions specifications to be collapsed.
 Returns
 collapsed_dimslist of lists of ints
Collapsed dimensions specification describing the same shape such that
len(collapsed_dims[i][j]) == 1
fori
andj
inrange(2)
.

deep_remove
(l, *what)[source]¶ Removes scalars from all levels of a nested list.
Given a list containing a mix of scalars and lists, returns a list of the same structure, but where one or more scalars have been removed.
Examples
>>> deep_remove([[[[0, 1, 2]], [3, 4], [5], [6, 7]]], 0, 5) [[[[1, 2]], [3, 4], [], [6, 7]]]

dims_idxs_to_tensor_idxs
(dims, indices)[source]¶ Given the dims of a Qobj instance, and some indices into dims, returns the corresponding tensor indices. This helps resolve, for instance, that columnstacking for superoperators, operket and operbra implies that the input and output tensor indices are reversed from their order in dims.
 Parameters
 dimslist
Dimensions specification for a Qobj.
 indicesint, list or tuple
Indices to convert to tensor indices. Can be specified as a single index, or as a collection of indices. In the latter case, this can be nested arbitrarily deep. For instance, [0, [0, (2, 3)]].
 Returns
 tens_indicesint, list or tuple
Container of the same structure as indices containing the tensor indices for each element of indices.

dims_to_tensor_perm
(dims)[source]¶ Given the dims of a Qobj instance, returns a list representing a permutation from the flattening of that dims specification to the corresponding tensor indices.
 Parameters
 dimslist
Dimensions specification for a Qobj.
 Returns
 permlist
A list such that
data[flatten(dims)[idx]]
gives the index of the tensordata
corresponding to theidx``th dimension of ``dims
.

dims_to_tensor_shape
(dims)[source]¶ Given the dims of a Qobj instance, returns the shape of the corresponding tensor. This helps, for instance, resolve the columnstacking convention for superoperators.
 Parameters
 dimslist
Dimensions specification for a Qobj.
 Returns
 tensor_shapetuple
NumPy shape of the corresponding tensor.

enumerate_flat
(l)[source]¶ Labels the indices at which scalars occur in a flattened list.
Given a list containing a mix of scalars and lists, returns a list of the same structure, where each scalar has been replaced by an index into the flattened list.
Examples
>>> print(enumerate_flat([[[10], [20, 30]], 40])) [[[0], [1, 2]], 3]

flatten
(l)[source]¶ Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists, flattens down to a list of the scalars within the original list.
Examples
>>> flatten([[[0], 1], 2]) [0, 1, 2]

is_scalar
(dims)[source]¶ Returns True if a dims specification is effectively a scalar (has dimension 1).

unflatten
(l, idxs)[source]¶ Unflattens a list by a given structure.
Given a list of scalars and a deep list of indices as produced by flatten, returns an “unflattened” form of the list. This perfectly inverts flatten.
Examples
>>> l = [[[10, 20, 30], [40, 50, 60]], [[70, 80, 90], [100, 110, 120]]] >>> idxs = enumerate_flat(l) >>> unflatten(flatten(l), idxs) == l True
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/arraylike
A single or a list or operators for expectation value.
 stateqobj/arraylike
A single or a list of quantum states or density matrices.
 Returns
 exptfloat/complex/arraylike
Expectation value.
real
if oper is Hermitian,complex
otherwise. A (nested) array of expectaction values of state or operator are arrays.
Examples
>>> expect(num(4), basis(4, 3)) == 3 True
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 columnreshuffled 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 usingoperator_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
orarray
of quantum objects withtype="super"
.
 Returns
 objqobj
A composite quantum object.

tensor
(*args)[source]¶ Calculates the tensor product of input operators.
 Parameters
 argsarray_like
list
orarray
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
 pairstuple
One or more tuples
(i, j)
indicating that thei
andj
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
 rho
qutip.qobj
A density matrix.
 masklist / array
A mask that selects which subsystems should be transposed.
 methodstr
choice of method, dense or sparse. The default method is dense. The sparse implementation can be faster for large and sparse systems (hundreds of quantum states).
 rho
 Returns
 rho_pr:
qutip.qobj
A density matrix with the selected subsystems transposed.
 rho_pr:
Entropy Functions¶

concurrence
(rho)[source]¶ Calculate the concurrence entanglement measure for a twoqubit state.
 Parameters
 stateqobj
Ket, bra, or density matrix for a twoqubit state.
 Returns
 concurfloat
Concurrence
References

entropy_conditional
(rho, selB, base=2.718281828459045, sparse=False)[source]¶ Calculates the conditional entropy \(S(AB)=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}
Base of logarithm.
 sparse{False,True}
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}
Base of logarithm.
 sparse{False,True}
Use sparse eigensolver.
 Returns
 ent_mutfloat
Mutual information between selected components.

entropy_relative
(rho, sigma, base=2.718281828459045, sparse=False, tol=1e12)[source]¶ Calculates the relative entropy S(rhosigma) between two density matrices.
 Parameters
 rho
qutip.Qobj
First density matrix (or ket which will be converted to a density matrix).
 sigma
qutip.Qobj
Second density matrix (or ket which will be converted to a density matrix).
 base{e,2}
Base of logarithm. Defaults to e.
 sparsebool
Flag to use sparse solver when determining the eigenvectors of the density matrices. Defaults to False.
 tolfloat
Tolerance to use to detect 0 eigenvalues or dot producted between eigenvectors. Defaults to 1e12.
 rho
 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]¶ VonNeumann entropy of density matrix
 Parameters
 rhoqobj
Density matrix.
 base{e,2}
Base of logarithm.
 sparse{False,True}
Use sparse eigensolver.
 Returns
 entropyfloat
VonNeumann 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
 oper
qutip.Qobj
/list A unitary operator, or a superoperator in supermatrix, Choi or chimatrix form, or a list of Kraus operators
 target
qutip.Qobj
A unitary operator
 oper
 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
Solver to use with CVXPY. One of “CVXOPT” (default) or “SCS”. The latter tends to be significantly faster, but somewhat less accurate.
 verbosebool
If True, prints additional information about the solution.
 force_solvebool
If True, forces dnorm to solve the associated SDP, even if a special case is known for the argument.
 sparsebool
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 (pseudometric) 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.
 Returns
 fidfloat
Fidelity pseudometric between A and B.
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(22*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
 A
qutip.Qobj
Density matrix or state vector.
 B
qutip.Qobj
Density matrix or state vector with same dimensions as A.
 tolfloat
Tolerance used by sparse eigensolver, if used. (0=Machine precision)
 sparse{False, True}
Use sparse eigensolver.
 A
 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.testing.assert_almost_equal(hellinger_dist(x,y), 1.3725145002591095)

hilbert_dist
(A, B)[source]¶ Returns the HilbertSchmidt 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
HilbertSchmidt 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
 oper
qutip.Qobj
/list A unitary operator, or a superoperator in supermatrix, Choi or chimatrix form, or a list of Kraus operators
 target
qutip.Qobj
/list A unitary operator, or a superoperator in supermatrix, Choi or chimatrix form, or a list of Kraus operators
 oper
 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 in
control.fidcomp.FidCompUnitary.get_fidelity
. 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 inqutip.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
Tolerance used by sparse eigensolver, if used. (0=Machine precision)
 sparse{False, True}
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)
Continuous Variables¶
This module contains a collection functions for calculating continuous variable quantities from fockbasis representation of the state of multimode 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
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 2dimensional 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
Density matrix for which to calculate the covariance matrix.
 Returns
 cov_matndarray
Array of complex numbers or Qobj’s A 2dimensional 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
Density matrix for which to calculate the covariance matrix.
 gfloat
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 2dimensional 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 {True, False}
Flag indicating whether the symmetrized (default) or nonsymmetrized correlation matrix is to be calculated.
 Returns
 corr_matndarray
A 2dimensional 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 twomode field state that is described by V must be Gaussian for this function to applicable. Parameters
 V2d array
The covariance matrix.
 gfloat
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 twomode 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
Field operator for mode 1.
 a2Qobj
Field operator for mode 2.
 Rndarray
The quadrature correlation matrix.
 rhoQobj
Density matrix for which to calculate the covariance matrix.
 gfloat
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 2dimensional array of covariance values.
Measurement¶
Measurement of quantum states¶
Module for measuring quantum objects.

measure
(state, ops)[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:
measure_observable
for observable measurements.measure_povm
for POVM measurements.

measure_observable
(state, op)[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
 Returns
 measured_valuefloat
The result of the measurement (one of the eigenvalues of op).
 state
Qobj
The new state (a ket if a ket was given, otherwise a density matrix).
Examples
Measure the zcomponent of the spin of the spinup 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 spinup basis is an eigenstate of sigmaz, this measurement always returns 1 as the measurement result (the eigenvalue of the spinup basis) and the original state (up to a global phase).
Measure the xcomponent of the spin of the spindown 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 spindown 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)[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
 state
Qobj
The ket or density matrix specifying the state to measure.
 opslist of
Qobj
List of measurement operators \(M_i\) or kets. Either:
specifying a POVM s.t. \(E_i = M_i^\dagger M_i\)
projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))
kets (transformed to projectors)
 state
 Returns
 indexfloat
The resultant index of the measurement.
 state
Qobj
The new state (a ket if a ket was given, otherwise a density matrix).

measurement_statistics
(state, ops)[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:
measurement_statistics_observable
for observable measurements.measurement_statistics_povm
for POVM measurements.
 Parameters
 state
Qobj
The ket or density matrix specifying the state to measure.
 ops
Qobj
or list ofQobj
measurement observable (:class:.Qobj); or
list of measurement operators \(M_i\) or kets (list of
Qobj
) Either:specifying a POVM s.t. \(E_i = M_i^\dagger * M_i\)
projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))
kets (transformed to projectors)
 state

measurement_statistics_observable
(state, op)[source]¶ Return the measurement eigenvalues, eigenstates (or projectors) and measurement probabilities for the given state and measurement operator.
 Parameters
 Returns
 eigenvalues: list of float
The list of eigenvalues of the measurement operator.
 eigenstates_or_projectors: list of
Qobj
If the state was a ket, return the eigenstates of the measurement operator. Otherwise 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)[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
 state
Qobj
The ket or density matrix specifying the state to measure.
 opslist of
Qobj
List of measurement operators \(M_i\) or kets. Either:
specifying a POVM s.t. \(E_i = M_i^\dagger M_i\)
projection operators if ops correspond to projectors (s.t. \(E_i = M_i^\dagger = M_i\))
kets (transformed to projectors)
 state
 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.
 collapsed_stateslist of
Dynamics and TimeEvolution¶
Schrödinger Equation¶
This module provides solvers for the unitary Schrodinger equation.

sesolve
(H, psi0, tlist, e_ops=None, args=None, options=None)[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
Timedependent operators
For timedependent problems, H and c_ops can be a
QobjEvo
or object that can be interpreted asQobjEvo
such as a list of (Qobj, Coefficient) pairs or a function. Parameters
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. System Hamiltonian as a Qobj or QobjEvo for timedependent Hamiltonians. List of [
Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. psi0
qutip.qobj
initial state vector (ket) or initial unitary operator psi0 = U
 tlistlist / array
list of times for \(t\).
 e_ops
qutip.qobj
, callable, or list. 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. argsNone / dictionary
dictionary of parameters for timedependent Hamiltonians
 optionsNone / dict
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 : 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.
 H
 Returns
 result:
qutip.Result
An instance of the class
qutip.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].
 result:
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)[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.
Timedependent operators
For timedependent problems, H and c_ops can be a
QobjEvo
or object that can be interpreted asQobjEvo
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.
Note
When no collapse operator are given and the H is not a superoperator, it will defer to
sesolve
. Parameters
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. Possibly timedependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. List of [
Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. rho0
Qobj
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 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. argsNone / dictionary
dictionary of parameters for timedependent Hamiltonians and collapse operators.
 optionsNone / dict
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 : 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.
 H
 Returns
 result:
qutip.Result
An instance of the class
qutip.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].
 result:
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)[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
 H
qutip.Qobj
,qutip.QobjEvo
,list
, callable. System Hamiltonian as a Qobj, QobjEvo. It can also be any input type that QobjEvo accepts (see
qutip.QobjEvo
’s documentation).H
can also be a superoperator (liouvillian) if some collapse operators are to be treated deterministically. state
qutip.Qobj
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 (seequtip.QobjEvo
’s documentation). They must be operators even ifH
is a superoperator. If none are given, the solver will defer tosesolve
ormesolve
. e_opslist, [optional]
A
list
of operator as Qobj, QobjEvo or callable with signature of (t, state: Qobj) for calculating expectation values. When noe_ops
are given, the solver will default to save the states. ntrajint
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, seetarget_tol
. argsNone / dict
Arguments for timedependent Hamiltonian and collapse operator terms.
 optionsNone / dict
Dictionary of options for the solver.
store_final_state : bool [False] Whether or not to store the final state of the evolution in the result class.
store_states : bool, NoneType, [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’, ‘’}, [‘text’] 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, [{“chunk_size”: 10}] kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
method : str {“adams”, “bdf”, “dop853”, “vern9”, etc.} [“adams”] Which differential equation integration method to use.
keep_runs_results : bool, [False] Whether to store results from all trajectories or just store the averages.
map : str {“serial”, “parallel”, “loky”}, [“serial”] How to run the trajectories. “parallel” uses concurent module to run in parallel while “loky” use the module of the same name to do so.
job_timeout : NoneType, int, [None] Maximum time to compute one trajectory.
num_cpus : NoneType, int, [None] 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, [1e6, 1e4, 5] Parameters used to find the collapse location.
norm_t_tol
andnorm_tol
are the tolerance in time and norm respectively. An error will be raised if the collapse could not be found withinnorm_steps
tries.mc_corr_eps : float, [1e10] Small number used to detect nonphysical collapse caused by numerical imprecision.
atol, rtol : float, [1e8, 1e6] Absolute and relative tolerance of the ODE integrator.
nsteps : int [2500] 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.
 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.
 H
 Returns
 results
qutip.solver.Result
Object storing all results from the simulation. Which results is saved depends on the presence of
e_ops
and the options used.collapse
andphotocurrent
is available to Monte Carlo simulation results.
 results
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
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. System Hamiltonian as a Qobj or QobjEvo for timedependent Hamiltonians. List of [
Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. psi0
qutip.qobj
initial state vector (ket) or initial unitary operator psi0 = U
 tlistlist / array
list of times for \(t\).
 krylov_dim: int
Dimension of Krylov approximation subspaces used for the time evolution approximation.
 e_ops
qutip.qobj
, callable, or list. 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. argsNone / dictionary
dictionary of parameters for timedependent Hamiltonians
 optionsNone / dict
Dictionary of options for the solver.
store_final_state : bool, [False] 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, [True] Normalize output state to hide ODE numerical errors.
progress_bar : str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}, [“text”] 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, [{“chunk_size”: 10}] kwargs to pass to the progress_bar. Qutip’s bars use chunk_size.
atol: float [1e7] Absolute and relative tolerance of the ODE integrator.
nsteps : int [100] Maximum number of (internally defined) steps allowed in one
tlist
step.min_step, max_step : float, [1e5, 1e5] Miniumum and maximum lenght of one internal step.
always_compute_step: bool [False] 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, [1e7] 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
.
 H
 Returns
 result:
qutip.Result
An instance of the class
qutip.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].
 result:
BlochRedfield 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={}, sec_cutoff=0.1, options=None)[source]¶ Solves for the dynamics of a system using the BlochRedfield master equation, given an input Hamiltonian, Hermitian bathcoupling terms and their associated spectral functions, as well as possible Lindblad collapse operators.
 Parameters
 H
Qobj
,QobjEvo
Possibly timedependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. list of [
Qobj
,Coefficient
] or callable that can be made intoQobjEvo
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_op
qutip.Qobj
,qutip.QobjEvo
The operator coupling to the environment. Must be hermitian.
 spectra
Coefficient
, 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 oft
. Function are expected to be of the signaturef(w)
orf(t, w, **args)
.The spectra function can depend on
t
if the correspondinga_op
is aQobjEvo
.
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))), ]
 a_op
 e_opslist of
Qobj
/ callback function 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) List of collapse operators.
 argsdict
Dictionary of parameters for timedependent Hamiltonians and collapse operators. The key
w
is reserved for the spectra function. sec_cutofffloat {0.1}
Cutoff for secular approximation. Use
1
if secular approximation is not used when evaluating bathcoupling terms. optionsNone / dict
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 : 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.
 H
 Returns
 result:
qutip.solver.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.
 result:
Floquet States and FloquetMarkov Master Equation¶

class
FMESolver
(floquet_basis, a_ops, w_th=0.0, *, kmax=5, nT=None, options=None)[source]¶ Solver for the FloquetMarkov master equation.
Note
Operators (
c_ops
ande_ops
) are in the laboratory basis. Parameters
 floquet_basis
qutip.FloquetBasis
The system Hamiltonian wrapped in a FloquetBasis object. Choosing a different integrator for the
floquet_basis
than for the evolution of the floquet state can improve the performance. a_opslist of tuple(
qutip.Qobj
, callable) List of collapse operators and the corresponding function for the noise power spectrum. The collapse operator must be a
Qobj
and cannot be time dependent. The spectrum function must take and return an numpy array. w_thfloat
The temperature of the environment in units of Hamiltonian frequency.
 kmaxint [5]
The truncation of the number of sidebands..
 nTint [20*kmax]
The number of integration steps (for calculating X) within one period.
 optionsdict, optional
Options for the solver, see
FMESolver.options
and Integrator for a list of all options.
 floquet_basis

resultclass
¶ alias of
qutip.solver.floquet.FloquetResult

run
(state0, tlist, *, floquet=False, args=None, e_ops=None)[source]¶ Calculate the evolution of the quantum system.
For a
state0
at timetlist[0]
do the evolution as directed byrhs
and for each time intlist
store the state and/or expectation values in aResult
. The evolution method and stored results are determined byoptions
. Parameters
 state0
Qobj
Initial state of the evolution.
 tlistlist of double
Time for which to save the results (state and/or expect) of the evolution. The first element of the list is the initial time of the evolution. Each times of the list must be increasing, but does not need to be uniformy distributed.
 floquetbool, optional {False}
Whether the initial state in the floquet basis or laboratory basis.
 argsdict, optional {None}
Not supported
 e_opslist {None}
List of Qobj, QobjEvo or callable to compute the expectation values. Function[s] must have the signature f(t : float, state : Qobj) > expect.
 state0
 Returns
 results
qutip.solver.FloquetResult
Results of the evolution. States and/or expect will be saved. You can control the saved data in the options.
 results

start
(state0, t0, *, floquet=False)[source]¶ Set the initial state and time for a step evolution.
options
for the evolutions are read at this step. Parameters
 state0
Qobj
Initial state of the evolution.
 t0double
Initial time of the evolution.
 floquetbool, optional {False}
Whether the initial state is in the floquet basis or laboratory basis.
 state0

step
(t, *, args=None, copy=True, floquet=False)[source]¶ Evolve the state to
t
and return the state as aQobj
. Parameters
 tdouble
Time to evolve to, must be higher than the last call.
 copybool, optional {True}
Whether to return a copy of the data or the data in the ODE solver.
 floquetbool, optional {False}
Whether to return the state in the floquet basis or laboratory basis.
 argsdict, optional {None}
Not supported
 .. note::
The state must be initialized first by calling
start
orrun
. Ifrun
is called,step
will continue from the last time and state obtained.

class
FloquetBasis
(H, T, args=None, options=None, sparse=False, sort=True, precompute=None)[source]¶ Utility to compute floquet modes and states.
 Attributes
 U
Propagator
The propagator of the Hamiltonian over one period.
 evecs
qutip.data.Data
Matrix where each column is an initial Floquet mode.
 e_quasinp.ndarray[float]
The quasi energies of the Hamiltonian.
 U

from_floquet_basis
(floquet_basis, t=0)[source]¶ Transform a ket or density matrix from the Floquet basis at time
t
to the lab basis. Parameters
 floquet_basis
Qobj
,qutip.data.Data
Initial state in the Floquet basis at time
t
. May be either a ket or density matrix. tfloat [0]
The time at which to evaluate the Floquet states.
 floquet_basis
 Returns
 output
Qobj
,qutip.data.Data
The state in the lab basis. The return type is the same as the type of the input state.
 output

mode
(t, data=False)[source]¶ Calculate the Floquet modes at time
t
. Parameters
 tfloat
The time for which to evaluate the Floquet mode.
 databool [False]
Whether to return the states as a single data matrix or a list of ket states.
 Returns
 outputlist[
Qobj
],qutip.data.Data
A list of Floquet states for the time
t
or the states as column in a single matrix.
 outputlist[

state
(t, data=False)[source]¶ Evaluate the floquet states at time t.
 Parameters
 tfloat
The time for which to evaluate the Floquet states.
 databool [False]
Whether to return the states as a single data matrix or a list of ket states.
 Returns
 outputlist[
Qobj
],qutip.data.Data
A list of Floquet states for the time
t
or the states as column in a single matrix.
 outputlist[

to_floquet_basis
(lab_basis, t=0)[source]¶ Transform a ket or density matrix in the lab basis to the Floquet basis at time
t
. Parameters
 lab_basis
Qobj
,qutip.data.Data
Initial state in the lab basis.
 tfloat [0]
The time at which to evaluate the Floquet states.
 lab_basis
 Returns
 output
Qobj
,qutip.data.Data
The state in the Floquet basis. The return type is the same as the type of the input state.
 output

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
 H
QobjEvo
Periodic Hamiltonian
 Tfloat
The period of the timedependence of the hamiltonian.
 c_opslist of
qutip.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
The temperature in units of frequency.
 kmaxint
The truncation of the number of sidebands (default 5).
 H
 Returns
 outputarray
The FloquetMarkov 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 FloquetMarkov master equation.
 Parameters
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. Periodic system Hamiltonian as
QobjEvo
. List of [Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. rho0 / psi0
qutip.Qobj
Initial density matrix or state vector (ket).
 tlistlist / array
List of times for \(t\).
 c_opslist of
qutip.Qobj
List of collapse operators. Time dependent collapse operators are not supported.
 e_opslist of
qutip.Qobj
/ callback function List of operators for which to evaluate expectation values. The states are reverted to the lab basis before applying the
 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.
 Tfloat
The period of the timedependence of the hamiltonian. The default value ‘None’ indicates that the ‘tlist’ spans a single period of the driving.
 w_thfloat
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 = 25e3 # unit K h = 6.626e34 kB = 1.38e23 args[‘w_th’] = temperature * (kB / h) * 2 * pi * 1e9
 argsdictionary
Dictionary of parameters for timedependent Hamiltonian
 optionsNone / dict
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 : 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.
 H
 Returns
 result:
qutip.Result
An instance of the class
qutip.Result
, which contains the expectation values for the times specified by tlist, and/or the state density matrices corresponding to the times.
 result:

fsesolve
(H, psi0, tlist, e_ops=None, T=0.0, args=None, options=None)[source]¶ Solve the Schrodinger equation using the Floquet formalism.
 Parameters
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. Periodic system Hamiltonian as
QobjEvo
. List of [Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. psi0
qutip.qobj
Initial state vector (ket). If an operator is provided,
 tlistlist / array
List of times for \(t\).
 e_opslist of
qutip.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 timedependence 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.
 H
 Returns
 output
qutip.solver.Result
An instance of the class
qutip.solver.Result
, which contains either an array of expectation values or an array of state vectors, for the times specified by tlist.
 output
Stochastic Schrödinger Equation and Master Equation¶

general_stochastic
(state0, times, d1, d2, e_ops=[], m_ops=[], _safe_mode=True, len_d2=1, args={}, **kwargs)[source]¶ Solve stochastic general equation. Dispatch to specific solvers depending on the value of the solver keyword argument.
 Parameters
 state0
qutip.Qobj
Initial state vector (ket) or density matrix as a vector.
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 d1function, callable class
Function representing the deterministic evolution of the system.
 def d1(time (double), state (as a np.array vector)):
return 1d np.array
 d2function, callable class
Function representing the stochastic evolution of the system.
 def d2(time (double), state (as a np.array vector)):
return 2d np.array (N_sc_ops, len(state0))
 len_d2int
Number of output vector produced by d2
 e_opslist of
qutip.Qobj
single operator or list of operators for which to evaluate expectation values. Must be a superoperator if the state vector is a density matrix.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 state0
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

photocurrent_mesolve
(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[], _safe_mode=True, args={}, **kwargs)[source]¶ Solve stochastic master equation using the photocurrent method.
 Parameters
 H
qutip.Qobj
, or time dependent system. System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.
 rho0
qutip.Qobj
Initial density matrix or state vector (ket).
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 c_opslist of
qutip.Qobj
, or time dependent Qobjs. Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation. Can depend on time, see StochasticSolverOptions help for format.
 sc_opslist of
qutip.Qobj
, or time dependent Qobjs. List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. Can depend on time, see StochasticSolverOptions help for format.
 e_opslist of
qutip.Qobj
/ callback function single single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

photocurrent_sesolve
(H, psi0, times, sc_ops=[], e_ops=[], _safe_mode=True, args={}, **kwargs)[source]¶ Solve stochastic schrodinger equation using the photocurrent method.
 Parameters
 H
qutip.Qobj
, or time dependent system. System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.
 psi0
qutip.Qobj
Initial state vector (ket).
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 sc_opslist of
qutip.Qobj
, or time dependent Qobjs. List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. Can depend on time, see StochasticSolverOptions help for format.
 e_opslist of
qutip.Qobj
/ callback function single single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

smepdpsolve
(H, rho0, times, c_ops, e_ops, **kwargs)[source]¶ A stochastic (piecewse deterministic process) PDP solver for density matrix evolution.
 Parameters
 H
qutip.Qobj
System Hamiltonian.
 rho0
qutip.Qobj
Initial density matrix.
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 c_opslist of
qutip.Qobj
Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation.
 sc_opslist of
qutip.Qobj
List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined.
 e_opslist of
qutip.Qobj
/ callback function single single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

smesolve
(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[], _safe_mode=True, args={}, **kwargs)[source]¶ Solve stochastic master equation. Dispatch to specific solvers depending on the value of the solver keyword argument.
 Parameters
 H
qutip.Qobj
, or time dependent system. System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.
 rho0
qutip.Qobj
Initial density matrix or state vector (ket).
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 c_opslist of
qutip.Qobj
, or time dependent Qobjs. Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation. Can depend on time, see StochasticSolverOptions help for format.
 sc_opslist of
qutip.Qobj
, or time dependent Qobjs. List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. Can depend on time, see StochasticSolverOptions help for format.
 e_opslist of
qutip.Qobj
single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

ssepdpsolve
(H, psi0, times, c_ops, e_ops, **kwargs)[source]¶ A stochastic (piecewse deterministic process) PDP solver for wavefunction evolution. For most purposes, use
qutip.mcsolve
instead for quantum trajectory simulations. Parameters
 H
qutip.Qobj
System Hamiltonian.
 psi0
qutip.Qobj
Initial state vector (ket).
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 c_opslist of
qutip.Qobj
Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation.
 e_opslist of
qutip.Qobj
/ callback function single single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

ssesolve
(H, psi0, times, sc_ops=[], e_ops=[], _safe_mode=True, args={}, **kwargs)[source]¶ Solve stochastic schrodinger equation. Dispatch to specific solvers depending on the value of the solver keyword argument.
 Parameters
 H
qutip.Qobj
, or time dependent system. System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.
 psi0
qutip.Qobj
State vector (ket).
 timeslist / array
List of times for \(t\). Must be uniformly spaced.
 sc_opslist of
qutip.Qobj
, or time dependent Qobjs. List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. Can depend on time, see StochasticSolverOptions help for format.
 e_opslist of
qutip.Qobj
single operator or list of operators for which to evaluate expectation values.
 kwargsdictionary
Optional keyword arguments. See
qutip.stochastic.StochasticSolverOptions
.
 H
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:

stochastic_solvers
()[source]¶ This function is purely a reference point for documenting the available stochastic solver methods, and takes no actions.
Notes
 Available solvers for
ssesolve
andsmesolve
 eulermaruyama
A simple generalization of the Euler method for ordinary differential equations to stochastic differential equations. Only solver which could take noncommuting
sc_ops
. not testedOrder 0.5
Code:
'eulermaruyama'
,'euler'
or0.5
 milstein
An order 1.0 strong Taylor scheme. Better approximate numerical solution to stochastic differential equations. See eq. (2.9) of chapter 12.2 of [1].
Order strong 1.0
Code:
'milstein'
or1.0
 milsteinimp
An order 1.0 implicit strong Taylor scheme. Implicit Milstein scheme for the numerical simulation of stiff stochastic differential equations.
Order strong 1.0
Code:
'milsteinimp'
 predictorcorrector
Generalization of the trapezoidal method to stochastic differential equations. More stable than explicit methods. See eq. (5.4) of chapter 15.5 of [1].
Order strong 0.5, weak 1.0
Codes to only correct the stochastic part (\(\alpha=0\), \(\eta=1/2\)):
'predcorr'
,'predictorcorrector'
or'pceuler'
Codes to correct both the stochastic and deterministic parts (\(\alpha=1/2\), \(\eta=1/2\)):
'pceulerimp'
,'pceuler2'
or'predcorr2'
 platen
Explicit scheme, creates the Milstein using finite differences instead of analytic derivatives. Also contains some higher order terms, thus converges better than Milstein while staying strong order 1.0. Does not require derivatives, therefore usable by
general_stochastic
. See eq. (7.47) of chapter 7 of [2].Order strong 1.0, weak 2.0
Code:
'platen'
,'platen1'
or'explicit1'
 rouchon
Scheme keeping the positivity of the density matrix (
smesolve
only). See eq. (4) with \(\eta=1\) of [3].Order strong 1.0?
Code:
'rouchon'
or'Rouchon'
 taylor1.5
Order 1.5 strong Taylor scheme. Solver with more terms of the ItoTaylor expansion. Default solver for
smesolve
andssesolve
. See eq. (4.6) of chapter 10.4 of [1].Order strong 1.5
Code:
'taylor1.5'
,'taylor15'
,1.5
, orNone
 taylor1.5imp
Order 1.5 implicit strong Taylor scheme. Implicit Taylor 1.5 (\(\alpha = 1/2\), \(\beta\) doesn’t matter). See eq. (2.18) of chapter 12.2 of [1].
Order strong 1.5
Code:
'taylor1.5imp'
or'taylor15imp'
 explicit1.5
Explicit order 1.5 strong schemes. Reproduce the order 1.5 strong Taylor scheme using finite difference instead of derivatives. Slower than
taylor15
but usable bygeneral_stochastic
. See eq. (2.13) of chapter 11.2 of [1].Order strong 1.5
Code:
'explicit1.5'
,'explicit15'
or'platen15'
 taylor2.0
Order 2 strong Taylor scheme. Solver with more terms of the Stratonovich expansion. See eq. (5.2) of chapter 10.5 of [1].
Order strong 2.0
Code:
'taylor2.0'
,'taylor20'
or2.0
All solvers, except taylor2.0, are usable in both smesolve and ssesolve and for both heterodyne and homodyne. taylor2.0 only works for 1 stochastic operator independent of time with the homodyne method.
general_stochastic
only accepts the derivativefree solvers:'euler'
,'platen'
and'explicit1.5'
. Available solvers for
photocurrent_sesolve
andphotocurrent_mesolve
Photocurrent use ordinary differential equations between stochastic “jump/collapse”.
 euler
Euler method for ordinary differential equations between jumps. Only one jump per time interval. Default solver. See eqs. (4.19) and (4.4) of chapter 4 of [4].
Order 1.0
Code:
'euler'
 predictor–corrector
predictor–corrector method (PECE) for ordinary differential equations. Uses the Poisson distribution to obtain the number of jumps at each timestep.
Order 2.0
Code:
'predcorr'
References
 1(1,2,3,4,5,6)
Peter E. Kloeden and Exkhard Platen, Numerical Solution of Stochastic Differential Equations.
 2
H.P. Breuer and F. Petruccione, The Theory of Open Quantum Systems.
 3
Pierre Rouchon and Jason F. Ralpha, Efficient Quantum Filtering for Quantum Feedback Control, arXiv:1410.5345 [quantph], Phys. Rev. A 91, 012118, (2015).
 4
Howard M. Wiseman, Gerard J. Milburn, Quantum measurement and control.
 Available solvers for
Hierarchical Equations of Motion¶
This module provides solvers for systembath 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 DrudeLorentz specific HEOM solver) is provided. It is implemented on top of the new HEOMSolver but should largely be a dropin 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
 H
Qobj
,QobjEvo
Possibly timedependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo. list of [
Qobj
,Coefficient
] or callable that can be made intoQobjEvo
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).
 state0
Qobj
orHierarchyADOsState
or arraylike If
rho0
is aQobj
the it is the initial state of the system (i.e. aQobj
density matrix).If it is a
HierarchyADOsState
or arraylike, thenrho0
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 optionstore_ados
set to True. For example,result = solver.run(...)
could be followed bysolver.run(result.ado_states[1], tlist)
.If a numpy arraylike 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 operatorop
, the result will be computed using(state * op).tr()
and the state at each timet
. For callable functions,f
, the result is computed usingf(t, ado_state)
. The values are stored in theexpect
ande_data
attributes of the result (see the return section below). argsdict, optional {None}
Change the
args
of the RHS for the evolution. optionsdict, optional {None}
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 {False, True} 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’} 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 : 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.
 H
 Returns
HEOMResult
The results of the simulation run, with the following important attributes:
times
: the timest
(i.e. thetlist
).states
: the system state at each timet
(only available ife_ops
wasNone
or if the solver optionstore_states
was set toTrue
).ado_states
: the full ADO state at each time (only available if the results optionado_return
was set toTrue
). Each element is an instance ofHierarchyADOsState
. The state of a particular ADO may be extracted fromresult.ado_states[i]
by callingextract
.expect
: a list containing the values of eache_ops
at timet
.e_data
: a dictionary containing the values of eache_ops
at tmet
. The keys are those given bye_ops
if it was a dict, otherwise they are the indexes of the suppliede_ops
.
See
HEOMResult
andResult
for the complete list of attributes.
Correlation Functions¶

coherence_function_g1
(H, state0, taulist, c_ops, a_op, solver='me', args={}, options={})[source]¶ Calculate the normalized firstorder 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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_op
Qobj
,QobjEvo
Operator A.
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 Returns
 g1, G1tuple
The normalized and unnormalized secondorder coherence function.

coherence_function_g2
(H, state0, taulist, c_ops, a_op, solver='me', args={}, options={})[source]¶ Calculate the normalized secondorder 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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 timedependent for solver choice of me.
 a_op
Qobj
Operator A.
 argsdict
Dictionary of arguments to be passed to solver.
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 Returns
 g2, G2tuple
The normalized and unnormalized secondorder coherence function.

correlation_2op_1t
(H, state0, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args={}, options={})[source]¶ Calculate the twooperator onetime 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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_op
Qobj
,QobjEvo
Operator A.
 b_op
Qobj
,QobjEvo
Operator B.
 reversebool {False}
If True, calculate \(\left<A(t)B(t+\tau)\right>\) instead of \(\left<A(t+\tau)B(t)\right>\).
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 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={}, options={})[source]¶ Calculate the twooperator twotime 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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 steadysteady correlations only one
tlist
value is necessary, i.e. when \(t \rightarrow \infty\). Iftlist
isNone
,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_op
Qobj
,QobjEvo
Operator A.
 b_op
Qobj
,QobjEvo
Operator B.
 reversebool {False}
If True, calculate \(\left<A(t)B(t+\tau)\right>\) instead of \(\left<A(t+\tau)B(t)\right>\).
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 Returns
 corr_matndarray
An 2dimensional 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 threeoperator twotime 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
 solver
MESolver
,BRSolver
Qutip solver for an open system.
 state0
Qobj
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, C: :class:`Qobj`, :class:`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, ifA
is not provided,<B(t+\tau)C(t)>
is computed.
 solver
 Returns
 corr_matarray
An 2dimensional array (matrix) of correlation values for the times specified by tlist (first index) and taulist (second index). If tlist is None, then a 1dimensional array of correlation values is returned instead.

correlation_3op_1t
(H, state0, taulist, c_ops, a_op, b_op, c_op, solver='me', args={}, options={})[source]¶ Calculate the threeoperator twotime 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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_op
Qobj
,QobjEvo
Operator A.
 b_op
Qobj
,QobjEvo
Operator B.
 c_op
Qobj
,QobjEvo
Operator C.
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 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={}, options={})[source]¶ Calculate the threeoperator twotime 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
 H
Qobj
,QobjEvo
System Hamiltonian, may be timedependent for solver choice of me.
 state0
Qobj
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 ‘steadystate’ 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 steadysteady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\). If
tlist
isNone
,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_op
Qobj
,QobjEvo
Operator A.
 b_op
Qobj
,QobjEvo
Operator B.
 c_op
Qobj
,QobjEvo
Operator C.
 solverstr {‘me’, ‘es’}
Choice of solver, me for masterequation, 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.
 H
 Returns
 corr_matarray
An 2dimensional 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
 H
qutip.qobj
system Hamiltonian.
 wlistarray_like
List of frequencies for \(\omega\).
 c_opslist
List of collapse operators.
 a_opQobj
Operator A.
 b_opQobj
Operator B.
 solverstr
Choice of solver (es for exponential series and pi for psuedoinverse, solve for generic solver).
 H
 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 twotime 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: boolean
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 twosided power spectrum ‘S(w)’.
Steadystate 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
A steadystate density matrix as Qobj instance, for the Liouvillian superoperator L.
 wdouble
frequency at which to evaluate pseudoinverse. Can be zero for dense systems and large sparse systems. Small sparse systems can fail for zero frequencies.
 sparsebool
Flag that indicate whether to use sparse or dense matrix methods when computing the pseudo inverse.
 methodstring
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 qutiptensorflow, can use come with their own solver. When
L
use these data backends, see the corresponding librarieslinalg
for available solver. kwargsdictionary
Additional keyword arguments for setting parameters for solver methods.
 Returns
 RQobj
Returns a Qobj instance representing the pseudo inverse of L.
Note
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/fedora/objects/orbit:82314/datastreams/ file_4732600/content
Note also that the definition of the pseudoinverse 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
 A
Qobj
A Hamiltonian or Liouvillian operator.
 c_op_listlist
A list of collapse operators.
 methodstr, 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” : Inversepower method solverstr, default=None
‘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 qutiptensorflow, can use come with their own solver. When
A
andc_ops
use these data backends, see the corresponding librarieslinalg
for available solver.Extra options for these solver can be passed in
**kw
. use_rcmbool, default False
Use reverse CuthillMckee reordering to minimize fillin 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 1e12
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 1e15
Small weight used in the “power” method.
 sparse: bool
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
orscipy.sparse.linalg
to see what extra arguments are supported.
 A
 Returns
 dmqobj
Steady state density matrix.
 infodict, optional
Dictionary containing solverspecific information about the solution.
Note
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 timedependent cosinusoidal term:
\[\mathcal{\hat{H}}(t) = \hat{H}_0 + \mathcal{\hat{O}} \cos(\omega_d t)\] Parameters
 H_0
Qobj
A Hamiltonian or Liouvillian operator.
 c_opslist
A list of collapse operators.
 Op_t
Qobj
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, default=None
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 qutiptensorflow, may provide their own solvers. When
H_0
andc_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
orscipy.sparse.linalg
to see what extra arguments are supported.
 H_0
 Returns
 dmqobj
Steady state density matrix.
Note
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
 H
Qobj
,QobjEvo
,QobjEvo
compatible format. Possibly timedependent system Liouvillian or Hamiltonian as a Qobj or QobjEvo.
list
of [Qobj
,Coefficient
] or callable that can be made intoQobjEvo
are also accepted. tfloat or arraylike
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 timedependent Hamiltonians and collapse operators.
 optionsdict, optional
Options for the solver.
 **kwargs :
Extra parameters to use when creating the
QobjEvo
from a list formatH
.
 H
 Returns
 Uqobj, list
Instance representing the propagator(s) \(U(t)\). Return a single Qobj when
t
is a number or a list whent
is a list.
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
 H:class: qutip.Qobj or list
Systemwaveguide(s) Hamiltonian or effective Hamiltonian in Qobj or listcallback format. If construct_effective_hamiltonian is not specified, an effective Hamiltonian is constructed from H and c_ops.
 psi0:class: qutip.Qobj
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_state:class: qutip.Qobj
State representing zero excitations in the system. Defaults to basis(systemDims, 0).
 construct_effective_hamiltonianbool
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, n_emissions=None)[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_vector:class: qutip.Qobj
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 nphoton state projected onto the temporal basis.
 Parameters
 H:class: qutip.Qobj or list
Systemwaveguide(s) Hamiltonian or effective Hamiltonian in Qobj or listcallback format. If construct_effective_hamiltonian is not specified, an effective Hamiltonian is constructed from H and c_ops.
 psi0:class: qutip.Qobj
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_state:class: qutip.Qobj
State representing zero excitations in the system. Defaults to \(\psi(t_0)\)
 construct_effective_hamiltonianbool
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_n:class: qutip.Qobj
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 twolevel 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,m1\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 blockdiagonal matrix for the Dicke basis.
 Parameters
 Nint
Number of twolevel systems.
 elementsstr {‘ones’ (default),’degeneracy’}
 Returns
 block_matrndarray
A 2D blockdiagonal matrix with dimension (nds,nds), where nds is the number of Dicke states for N twolevel 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 twolevel system (TLS) SU(2) Pauli matrices.
 Parameters
 N: int
The number of twolevel systems.
 emission: float
Incoherent emission coefficient (also nonradiative emission). default: 0.0
 dephasing: float
Local dephasing coefficient. default: 0.0
 pumping: float
Incoherent pumping coefficient. default: 0.0
 collective_emission: float
Collective (superradiant) emmission coefficient. default: 0.0
 collective_pumping: float
Collective pumping coefficient. default: 0.0
 collective_dephasing: float
Collective dephasing coefficient. default: 0.0
 Returns
 c_ops: list
The list of collapse operators as qutip.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 twolevel systems.
 x, y: float
The coefficients of the CSS state.
 basis: str
The basis to use. Either “dicke” or “uncoupled”.
 coordinates: str
Either “cartesian” or “polar”. If polar then the coefficients are constructed as sin(x/2), cos(x/2)e^(iy).
 Returns
 rho: :class: qutip.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 twolevel 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: :class: qutip.Qobj
The density matrix.

dicke_basis
(N, jmm1=None)[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 twolevel systems.
 jmm1: dict
A dictionary of {(j, m, m1): p} that gives a density p for the (j, m, m1) matrix element.
 Returns
 rho: :class: qutip.Qobj
The density matrix in the Dicke basis.

dicke_blocks
(rho)[source]¶ Create the list of blocks for blockdiagonal density matrix in the Dicke basis.
 Parameters
 rho
qutip.Qobj
A 2D blockdiagonal matrix of ones with dimension (nds,nds), where nds is the number of Dicke states for N twolevel systems.
 rho
 Returns
 square_blocks: list of np.array
Give back the blocks list.

dicke_blocks_full
(rho)[source]¶ Give the full (2^Ndimensional) list of blocks for a Dickebasis matrix.
 Parameters
 rho
qutip.Qobj
A 2D blockdiagonal matrix of ones with dimension (nds,nds), where nds is the number of Dicke states for N twolevel systems.
 rho
 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 Taylorexpandable function of rho. :type f: function :param rho: A density matrix in the Dicke basis. :type rho:
qutip.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 builtin function scipy.special.binom
 Parameters
 N: int
The number of twolevel systems.
 m: float
Total spin zaxis 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 Dickebasis density matrix.
 Parameters
 rho
qutip.Qobj
A 2D blockdiagonal matrix of ones with dimension (nds,nds), where nds is the number of Dicke states for N twolevel systems.
 rho
 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 twolevel systems.
 basis: str
The basis to use. Either “dicke” or “uncoupled”.
 Returns
 state: :class: qutip.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 twolevel systems.
 basis: str
The basis to use. Either “dicke” or “uncoupled”.
 Returns
 state: :class: qutip.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 twolevel systems.
 basis: str
The basis to use. Either “dicke” or “uncoupled”
 Returns
 state: :class: qutip.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 twolevel systems.
 Returns
 identity: :class: qutip.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 twolevel systems.
 op: str
The operator to return ‘x’,’y’,’z’,’+’,’‘. If no operator given, then output is the list of operators for [‘x’,’y’,’z’].
 basis: str
The basis of the operators  “dicke” or “uncoupled” default: “dicke”.
 Returns
 j_alg: list or :class: qutip.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 twolevel systems.
 m: float
Total spin zaxis projection eigenvalue (proportional to the total energy).
 Returns
 degeneracy: int
The mdegeneracy.

num_dicke_ladders
(N)[source]¶ Calculate the total number of ladders in the Dicke space.
For a collection of N twolevel systems it counts how many different “j” exist or the number of blocks in the blockdiagonal matrix.
 Parameters
 N: int
The number of twolevel 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 twolevel systems.
 Returns
 nds: int
The number of Dicke states.

num_tls
(nds)[source]¶ Calculate the number of twolevel systems.
 Parameters
 nds: int
The number of Dicke states.
 Returns
 N: int
The number of twolevel 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
 rho
qutip.Qobj
Density matrix in the Dicke basis of qutip.piqs.jspin(N), for N spins.
 rho
 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 twolevel 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, …, (N1), is placed in a \(2^N\)dimensional Hilbert space.
 Parameters
 N: int
The number of twolevel systems.
 Returns
 spin_operators: list or :class: qutip.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 twolevel 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 twolevel systems.
 basis: str
The basis to use. Either “dicke” or “uncoupled”.
 Returns
 state: :class: qutip.Qobj
The superradiant state density matrix in the requested basis.

tau_column
(tau, k, j)[source]¶ Determine the column index for the nonzero 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: qutip.core.qobj.Qobj, xvec, yvec, g: float = 1.4142135623730951, precompute_memory: float = 1024)[source]¶ HusimiQ function of a given state vector or density matrix at phasespace points
0.5 * g * (xvec + i*yvec)
. Parameters
 state
Qobj
A state vector or density matrix. This cannot have tensorproduct structure.
 xvec, yvecarray_like
x and ycoordinates at which to calculate the HusimiQ 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 densitymatrix inputs. This is ignored for statevector inputs. The bound is not quite exact due to other, orderofmagnitude smaller, intermediaries being necessary, but is a good approximation. If you want to use the same iterative algorithm for density matrices that is used for single kets, set
precompute_memory=None
.
 state
 Returns
 ndarray
Values representing the HusimiQ function calculated over the specified range
[xvec, yvec]
.
See also
QFunc
a classbased version, more efficient if you want to calculate the HusimiQ function for several states over the same coordinates.

spin_q_function
(rho, theta, phi)[source]¶ The Husimi Q function for spins is defined as
Q(theta, phi) = SCS.dag() * rho * SCS
for the spin coherent stateSCS = spin_coherent( j, theta, phi)
where j is the spin length. The implementation here is more efficient as it doesn’t generate all of the SCS at theta and phi (see references).The spin Q function is normal when integrated over the surface of the sphere
\[\frac{4 \pi}{2j + 1}\int_\phi \int_\theta Q(\theta, \phi) \sin(\theta) d\theta d\phi = 1\] Parameters
 stateqobj
A state vector or density matrix for a spinj quantum system.
 thetaarray_like
Polar (colatitude) angle at which to calculate the HusimiQ function.
 phiarray_like
Azimuthal angle at which to calculate the HusimiQ function.
 Returns
 Q, THETA, PHI2darray
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 spinj 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 spinj 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, PHI2darray
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 3j symbol and ClebschGordan coefficients taken from Wikipedia (https://en.wikipedia.org/wiki/3j_symbol)

wigner
(psi, xvec, yvec, 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
xcoordinates at which to calculate the Wigner function.
 yvecarray_like
ycoordinates at which to calculate the Wigner function. Does not apply to the ‘fft’ method.
 gfloat
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’}
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 {False, True}
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 {False, True}
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 ycoordinate values calculated via the Fourier transform.
Notes
The ‘fft’ method accepts only an xvec input for the xcoordinate. The ycoordinates are calculated internally.
References
Ulf Leonhardt, Measuring the Quantum State of Light, (Cambridge University Press, 1997)
Graphs and Visualization¶
Functions for visualizing results of quantum dynamics simulations, visualizations of quantum states and processes.

hinton
(rho, xlabels=None, ylabels=None, title=None, ax=None, cmap=None, label_top=True, color_style='scaled')[source]¶ Draws a Hinton diagram for visualizing a density matrix or superoperator.
 Parameters
 rhoqobj
Input density matrix or superoperator.
 xlabelslist of strings or False
list of x labels
 ylabelslist of strings or False
list of y labels
 titlestring
title of the plot (optional)
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 cmapa matplotlib colormap instance
Color map to use when plotting.
 label_topbool
If True, xaxis labels will be placed on top, otherwise they will appear below the plot.
 color_stylestring
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.
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances 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, xlabels=None, ylabels=None, title=None, limits=None, colorbar=True, fig=None, ax=None, options=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
 xlabelslist of strings
list of x labels
 ylabelslist of strings
list of y labels
 titlestring
title of the plot (optional)
 limitslist/array with two float numbers
The zaxis limits [min, max] (optional)
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 colorbarbool (default: True)
show colorbar
 optionsdict
A dictionary containing extra options for the plot. The names (keys) and values of the options are described below:
 ‘zticks’list of numbers
A list of zaxis tick locations.
 ‘cmap’string (default: ‘jet’)
The name of the color map to use.
 ‘cmap_min’float (default: 0.0)
The lower bound to truncate the color map at. A value in range 0  1. The default, 0, leaves the lower bound of the map unchanged.
 ‘cmap_max’float (default: 1.0)
The upper bound to truncate the color map at. A value in range 0  1. The default, 1, leaves the upper bound of the map unchanged.
 ‘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
The azimuthal viewing angle.
 ‘elev’float
The elevation viewing angle.
 ‘proj_type’string (default: ‘ortho’ if ax is not passed)
The type of projection (‘ortho’ or ‘persp’)
 ‘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 zvalues to the maximum and minimum colors in the colorbar (True) or not (False).
 ‘figsize’tuple of two numbers
The size of the figure.
 Returns :
 ——
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.
 Raises
 ValueError
Input argument is not valid.

matrix_histogram_complex
(M, xlabels=None, ylabels=None, title=None, limits=None, phase_limits=None, colorbar=True, fig=None, ax=None, threshold=None)[source]¶ Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title.
 Parameters
 MMatrix of Qobj
The matrix to visualize
 xlabelslist of strings
list of x labels
 ylabelslist of strings
list of y labels
 titlestring
title of the plot (optional)
 limitslist/array with two float numbers
The zaxis limits [min, max] (optional)
 phase_limitslist/array with two float numbers
The phaseaxis (colorbar) limits [min, max] (optional)
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 threshold: float (None)
Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map.
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.
 Raises
 ValueError
Input argument is not valid.

plot_energy_levels
(H_list, N=0, labels=None, show_ylabels=False, figsize=(8, 12), fig=None, ax=None)[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.
 labelsList of string
A list of labels for each Hamiltonian
 show_ylabelsBool (default False)
Show y labels to the left of energy levels of the initial Hamiltonian.
 Nint
The number of energy levels to plot
 figsizetuple (int,int)
The size of the figure (width, height).
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axa matplotlib axes instance
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=[], title=None, show_legend=False, fig=None, axes=None, figsize=(8, 4))[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)
qutip.solver.Result
List of results objects returned by any of the QuTiP evolution solvers.
 ylabelslist of strings
The yaxis labels. List should be of the same length as results.
 titlestring
The title of the figure.
 show_legendbool
Whether or not to show the legend.
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axesa matplotlib axes instance
The axes context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 results(list of)
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_fock_distribution
(rho, offset=0, fig=None, ax=None, figsize=(8, 6), title=None, unit_y_range=True)[source]¶ Plot the Fock distribution for a density matrix (or ket) that describes an oscillator mode.
 Parameters
 rho
qutip.Qobj
The density matrix (or ket) of the state to visualize.
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 titlestring
An optional title for the figure.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 rho
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_qubism
(ket, theme='light', how='pairs', grid_iteration=1, legend_iteration=0, fig=None, ax=None, figsize=(6, 6))[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.
 Parameters
 ketQobj
Pure state for plotting.
 theme‘light’ (default) or ‘dark’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
 how‘pairs’ (default), ‘pairs_skewed’ or ‘before_after’
Type of Qubism plotting. Options:
‘pairs’  typical coordinates,
‘pairs_skewed’  for ferromagnetic/antriferromagnetic plots,
‘before_after’  related to Schmidt plot (see also: plot_schmidt).
 grid_iterationint (default 1)
Helper lines to be drawn on plot. Show tiles for 2*grid_iteration particles vs all others.
 legend_iterationint (default 0) or ‘grid_iteration’ or ‘all’
Show labels for first
2*legend_iteration
particles. Option ‘grid_iteration’ sets the same number of particles as for grid_iteration. Option ‘all’ makes label for all particles. Typically it should be 0, 1, 2 or perhaps 3. figa matplotlib figure instance
The figure canvas on which the plot will be drawn.
 axa matplotlib axis instance
The axis context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.
Notes
See also [1].
References
 1
J. RodriguezLaguna, P. Migdal, M. Ibanez Berganza, M. Lewenstein and G. Sierra, Qubism: selfsimilar visualization of manybody wavefunctions, New J. Phys. 14 053028, arXiv:1112.3560 (2012), open access.

plot_schmidt
(ket, splitting=None, labels_iteration=(3, 2), theme='light', fig=None, ax=None, figsize=(6, 6))[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.
 Parameters
 ketQobj
Pure state for plotting.
 splittingint
Plot for a number of first particles versus the rest. If not given, it is (number of particles + 1) // 2.
 theme‘light’ (default) or ‘dark’
Set coloring theme for mapping complex values into colors. See: complex_array_to_rgb.
 labels_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
The figure canvas on which the plot will be drawn.
 axa matplotlib axis instance
The axis context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_spin_distribution_2d
(P, THETA, PHI, fig=None, ax=None, figsize=(8, 8))[source]¶ Plot a spin distribution function (given as meshgrid data) with a 2D projection where the surface of the unit sphere is mapped on the unit disk.
 Parameters
 Pmatrix
Distribution values as a meshgrid matrix.
 THETAmatrix
Meshgrid matrix for the theta coordinate.
 PHImatrix
Meshgrid matrix for the phi coordinate.
 figa matplotlib figure instance
The figure canvas on which the plot will be drawn.
 axa matplotlib axis instance
The axis context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_spin_distribution_3d
(P, THETA, PHI, fig=None, ax=None, figsize=(8, 6))[source]¶ Plots a matrix of values on a sphere
 Parameters
 Pmatrix
Distribution values as a meshgrid matrix.
 THETAmatrix
Meshgrid matrix for the theta coordinate.
 PHImatrix
Meshgrid matrix for the phi coordinate.
 figa matplotlib figure instance
The figure canvas on which the plot will be drawn.
 axa matplotlib axis instance
The axis context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_wigner
(rho, fig=None, ax=None, figsize=(6, 6), cmap=None, alpha_max=7.5, colorbar=False, method='clenshaw', projection='2d')[source]¶ Plot the the Wigner function for a density matrix (or ket) that describes an oscillator mode.
 Parameters
 rho
qutip.Qobj
The density matrix (or ket) of the state to visualize.
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 cmapa matplotlib cmap instance
The colormap.
 alpha_maxfloat
The span of the x and y coordinates (both [alpha_max, alpha_max]).
 colorbarbool
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
 methodstring {‘clenshaw’, ‘iterative’, ‘laguerre’, ‘fft’}
The method used for calculating the wigner function. See the documentation for qutip.wigner for details.
 projection: string {‘2d’, ‘3d’}
Specify whether the Wigner function is to be plotted as a contour graph (‘2d’) or surface plot (‘3d’).
 rho
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_wigner_fock_distribution
(rho, fig=None, axes=None, figsize=(8, 4), cmap=None, alpha_max=7.5, colorbar=False, method='iterative', projection='2d')[source]¶ Plot the Fock distribution and the Wigner function for a density matrix (or ket) that describes an oscillator mode.
 Parameters
 rho
qutip.Qobj
The density matrix (or ket) of the state to visualize.
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axesa list of two matplotlib axes instances
The axes context in which the plot will be drawn.
 figsize(width, height)
The size of the matplotlib figure (in inches) if it is to be created (that is, if no ‘fig’ and ‘ax’ arguments are passed).
 cmapa matplotlib cmap instance
The colormap.
 alpha_maxfloat
The span of the x and y coordinates (both [alpha_max, alpha_max]).
 colorbarbool
Whether (True) or not (False) a colorbar should be attached to the Wigner function graph.
 methodstring {‘iterative’, ‘laguerre’, ‘fft’}
The method used for calculating the wigner function. See the documentation for qutip.wigner for details.
 projection: string {‘2d’, ‘3d’}
Specify whether the Wigner function is to be plotted as a contour graph (‘2d’) or surface plot (‘3d’).
 rho
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

plot_wigner_sphere
(fig, ax, wigner, reflections)[source]¶ Plots a coloured Bloch sphere.
 Parameters
 fig
matplotlib.figure.Figure
An instance of
Figure
. ax
matplotlib.axes.Axes
An axes instance in the given figure.
 wignerlist of float
The wigner transformation at steps different theta and phi.
 reflectionsbool
If the reflections of the sphere should be plotted as well.
 fig
Notes
Special thanks to Russell P Rundle for writing this function.

sphereplot
(theta, phi, values, fig=None, ax=None, save=False)[source]¶ Plots a matrix of values on a sphere
 Parameters
 thetafloat
Angle with respect to zaxis
 phifloat
Angle in xy plane
 valuesarray
Data set to be plotted
 figa matplotlib Figure instance
The Figure canvas in which the plot will be drawn.
 axa matplotlib axes instance
The axes context in which the plot will be drawn.
 savebool {False , True}
Whether to save the figure or not
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.

orbital
(theta, phi, *args)[source]¶ Calculates an angular wave function on a sphere.
psi = orbital(theta,phi,ket1,ket2,...)
calculates the angular wave function on a sphere at the mesh of points defined by theta and phi which is \(\sum_{lm} c_{lm} Y_{lm}(theta,phi)\) where \(C_{lm}\) are the coefficients specified by the list of kets. Each ket has 2l+1 components for some integer l. The first entry of the ket defines the coefficient c_{l,l}, while the last entry of the ket defines the coefficient c_{l, l}. Parameters
 thetaint/float/list/array
Polar angles in [0, pi]
 phiint/float/list/array
Azimuthal angles in [0, 2*pi]
 argslist/array
list
of ket vectors.
 Returns
array
for angular wave function evaluated at allpossible combinations of theta and phi
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
Number of color levels to create.
 shiftfloat
Shifts the value at which Wigner elements are emphasized. This parameter should typically be negative and small (i.e 1e5).
 max_colorstr
String for color corresponding to maximum value of data. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
 mid_colorstr
Color corresponding to zero values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
 min_colorstr
Color corresponding to minimum data values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
 neg_colorstr
Color that starts highlighting negative values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter.
 invertbool
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 roundoff 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.
 titlestring
Plot title.
 figfigure instance
User defined figure instance used for generating QPT plot.
 axeslist of figure axis instance
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.
 titlestring
Plot title.
 figfigure instance
User defined figure instance used for generating QPT plot.
 axfigure axis instance
User defined figure axis instance used for generating QPT plot (alternative to the fig argument).
 threshold: float (None)
Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map.
 Returns
 fig, axtuple
A tuple of the matplotlib figure and axes instances used to produce the figure.
NonMarkovian Solvers¶
This module contains an implementation of the nonMarkovian transfer tensor method (TTM), introduced in [1].
[1] Javier Cerrillo and Jianshu Cao, Phys. Rev. Lett 112, 110401 (2014)

ttmsolve
(dynmaps, rho0, times, e_ops=[], learningtimes=None, tensors=None, **kwargs)[source]¶ Solve timeevolution using the Transfer Tensor Method, based on a set of precomputed dynamical maps.
 Parameters
 dynmapslist of
qutip.Qobj
List of precomputed dynamical maps (superoperators), or a callback function that returns the superoperator at a given time.
 rho0
qutip.Qobj
Initial density matrix or state vector (ket).
 timesarray_like
list of times \(t_n\) at which to compute \(\rho(t_n)\). Must be uniformily spaced.
 e_opslist of
qutip.Qobj
/ callback function single operator or list of operators for which to evaluate expectation values.
 learningtimesarray_like
list of times \(t_k\) for which we have knowledge of the dynamical maps \(E(t_k)\).
 tensorsarray_like
optional list of precomputed tensors \(T_k\)
 kwargsdictionary
Optional keyword arguments. See
qutip.nonmarkov.transfertensor.TTMSolverOptions
.
 dynmapslist of
 Returns
 output:
qutip.solver.Result
An instance of the class
qutip.solver.Result
.
 output:
Optimal control¶
Wrapper functions that will manage the creation of the objects, build the configuration, and execute the algorithm required to optimise a set of ctrl pulses for a given (quantum) system. The fidelity error is some measure of distance of the system evolution from the given target evolution in the time allowed for the evolution. The functions minimise this fidelity error wrt the piecewise control amplitudes in the timeslots
There are currently two quantum control pulse optmisations algorithms implemented in this library. There are accessible through the methods in this module. Both the algorithms use the scipy.optimize methods to minimise the fidelity error with respect to to variables that define the pulse.
GRAPE¶
The default algorithm (as it was implemented here first) is GRAPE GRadient Ascent Pulse Engineering [1][2]. It uses a gradient based method such as BFGS to minimise the fidelity error. This makes convergence very quick when an exact gradient can be calculated, but this limits the factors that can taken into account in the fidelity.
CRAB¶
The CRAB [3][4] algorithm was developed at the University of Ulm. In full it is the Chopped RAndom Basis algorithm. The main difference is that it reduces the number of optimisation variables by defining the control pulses by expansions of basis functions, where the variables are the coefficients. Typically a Fourier series is chosen, i.e. the variables are the Fourier coefficients. Therefore it does not need to compute an explicit gradient. By default it uses the NelderMead method for fidelity error minimisation.
References
N Khaneja et. al. Optimal control of coupled spin dynamics: Design of NMR pulse sequences by gradient ascent algorithms. J. Magn. Reson. 172, 296–305 (2005).
Shai Machnes et.al DYNAMO  Dynamic Framework for Quantum Optimal Control arXiv.1011.4874
Doria, P., Calarco, T. & Montangero, S. Optimal Control Technique for ManyBody Quantum Dynamics. Phys. Rev. Lett. 106, 1–4 (2011).
Caneva, T., Calarco, T. & Montangero, S. Chopped randombasis quantum optimization. Phys. Rev. A  At. Mol. Opt. Phys. 84, (2011).

create_pulse_optimizer
(drift, ctrls, initial, target, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e10, min_grad=1e10, max_iter=500, max_wall_time=180, alg='GRAPE', alg_params=None, optim_params=None, optim_method='DEF', method_params=None, optim_alg=None, max_metric_corr=None, accuracy_factor=None, dyn_type='GEN_MAT', dyn_params=None, prop_type='DEF', prop_params=None, fid_type='DEF', fid_params=None, phase_option=None, fid_err_scale_factor=None, tslot_type='DEF', tslot_params=None, amp_update_mode=None, init_pulse_type='DEF', init_pulse_params=None, pulse_scaling=1.0, pulse_offset=0.0, ramping_pulse_type=None, ramping_pulse_params=None, log_level=0, gen_stats=False)[source]¶ Generate the objects of the appropriate subclasses required for the pulse optmisation based on the parameters given Note this method may be preferable to calling optimize_pulse if more detailed configuration is required before running the optmisation algorthim, or the algorithm will be run many times, for instances when trying to finding global the optimum or minimum time optimisation
 Parameters
 driftQobj or list of Qobj
The underlying dynamics generator of the system can provide list (of length num_tslots) for time dependent drift.
 ctrlsList of Qobj or array like [num_tslots, evo_time]
A list of control dynamics generators. These are scaled by the amplitudes to alter the overall dynamics. Arraylike input can be provided for time dependent control generators.
 initialQobj
Starting point for the evolution. Typically the identity matrix.
 targetQobj
Target transformation, e.g. gate or state, for the time evolution.
 num_tslotsinteger or None
Number of timeslots.
None
implies that timeslots will be given in the tau array. evo_timefloat or None
Total time for the evolution.
None
implies that timeslots will be given in the tau array. tauarray[num_tslots] of floats or None
Durations for the timeslots. If this is given then
num_tslots
andevo_time
are dervived from it.None
implies that timeslot durations will be equal and calculated asevo_time/num_tslots
. amp_lboundfloat or list of floats
Lower boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 amp_uboundfloat or list of floats
Upper boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 fid_err_targfloat
Fidelity error target. Pulse optimisation will terminate when the fidelity error falls below this value.
 mim_gradfloat
Minimum gradient. When the sum of the squares of the gradients wrt to the control amplitudes falls below this value, the optimisation terminates, assuming local minima.
 max_iterinteger
Maximum number of iterations of the optimisation algorithm.
 max_wall_timefloat
Maximum allowed elapsed time for the optimisation algorithm.
 algstring
Algorithm to use in pulse optimisation. Options are:
‘GRAPE’ (default)  GRadient Ascent Pulse Engineering
‘CRAB’  Chopped RAndom Basis
 alg_paramsDictionary
options that are specific to the algorithm see above
 optim_paramsDictionary
The key value pairs are the attribute name and value used to set attribute values. Note: attributes are created if they do not exist already, and are overwritten if they do. Note: method_params are applied afterwards and so may override these.
 optim_methodstring
a scipy.optimize.minimize method that will be used to optimise the pulse for minimum fidelity error Note that FMIN, FMIN_BFGS & FMIN_L_BFGS_B will all result in calling these specific scipy.optimize methods Note the LBFGSB is equivalent to FMIN_L_BFGS_B for backwards capatibility reasons. Supplying DEF will given alg dependent result:
GRAPE  Default optim_method is FMIN_L_BFGS_B
CRAB  Default optim_method is NelderMead
 method_paramsdict
Parameters for the optim_method. Note that where there is an attribute of the
Optimizer
object or the termination_conditions matching the key that attribute. Otherwise, and in some case also, they are assumed to be method_options for the scipy.optimize.minimize method. optim_algstring
Deprecated. Use optim_method.
 max_metric_corrinteger
Deprecated. Use method_params instead
 accuracy_factorfloat
Deprecated. Use method_params instead
 dyn_typestring
Dynamics type, i.e. the type of matrix used to describe the dynamics. Options are UNIT, GEN_MAT, SYMPL (see Dynamics classes for details)
 dyn_paramsdict
Parameters for the Dynamics object The key value pairs are assumed to be attribute name value pairs They applied after the object is created
 prop_typestring
Propagator type i.e. the method used to calculate the propagtors and propagtor gradient for each timeslot options are DEF, APPROX, DIAG, FRECHET, AUG_MAT DEF will use the default for the specific dyn_type (see PropagatorComputer classes for details)
 prop_paramsdict
Parameters for the PropagatorComputer object The key value pairs are assumed to be attribute name value pairs They applied after the object is created
 fid_typestring
Fidelity error (and fidelity error gradient) computation method Options are DEF, UNIT, TRACEDIFF, TD_APPROX DEF will use the default for the specific dyn_type (See FidelityComputer classes for details)
 fid_paramsdict
Parameters for the FidelityComputer object The key value pairs are assumed to be attribute name value pairs They applied after the object is created
 phase_optionstring
Deprecated. Pass in fid_params instead.
 fid_err_scale_factorfloat
Deprecated. Use scale_factor key in fid_params instead.
 tslot_typestring
Method for computing the dynamics generators, propagators and evolution in the timeslots. Options: DEF, UPDATE_ALL, DYNAMIC UPDATE_ALL is the only one that currently works (See TimeslotComputer classes for details)
 tslot_paramsdict
Parameters for the TimeslotComputer object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 amp_update_modestring
Deprecated. Use tslot_type instead.
 init_pulse_typestring
type / shape of pulse(s) used to initialise the the control amplitudes. Options (GRAPE) include:
RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW DEF is RND
(see PulseGen classes for details) For the CRAB the this the guess_pulse_type.
 init_pulse_paramsdict
Parameters for the initial / guess pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 pulse_scalingfloat
Linear scale factor for generated initial / guess pulses By default initial pulses are generated with amplitudes in the range (1.0, 1.0). These will be scaled by this parameter
 pulse_offsetfloat
Linear offset for the pulse. That is this value will be added to any initial / guess pulses generated.
 ramping_pulse_typestring
Type of pulse used to modulate the control pulse. It’s intended use for a ramping modulation, which is often required in experimental setups. This is only currently implemented in CRAB. GAUSSIAN_EDGE was added for this purpose.
 ramping_pulse_paramsdict
Parameters for the ramping pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created
 log_levelinteger
level of messaging output from the logger. Options are attributes of qutip.logging_utils, in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN
 gen_statsboolean
if set to True then statistics for the optimisation run will be generated  accessible through attributes of the stats object
 Returns
 optOptimizer
Instance of an Optimizer, through which the Config, Dynamics, PulseGen, and TerminationConditions objects can be accessed as attributes. The PropagatorComputer, FidelityComputer and TimeslotComputer objects can be accessed as attributes of the Dynamics object, e.g. optimizer.dynamics.fid_computer The optimisation can be run through the optimizer.run_optimization

opt_pulse_crab
(drift, ctrls, initial, target, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e05, max_iter=500, max_wall_time=180, alg_params=None, num_coeffs=None, init_coeff_scaling=1.0, optim_params=None, optim_method='fmin', method_params=None, dyn_type='GEN_MAT', dyn_params=None, prop_type='DEF', prop_params=None, fid_type='DEF', fid_params=None, tslot_type='DEF', tslot_params=None, guess_pulse_type=None, guess_pulse_params=None, guess_pulse_scaling=1.0, guess_pulse_offset=0.0, guess_pulse_action='MODULATE', ramping_pulse_type=None, ramping_pulse_params=None, log_level=0, out_file_ext=None, gen_stats=False)[source]¶ Optimise a control pulse to minimise the fidelity error. The dynamics of the system in any given timeslot are governed by the combined dynamics generator, i.e. the sum of the drift+ctrl_amp[j]*ctrls[j] The control pulse is an [n_ts, n_ctrls] array of piecewise amplitudes. The CRAB algorithm uses basis function coefficents as the variables to optimise. It does NOT use any gradient function. A multivariable optimisation algorithm attempts to determines the optimal values for the control pulse to minimise the fidelity error The fidelity error is some measure of distance of the system evolution from the given target evolution in the time allowed for the evolution.
 Parameters
 driftQobj or list of Qobj
the underlying dynamics generator of the system can provide list (of length num_tslots) for time dependent drift
 ctrlsList of Qobj or array like [num_tslots, evo_time]
a list of control dynamics generators. These are scaled by the amplitudes to alter the overall dynamics Array like imput can be provided for time dependent control generators
 initialQobj
Starting point for the evolution. Typically the identity matrix.
 targetQobj
Target transformation, e.g. gate or state, for the time evolution.
 num_tslotsinteger or None
Number of timeslots.
None
implies that timeslots will be given in the tau array. evo_timefloat or None
Total time for the evolution.
None
implies that timeslots will be given in the tau array. tauarray[num_tslots] of floats or None
Durations for the timeslots. If this is given then
num_tslots
andevo_time
are dervived from it.None
implies that timeslot durations will be equal and calculated asevo_time/num_tslots
. amp_lboundfloat or list of floats
Lower boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 amp_uboundfloat or list of floats
Upper boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 fid_err_targfloat
Fidelity error target. Pulse optimisation will terminate when the fidelity error falls below this value.
 max_iterinteger
Maximum number of iterations of the optimisation algorithm.
 max_wall_timefloat
Maximum allowed elapsed time for the optimisation algorithm.
 alg_paramsDictionary
Options that are specific to the algorithm see above.
 optim_paramsDictionary
The key value pairs are the attribute name and value used to set attribute values. Note: attributes are created if they do not exist already, and are overwritten if they do. Note: method_params are applied afterwards and so may override these.
 coeff_scalingfloat
Linear scale factor for the random basis coefficients. By default these range from 1.0 to 1.0. Note this is overridden by alg_params (if given there).
 num_coeffsinteger
Number of coefficients used for each basis function. Note this is calculated automatically based on the dimension of the dynamics if not given. It is crucial to the performane of the algorithm that it is set as low as possible, while still giving high enough frequencies. Note this is overridden by alg_params (if given there).
 optim_methodstring
Multivariable optimisation method. The only tested options are ‘fmin’ and ‘Neldermead’. In theory any nongradient method implemented in scipy.optimize.mininize could be used.
 method_paramsdict
Parameters for the optim_method. Note that where there is an attribute of the
Optimizer
object or the termination_conditions matching the key that attribute. Otherwise, and in some case also, they are assumed to be method_options for thescipy.optimize.minimize
method. The commonly used parameter are:xtol  limit on variable change for convergence
ftol  limit on fidelity error change for convergence
 dyn_typestring
Dynamics type, i.e. the type of matrix used to describe the dynamics. Options are UNIT, GEN_MAT, SYMPL (see Dynamics classes for details).
 dyn_paramsdict
Parameters for the
qutip.control.dynamics.Dynamics
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. prop_typestring
Propagator type i.e. the method used to calculate the propagtors and propagtor gradient for each timeslot options are DEF, APPROX, DIAG, FRECHET, AUG_MAT DEF will use the default for the specific dyn_type (see
PropagatorComputer
classes for details). prop_paramsdict
Parameters for the
PropagatorComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. fid_typestring
Fidelity error (and fidelity error gradient) computation method. Options are DEF, UNIT, TRACEDIFF, TD_APPROX. DEF will use the default for the specific dyn_type. (See
FidelityComputer
classes for details). fid_paramsdict
Parameters for the
FidelityComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. tslot_typestring
Method for computing the dynamics generators, propagators and evolution in the timeslots. Options: DEF, UPDATE_ALL, DYNAMIC UPDATE_ALL is the only one that currently works. (See
TimeslotComputer
classes for details). tslot_paramsdict
Parameters for the
TimeslotComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. guess_pulse_typestring, default None
Type / shape of pulse(s) used modulate the control amplitudes. Options include: RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW, GAUSSIAN.
 guess_pulse_paramsdict
Parameters for the guess pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 guess_pulse_actionstring, default ‘MODULATE’
Determines how the guess pulse is applied to the pulse generated by the basis expansion. Options are: MODULATE, ADD.
 pulse_scalingfloat
Linear scale factor for generated guess pulses. By default initial pulses are generated with amplitudes in the range (1.0, 1.0). These will be scaled by this parameter.
 pulse_offsetfloat
Linear offset for the pulse. That is this value will be added to any guess pulses generated.
 ramping_pulse_typestring
Type of pulse used to modulate the control pulse. It’s intended use for a ramping modulation, which is often required in experimental setups. This is only currently implemented in CRAB. GAUSSIAN_EDGE was added for this purpose.
 ramping_pulse_paramsdict
Parameters for the ramping pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 log_levelinteger
level of messaging output from the logger. Options are attributes of
qutip.logging_utils
, in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN. out_file_extstring or None
Files containing the initial and final control pulse. Amplitudes are saved to the current directory. The default name will be postfixed with this extension. Setting this to
None
will suppress the output of files. gen_statsboolean
If set to
True
then statistics for the optimisation run will be generated  accessible through attributes of the stats object.
 Returns
 optOptimResult
Returns instance of OptimResult, which has attributes giving the reason for termination, final fidelity error, final evolution final amplitudes, statistics etc

opt_pulse_crab_unitary
(H_d, H_c, U_0, U_targ, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e05, max_iter=500, max_wall_time=180, alg_params=None, num_coeffs=None, init_coeff_scaling=1.0, optim_params=None, optim_method='fmin', method_params=None, phase_option='PSU', dyn_params=None, prop_params=None, fid_params=None, tslot_type='DEF', tslot_params=None, guess_pulse_type=None, guess_pulse_params=None, guess_pulse_scaling=1.0, guess_pulse_offset=0.0, guess_pulse_action='MODULATE', ramping_pulse_type=None, ramping_pulse_params=None, log_level=0, out_file_ext=None, gen_stats=False)[source]¶ Optimise a control pulse to minimise the fidelity error, assuming that the dynamics of the system are generated by unitary operators. This function is simply a wrapper for optimize_pulse, where the appropriate options for unitary dynamics are chosen and the parameter names are in the format familiar to unitary dynamics. The dynamics of the system in any given timeslot are governed by the combined Hamiltonian, i.e. the sum of the
H_d + ctrl_amp[j]*H_c[j]
The control pulse is an[n_ts, n_ctrls]
array of piecewise amplitudes.The CRAB algorithm uses basis function coefficents as the variables to optimise. It does NOT use any gradient function. A multivariable optimisation algorithm attempts to determines the optimal values for the control pulse to minimise the fidelity error. The fidelity error is some measure of distance of the system evolution from the given target evolution in the time allowed for the evolution.
 Parameters
 H_dQobj or list of Qobj
Drift (aka system) the underlying Hamiltonian of the system can provide list (of length num_tslots) for time dependent drift.
 H_cList of Qobj or array like [num_tslots, evo_time]
A list of control Hamiltonians. These are scaled by the amplitudes to alter the overall dynamics. Array like imput can be provided for time dependent control generators.
 U_0Qobj
Starting point for the evolution. Typically the identity matrix.
 U_targQobj
Target transformation, e.g. gate or state, for the time evolution.
 num_tslotsinteger or None
Number of timeslots.
None
implies that timeslots will be given in the tau array. evo_timefloat or None
Total time for the evolution.
None
implies that timeslots will be given in the tau array. tauarray[num_tslots] of floats or None
Durations for the timeslots. If this is given then
num_tslots
andevo_time
are derived from it.None
implies that timeslot durations will be equal and calculated asevo_time/num_tslots
. amp_lboundfloat or list of floats
Lower boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 amp_uboundfloat or list of floats
Upper boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 fid_err_targfloat
Fidelity error target. Pulse optimisation will terminate when the fidelity error falls below this value.
 max_iterinteger
Maximum number of iterations of the optimisation algorithm.
 max_wall_timefloat
Maximum allowed elapsed time for the optimisation algorithm.
 alg_paramsDictionary
Options that are specific to the algorithm see above.
 optim_paramsDictionary
The key value pairs are the attribute name and value used to set attribute values. Note: attributes are created if they do not exist already, and are overwritten if they do. Note:
method_params
are applied afterwards and so may override these. coeff_scalingfloat
Linear scale factor for the random basis coefficients. By default these range from 1.0 to 1.0. Note this is overridden by
alg_params
(if given there). num_coeffsinteger
Number of coefficients used for each basis function. Note this is calculated automatically based on the dimension of the dynamics if not given. It is crucial to the performance of the algorithm that it is set as low as possible, while still giving high enough frequencies. Note this is overridden by
alg_params
(if given there). optim_methodstring
Multivariable optimisation method. The only tested options are ‘fmin’ and ‘Neldermead’. In theory any nongradient method implemented in
scipy.optimize.minimize
could be used. method_paramsdict
Parameters for the
optim_method
. Note that where there is an attribute of theOptimizer
object or the termination_conditions matching the key that attribute. Otherwise, and in some case also, they are assumed to be method_options for thescipy.optimize.minimize
method. The commonly used parameter are:xtol  limit on variable change for convergence
ftol  limit on fidelity error change for convergence
 phase_optionstring
Determines how global phase is treated in fidelity calculations (
fid_type='UNIT'
only). Options:PSU  global phase ignored
SU  global phase included
 dyn_paramsdict
Parameters for the
Dynamics
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. prop_paramsdict
Parameters for the
PropagatorComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. fid_paramsdict
Parameters for the
FidelityComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. tslot_typestring
Method for computing the dynamics generators, propagators and evolution in the timeslots. Options: DEF, UPDATE_ALL, DYNAMIC. UPDATE_ALL is the only one that currently works. (See
TimeslotComputer
classes for details). tslot_paramsdict
Parameters for the
TimeslotComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. guess_pulse_typestring, optional
Type / shape of pulse(s) used modulate the control amplitudes. Options include: RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW, GAUSSIAN.
 guess_pulse_paramsdict
Parameters for the guess pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 guess_pulse_actionstring, ‘MODULATE’
Determines how the guess pulse is applied to the pulse generated by the basis expansion. Options are: MODULATE, ADD.
 pulse_scalingfloat
Linear scale factor for generated guess pulses. By default initial pulses are generated with amplitudes in the range (1.0, 1.0). These will be scaled by this parameter.
 pulse_offsetfloat
Linear offset for the pulse. That is this value will be added to any guess pulses generated.
 ramping_pulse_typestring
Type of pulse used to modulate the control pulse. It’s intended use for a ramping modulation, which is often required in experimental setups. This is only currently implemented in CRAB. GAUSSIAN_EDGE was added for this purpose.
 ramping_pulse_paramsdict
Parameters for the ramping pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 log_levelinteger
Level of messaging output from the logger. Options are attributes of
qutip.logging_utils
, in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL. Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN. out_file_extstring or None
Files containing the initial and final control pulse amplitudes are saved to the current directory. The default name will be postfixed with this extension. Setting this to None will suppress the output of files.
 gen_statsboolean
If set to
True
then statistics for the optimisation run will be generated  accessible through attributes of the stats object.
 Returns
 optOptimResult
Returns instance of
OptimResult
, which has attributes giving the reason for termination, final fidelity error, final evolution final amplitudes, statistics etc.

optimize_pulse
(drift, ctrls, initial, target, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e10, min_grad=1e10, max_iter=500, max_wall_time=180, alg='GRAPE', alg_params=None, optim_params=None, optim_method='DEF', method_params=None, optim_alg=None, max_metric_corr=None, accuracy_factor=None, dyn_type='GEN_MAT', dyn_params=None, prop_type='DEF', prop_params=None, fid_type='DEF', fid_params=None, phase_option=None, fid_err_scale_factor=None, tslot_type='DEF', tslot_params=None, amp_update_mode=None, init_pulse_type='DEF', init_pulse_params=None, pulse_scaling=1.0, pulse_offset=0.0, ramping_pulse_type=None, ramping_pulse_params=None, log_level=0, out_file_ext=None, gen_stats=False)[source]¶ Optimise a control pulse to minimise the fidelity error. The dynamics of the system in any given timeslot are governed by the combined dynamics generator, i.e. the sum of the
drift + ctrl_amp[j]*ctrls[j]
.The control pulse is an
[n_ts, n_ctrls]
array of piecewise amplitudes Starting from an initial (typically random) pulse, a multivariable optimisation algorithm attempts to determines the optimal values for the control pulse to minimise the fidelity error. The fidelity error is some measure of distance of the system evolution from the given target evolution in the time allowed for the evolution. Parameters
 driftQobj or list of Qobj
The underlying dynamics generator of the system can provide list (of length
num_tslots
) for time dependent drift. ctrlsList of Qobj or array like [num_tslots, evo_time]
A list of control dynamics generators. These are scaled by the amplitudes to alter the overall dynamics. Arraylike input can be provided for time dependent control generators.
 initialQobj
Starting point for the evolution. Typically the identity matrix.
 targetQobj
Target transformation, e.g. gate or state, for the time evolution.
 num_tslotsinteger or None
Number of timeslots.
None
implies that timeslots will be given in the tau array. evo_timefloat or None
Total time for the evolution.
None
implies that timeslots will be given in the tau array. tauarray[num_tslots] of floats or None
Durations for the timeslots. If this is given then
num_tslots
andevo_time
are derived from it.None
implies that timeslot durations will be equal and calculated asevo_time/num_tslots
. amp_lboundfloat or list of floats
Lower boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 amp_uboundfloat or list of floats
Upper boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 fid_err_targfloat
Fidelity error target. Pulse optimisation will terminate when the fidelity error falls below this value.
 mim_gradfloat
Minimum gradient. When the sum of the squares of the gradients wrt to the control amplitudes falls below this value, the optimisation terminates, assuming local minima.
 max_iterinteger
Maximum number of iterations of the optimisation algorithm.
 max_wall_timefloat
Maximum allowed elapsed time for the optimisation algorithm.
 algstring
Algorithm to use in pulse optimisation. Options are:
‘GRAPE’ (default)  GRadient Ascent Pulse Engineering
‘CRAB’  Chopped RAndom Basis
 alg_paramsDictionary
Options that are specific to the algorithm see above.
 optim_paramsDictionary
The key value pairs are the attribute name and value used to set attribute values. Note: attributes are created if they do not exist already, and are overwritten if they do. Note:
method_params
are applied afterwards and so may override these. optim_methodstring
A
scipy.optimize.minimize
method that will be used to optimise the pulse for minimum fidelity error. Note thatFMIN
,FMIN_BFGS
&FMIN_L_BFGS_B
will all result in calling these specificscipy.optimize methods
. Note theLBFGSB
is equivalent toFMIN_L_BFGS_B
for backwards compatibility reasons. Supplying DEF will given alg dependent result:GRAPE  Default
optim_method
isFMIN_L_BFGS_B
CRAB  Default
optim_method
isFMIN
 method_paramsdict
Parameters for the
optim_method
. Note that where there is an attribute of theOptimizer
object or the termination_conditions matching the key that attribute. Otherwise, and in some case also, they are assumed to be method_options for thescipy.optimize.minimize
method. optim_algstring
Deprecated. Use
optim_method
. max_metric_corrinteger
Deprecated. Use
method_params
instead. accuracy_factorfloat
Deprecated. Use
method_params
instead. dyn_typestring
Dynamics type, i.e. the type of matrix used to describe the dynamics. Options are
UNIT
,GEN_MAT
,SYMPL
(seeDynamics
classes for details). dyn_paramsdict
Parameters for the
Dynamics
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. prop_typestring
Propagator type i.e. the method used to calculate the propagators and propagator gradient for each timeslot options are DEF, APPROX, DIAG, FRECHET, AUG_MAT. DEF will use the default for the specific
dyn_type
(seePropagatorComputer
classes for details). prop_paramsdict
Parameters for the
PropagatorComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. fid_typestring
Fidelity error (and fidelity error gradient) computation method. Options are DEF, UNIT, TRACEDIFF, TD_APPROX. DEF will use the default for the specific
dyn_type
(SeeFidelityComputer
classes for details). fid_paramsdict
Parameters for the
FidelityComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. phase_optionstring
Deprecated. Pass in
fid_params
instead. fid_err_scale_factorfloat
Deprecated. Use
scale_factor
key infid_params
instead. tslot_typestring
Method for computing the dynamics generators, propagators and evolution in the timeslots. Options: DEF, UPDATE_ALL, DYNAMIC. UPDATE_ALL is the only one that currently works. (See
TimeslotComputer
classes for details.) tslot_paramsdict
Parameters for the
TimeslotComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. amp_update_modestring
Deprecated. Use
tslot_type
instead. init_pulse_typestring
Type / shape of pulse(s) used to initialise the control amplitudes. Options (GRAPE) include: RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW. Default is RND. (see
PulseGen
classes for details). For the CRAB the this theguess_pulse_type
. init_pulse_paramsdict
Parameters for the initial / guess pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 pulse_scalingfloat
Linear scale factor for generated initial / guess pulses. By default initial pulses are generated with amplitudes in the range (1.0, 1.0). These will be scaled by this parameter.
 pulse_offsetfloat
Linear offset for the pulse. That is this value will be added to any initial / guess pulses generated.
 ramping_pulse_typestring
Type of pulse used to modulate the control pulse. It’s intended use for a ramping modulation, which is often required in experimental setups. This is only currently implemented in CRAB. GAUSSIAN_EDGE was added for this purpose.
 ramping_pulse_paramsdict
Parameters for the ramping pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 log_levelinteger
Level of messaging output from the logger. Options are attributes of
qutip.logging_utils
, in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL. Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN. out_file_extstring or None
Files containing the initial and final control pulse amplitudes are saved to the current directory. The default name will be postfixed with this extension. Setting this to None will suppress the output of files.
 gen_statsboolean
If set to True then statistics for the optimisation run will be generated  accessible through attributes of the stats object.
 Returns
 optOptimResult
Returns instance of
OptimResult
, which has attributes giving the reason for termination, final fidelity error, final evolution final amplitudes, statistics etc.

optimize_pulse_unitary
(H_d, H_c, U_0, U_targ, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e10, min_grad=1e10, max_iter=500, max_wall_time=180, alg='GRAPE', alg_params=None, optim_params=None, optim_method='DEF', method_params=None, optim_alg=None, max_metric_corr=None, accuracy_factor=None, phase_option='PSU', dyn_params=None, prop_params=None, fid_params=None, tslot_type='DEF', tslot_params=None, amp_update_mode=None, init_pulse_type='DEF', init_pulse_params=None, pulse_scaling=1.0, pulse_offset=0.0, ramping_pulse_type=None, ramping_pulse_params=None, log_level=0, out_file_ext=None, gen_stats=False)[source]¶ Optimise a control pulse to minimise the fidelity error, assuming that the dynamics of the system are generated by unitary operators. This function is simply a wrapper for optimize_pulse, where the appropriate options for unitary dynamics are chosen and the parameter names are in the format familiar to unitary dynamics The dynamics of the system in any given timeslot are governed by the combined Hamiltonian, i.e. the sum of the
H_d + ctrl_amp[j]*H_c[j]
The control pulse is an[n_ts, n_ctrls]
array of piecewise amplitudes Starting from an initial (typically random) pulse, a multivariable optimisation algorithm attempts to determines the optimal values for the control pulse to minimise the fidelity error The maximum fidelity for a unitary system is 1, i.e. when the time evolution resulting from the pulse is equivalent to the target. And therefore the fidelity error is1  fidelity
. Parameters
 H_dQobj or list of Qobj
Drift (aka system) the underlying Hamiltonian of the system can provide list (of length
num_tslots
) for time dependent drift. H_cList of Qobj or array like [num_tslots, evo_time]
A list of control Hamiltonians. These are scaled by the amplitudes to alter the overall dynamics. Arraylike input can be provided for time dependent control generators.
 U_0Qobj
Starting point for the evolution. Typically the identity matrix.
 U_targQobj
Target transformation, e.g. gate or state, for the time evolution.
 num_tslotsinteger or None
Number of timeslots.
None
implies that timeslots will be given in the tau array. evo_timefloat or None
Total time for the evolution.
None
implies that timeslots will be given in the tau array. tauarray[num_tslots] of floats or None
Durations for the timeslots. If this is given then
num_tslots
andevo_time
are derived from it.None
implies that timeslot durations will be equal and calculated asevo_time/num_tslots
. amp_lboundfloat or list of floats
Lower boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 amp_uboundfloat or list of floats
Upper boundaries for the control amplitudes. Can be a scalar value applied to all controls or a list of bounds for each control.
 fid_err_targfloat
Fidelity error target. Pulse optimisation will terminate when the fidelity error falls below this value.
 mim_gradfloat
Minimum gradient. When the sum of the squares of the gradients wrt to the control amplitudes falls below this value, the optimisation terminates, assuming local minima.
 max_iterinteger
Maximum number of iterations of the optimisation algorithm.
 max_wall_timefloat
Maximum allowed elapsed time for the optimisation algorithm.
 algstring
Algorithm to use in pulse optimisation. Options are:
‘GRAPE’ (default)  GRadient Ascent Pulse Engineering
‘CRAB’  Chopped RAndom Basis
 alg_paramsDictionary
options that are specific to the algorithm see above
 optim_paramsDictionary
The key value pairs are the attribute name and value used to set attribute values. Note: attributes are created if they do not exist already, and are overwritten if they do. Note:
method_params
are applied afterwards and so may override these. optim_methodstring
A
scipy.optimize.minimize
method that will be used to optimise the pulse for minimum fidelity error Note thatFMIN
,FMIN_BFGS
&FMIN_L_BFGS_B
will all result in calling these specific scipy.optimize methods Note theLBFGSB
is equivalent toFMIN_L_BFGS_B
for backwards compatibility reasons. SupplyingDEF
will given algorithmdependent result:GRAPE  Default
optim_method
is FMIN_L_BFGS_BCRAB  Default
optim_method
is FMIN
 method_paramsdict
Parameters for the
optim_method
. Note that where there is an attribute of theOptimizer
object or thetermination_conditions
matching the key that attribute. Otherwise, and in some case also, they are assumed to be method_options for thescipy.optimize.minimize
method. optim_algstring
Deprecated. Use
optim_method
. max_metric_corrinteger
Deprecated. Use
method_params
instead. accuracy_factorfloat
Deprecated. Use
method_params
instead. phase_optionstring
Determines how global phase is treated in fidelity calculations (
fid_type='UNIT'
only). Options:PSU  global phase ignored
SU  global phase included
 dyn_paramsdict
Parameters for the
Dynamics
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. prop_paramsdict
Parameters for the
PropagatorComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. fid_paramsdict
Parameters for the
FidelityComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. tslot_typestring
Method for computing the dynamics generators, propagators and evolution in the timeslots. Options:
DEF
,UPDATE_ALL
,DYNAMIC
.UPDATE_ALL
is the only one that currently works. (SeeTimeslotComputer
classes for details.) tslot_paramsdict
Parameters for the
TimeslotComputer
object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created. amp_update_modestring
Deprecated. Use
tslot_type
instead. init_pulse_typestring
Type / shape of pulse(s) used to initialise the control amplitudes. Options (GRAPE) include: RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW. DEF is RND. (see
PulseGen
classes for details.) For the CRAB the this the guess_pulse_type. init_pulse_paramsdict
Parameters for the initial / guess pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 pulse_scalingfloat
Linear scale factor for generated initial / guess pulses. By default initial pulses are generated with amplitudes in the range (1.0, 1.0). These will be scaled by this parameter.
 pulse_offsetfloat
Linear offset for the pulse. That is this value will be added to any initial / guess pulses generated.
 ramping_pulse_typestring
Type of pulse used to modulate the control pulse. It’s intended use for a ramping modulation, which is often required in experimental setups. This is only currently implemented in CRAB. GAUSSIAN_EDGE was added for this purpose.
 ramping_pulse_paramsdict
Parameters for the ramping pulse generator object. The key value pairs are assumed to be attribute name value pairs. They applied after the object is created.
 log_levelinteger
Level of messaging output from the logger. Options are attributes of
qutip.logging_utils
in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN. out_file_extstring or None
Files containing the initial and final control pulse amplitudes are saved to the current directory. The default name will be postfixed with this extension. Setting this to
None
will suppress the output of files. gen_statsboolean
If set to
True
then statistics for the optimisation run will be generated  accessible through attributes of the stats object.
 Returns
 optOptimResult
Returns instance of
OptimResult
, which has attributes giving the reason for termination, final fidelity error, final evolution final amplitudes, statistics etc.
Pulse generator  Generate pulses for the timeslots Each class defines a gen_pulse function that produces a float array of size num_tslots. Each class produces a differ type of pulse. See the class and gen_pulse function descriptions for details

create_pulse_gen
(pulse_type='RND', dyn=None, pulse_params=None)[source]¶ Create and return a pulse generator object matching the given type. The pulse generators each produce a different type of pulse, see the gen_pulse function description for details. These are the random pulse options:
RND  Independent random value in each timeslot RNDFOURIER  Fourier series with random coefficients RNDWAVES  Summation of random waves RNDWALK1  Random change in amplitude each timeslot RNDWALK2  Random change in amp gradient each timeslot
These are the other nonperiodic options:
LIN  Linear, i.e. contant gradient over the time ZERO  special case of the LIN pulse, where the gradient is 0
These are the periodic options
SINE  Sine wave SQUARE  Square wave SAW  Saw tooth wave TRIANGLE  Triangular wave
If a Dynamics object is passed in then this is used in instantiate the PulseGen, meaning that some timeslot and amplitude properties are copied over.
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 ClebschGordon 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
zcomponent of angular momentum 1.
 m2float
zcomponent of angular momentum 2.
 m3float
zcomponent of angular momentum 3.
 Returns
 cg_coefffloat
Requested ClebschGordan 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.
 origstring
The name of the original unit (“J”, “eV”, “meV”, “GHz”, “mK”)
 tostring
The name of the new unit (“J”, “eV”, “meV”, “GHz”, “mK”)
 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 array
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
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’}
Type of numerical data.
 numformatstr {‘decimal’,’exp’}
Format for written data.
 sepstr
Singlecharacter field seperator. Usually a tab, space, comma, or semicolon.
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.

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 / dictionary
The optional additional argument to the
task
function. task_kwargslist / dictionary
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. Note that the order in which results are passed to
reduce_func
is not defined. progress_barstring
Progress bar options’s string for showing progress.
 progress_bar_kwargsdict
Options for the progress bar.
 map_kw: dict (optional)
Dictionary containing entry for:  timeout: float, Maximum time (sec) for the whole map.  job_timeout: float, Maximum time (sec) for each job in the map.  num_cpus: int, Number of job to run at once.  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 invalues
. If areduce_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 dropin replacement of
qutip.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 / dictionary
The optional additional argument to the
task
function. task_kwargslist / dictionary
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.
 progress_barstring
Progress bar options’s string for showing progress.
 progress_bar_kwargsdict
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 invalues
. If areduce_func
is provided, and empty list will be returned.
Semidefinite Programming¶
IPython Notebook Tools¶
This module contains utility functions for using QuTiP with IPython notebooks.

parallel_map
(task, values, task_args=None, task_kwargs=None, client=None, view=None, progress_bar=None, show_scheduling=False, **kwargs)[source]¶ Call the function
task
for each value invalues
using a cluster of IPython engines. The functiontask
should have the signaturetask(value, *args, **kwargs)
.The
client
andview
are the IPython.parallel client and loadbalanced view that will be used in the parfor execution. If these areNone
, new instances will be created. Parameters
 task: a Python function
The function that is to be called for each value in
task_vec
. values: array / list
The list or array of values for which the
task
function is to be evaluated. task_args: list / dictionary
The optional additional argument to the
task
function. task_kwargs: list / dictionary
The optional additional keyword argument to the
task
function. client: IPython.parallel.Client
The IPython.parallel Client instance that will be used in the parfor execution.
 view: a IPython.parallel.Client view
The view that is to be used in scheduling the tasks on the IPython cluster. Preferably a loadbalanced view, which is obtained from the IPython.parallel.Client instance client by calling, view = client.load_balanced_view().
 show_scheduling: bool {False, True}, default False
Display a graph showing how the tasks (the evaluation of
task
for for the value intask_vec1
) was scheduled on the IPython engine cluster. show_progressbar: bool {False, True}, default False
Display a HTMLbased progress bar during the execution of the parfor loop.
 Returns
 resultlist
The result list contains the value of
task(value, task_args, task_kwargs)
for each value invalues
.

version_table
(verbose=False)[source]¶ Print an HTMLformatted table with version numbers for QuTiP and its dependencies. Use it in a IPython notebook to show which versions of different packages that were used to run the notebook. This should make it possible to reproduce the environment and the calculation later on.
 Returns
 version_table: string
Return an HTMLformatted 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 = 1e14, safe_mode: bool = True)[source]¶ Simultaneous diagonalization of commuting Hermitian matrices.
 Parameters
 opslist/array
list
orarray
of qobjs representing commuting Hermitian operators. evalsbool [True]
Whether to return the eigenvalues for each ops and eigenvectors or just the eigenvectors.
 tolfloat [1e14]
Tolerance for detecting degenerate eigenstates.
 safe_modebool [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.