Functions

Manipulation and Creation of States and Operators

Quantum States

basis(N, n=0, offset=0)[source]

Generates the vector representation of a Fock state.

Parameters
Nint

Number of Fock states in Hilbert space.

nint

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

offsetint (default 0)

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

Returns
statequtip.Qobj

Qobj representing the requested number state |n>.

Notes

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

basis(N, 0) = ground state

but in the qotoolbox:

basis(N, 1) = ground state

Examples

>>> basis(5,2)
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 0.+0.j]
 [ 0.+0.j]
 [ 1.+0.j]
 [ 0.+0.j]
 [ 0.+0.j]]
bell_state(state='00')[source]

Returns the Bell state:

|B00> = 1 / sqrt(2)*[|0>|0>+|1>|1>] |B01> = 1 / sqrt(2)*[|0>|0>-|1>|1>] |B10> = 1 / sqrt(2)*[|0>|1>+|1>|0>] |B11> = 1 / sqrt(2)*[|0>|1>-|1>|0>]

Returns
Bell_stateqobj

Bell state

bra(seq, dim=2)[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.

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

Generates a coherent state with eigenvalue alpha.

Constructed using displacement operator on vacuum state.

Parameters
Nint

Number of Fock states in Hilbert space.

alphafloat/complex

Eigenvalue of coherent state.

offsetint (default 0)

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

methodstring {‘operator’, ‘analytic’}

Method for generating coherent state.

Returns
stateqobj

Qobj quantum object for coherent state

Notes

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

Examples

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

Returns
dmqobj

Density matrix representation of coherent state.

Notes

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

Examples

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

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

Parameters
dims: list

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

excitationsinteger

The maximum numbers of dimension

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

The number of states nstates, a dictionary for looking up state indices from a state tuple, and a dictionary for looking up state state tuples from state indices.

enr_thermal_dm(dims, excitations, n)[source]

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

Parameters
dimslist

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

excitationsinteger

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

ninteger

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

Returns
dmQobj

Thermal state density matrix.

enr_fock(dims, excitations, state)[source]

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

Parameters
dimslist

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

excitationsinteger

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

statelist of integers

The state in the number basis representation.

Returns
ketQobj

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

fock(N, n=0, offset=0)[source]

Bosonic Fock (number) state.

Same as qutip.states.basis.

Parameters
Nint

Number of states in the Hilbert space.

nint

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

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

Examples

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

Density matrix representation of a Fock state

Constructed via outer product of qutip.states.fock.

Parameters
Nint

Number of Fock states in Hilbert space.

nint

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

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

Returns the N-qubit GHZ-state.

Parameters
Nint (default=3)

Number of qubits in state

Returns
Gqobj

N-qubit GHZ-state

maximally_mixed_dm(N)[source]

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

Parameters
Nint

Number of basis states in Hilbert space.

Returns
dmqobj

Thermal state density matrix.

ket(seq, dim=2)[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.

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.

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]]
phase_basis(N, m, phi0=0)[source]

Basis vector for the mth phase of the Pegg-Barnett 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.

Returns
stateqobj

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

Notes

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

projection(N, n, m, offset=0)[source]

The projection operator that projects state \(|m>\) on state \(|n>\).

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.

Returns
operqobj

Requested projection operator.

qutrit_basis()[source]

Basis states for a three level system (qutrit)

Returns
qstatesarray

Array of qutrit basis vectors

singlet_state()[source]

Returns the two particle singlet-state:

|S>=1/sqrt(2)*[|0>|1>-|1>|0>]

that is identical to the fourth bell state.

Returns
Bell_stateqobj

|B11> Bell state

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

Generates the spin state |j, m>, i.e. the eigenstate of the spin-j Sz operator with eigenvalue m.

Parameters
jfloat

The spin of the state ().

mint

Eigenvalue of the spin-j Sz operator.

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

Type of state to generate.

Returns
stateqobj

Qobj quantum object for spin state

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

Generate the coherent spin state |theta, phi>.

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.

Returns
stateqobj

Qobj quantum object for spin coherent state

state_number_enumerate(dims, excitations=None, state=None, idx=0)[source]

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

Example

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

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

statelist

Current state in the iteration. Used internally.

excitationsinteger (None)

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

idxinteger

Current index in the iteration. Used internally.

Returns
state_numberlist

Successive state number arrays 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_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
statelist

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

state_number_qobj(dims, state)[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.

Returns
statequtip.Qobj.qobj

The state as a qutip.Qobj.qobj instance.

thermal_dm(N, n, method='operator')[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

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]]
zero_ket(N, dims=None)[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.

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)[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.

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

Creation (raising) operator.

Parameters
Nint

Dimension of Hilbert space.

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)[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.

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

Single-mode 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.

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

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

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

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

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

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

Parameters
dimslist

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

excitationsinteger

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

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

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

Parameters
dimslist

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

excitationsinteger

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

statelist of integers

The state in the number basis representation.

Returns
opQobj

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

jmat(j, *args)[source]

Higher-order spin operators:

Parameters
jfloat

Spin of operator

argsstr

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

Returns
jmatqobj / ndarray

qobj for requested spin operator(s).

Notes

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

Examples

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

Returns
oper: qobj

Qobj for number operator.

Examples

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

Identity operator

Parameters
Nint or list of ints

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.

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

Identity operator. Alternative name to qeye.

Parameters
Nint or list of ints

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.

Returns
operqobj

Identity operator Qobj.

momentum(N, offset=0)[source]

Momentum operator p=-1j/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.

Returns
operqobj

Momentum operator as Qobj.

phase(N, phi0=0)[source]

Single-mode Pegg-Barnett phase operator.

Parameters
Nint

Number of basis states in Hilbert space.

phi0float

Reference phase.

Returns
operqobj

Phase operator with respect to reference phase.

Notes

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

position(N, offset=0)[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.

Returns
operqobj

Position operator as Qobj.

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

Constructs an operator from an array of diagonals.

Parameters
diagonalssequence of array_like

Array of elements to place along the selected diagonals.

offsetssequence of ints
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.

See also

scipy.sparse.diags

for usage information.

Notes

This function requires SciPy 0.11+.

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

Operators for a three level system (qutrit).

Returns
opers: array

array of qutrit operators.

qzero(N)[source]

Zero operator

Parameters
Nint or list of ints

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.

Returns
qzeroqobj

Zero operator Qobj.

sigmam()[source]

Annihilation operator for Pauli spins.

Examples

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

Creation operator for Pauli spins.

Examples

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

Pauli spin 1/2 sigma-x operator

Examples

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

Pauli spin 1/2 sigma-y operator.

Examples

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

Pauli spin 1/2 sigma-z operator.

Examples

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

Spin-j x operator

Parameters
jfloat

Spin of operator

Returns
opQobj

qobj representation of the operator.

spin_Jy(j)[source]

Spin-j y operator

Parameters
jfloat

Spin of operator

Returns
opQobj

qobj representation of the operator.

spin_Jz(j)[source]

Spin-j z operator

Parameters
jfloat

Spin of operator

Returns
opQobj

qobj representation of the operator.

spin_Jm(j)[source]

Spin-j annihilation operator

Parameters
jfloat

Spin of operator

Returns
opQobj

qobj representation of the operator.

spin_Jp(j)[source]

Spin-j creation operator

Parameters
jfloat

Spin of operator

Returns
opQobj

qobj representation of the operator.

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

Single-mode Squeezing operator.

Parameters
Nint

Dimension of hilbert space.

zfloat/complex

Squeezing parameter.

offsetint (default 0)

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

Returns
operqutip.qobj.Qobj

Squeezing operator.

Examples

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

Operator 1.

a2qutip.qobj.Qobj

Operator 2.

zfloat/complex

Squeezing parameter.

Returns
operqutip.qobj.Qobj

Squeezing operator.

tunneling(N, m=1)[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.

Returns
TQobj

Tunneling operator.

Notes

New in version 3.2.

Random Operators and States

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

rand_dm(N, density=0.75, pure=False, dims=None, seed=None)[source]

Creates a random NxN density matrix.

Parameters
Nint, ndarray, list

If int, then shape of output operator. If list/ndarray then eigenvalues of generated density matrix.

densityfloat

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

dimslist

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

Returns
operqobj

NxN density matrix quantum operator.

Notes

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

rand_dm_ginibre(N=2, rank=None, dims=None, seed=None)[source]

Returns a Ginibre random density operator of dimension dim and rank rank by using the algorithm of [BCSZ08]. If rank is None, a full-rank (Hilbert-Schmidt ensemble) random density operator will be returned.

Parameters
Nint

Dimension of the density operator to be returned.

dimslist

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

rankint or None

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

Returns
rhoQobj

An N × N density operator sampled from the Ginibre or Hilbert-Schmidt distribution.

rand_dm_hs(N=2, dims=None, seed=None)[source]

Returns a Hilbert-Schmidt random density operator of dimension dim and rank rank by using the algorithm of [BCSZ08].

Parameters
Nint

Dimension of the density operator to be returned.

dimslist

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

Returns
rhoQobj

A dim × dim density operator sampled from the Ginibre or Hilbert-Schmidt distribution.

rand_herm(N, density=0.75, dims=None, pos_def=False, seed=None)[source]

Creates a random NxN sparse Hermitian quantum object.

If ‘N’ is an integer, uses \(H=0.5*(X+X^{+})\) where \(X\) is a randomly generated quantum operator with a given density. Else uses complex Jacobi rotations when ‘N’ is given by an array.

Parameters
Nint, list/ndarray

If int, then shape of output operator. If list/ndarray then eigenvalues of generated operator.

densityfloat

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

dimslist

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

pos_defbool (default=False)

Return a positive semi-definite matrix (by diagonal dominance).

Returns
operqobj

NxN Hermitian quantum operator.

rand_ket(N, density=1, dims=None, seed=None)[source]

Creates a random Nx1 sparse ket vector.

Parameters
Nint

Number of rows for output quantum operator.

densityfloat

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

dimslist

Left-dimensions of quantum object. Used for specifying tensor structure. Default is dims=[[N]].

Returns
operqobj

Nx1 ket state quantum operator.

rand_ket_haar(N=2, dims=None, seed=None)[source]

Returns a Haar random pure state of dimension dim by applying a Haar random unitary to a fixed pure state.

Parameters
Nint

Dimension of the state vector to be returned.

dimslist of ints, or None

Left-dimensions of the resultant quantum object. If None, [N] is used.

Returns
psiQobj

A random state vector drawn from the Haar measure.

rand_unitary(N, density=0.75, dims=None, seed=None)[source]

Creates a random NxN sparse unitary quantum object.

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

Parameters
Nint

Shape of output quantum operator.

densityfloat

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

dimslist

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

Returns
operqobj

NxN Unitary quantum operator.

rand_unitary_haar(N=2, dims=None, seed=None)[source]

Returns a Haar random unitary matrix of dimension dim, using the algorithm of [Mez07].

Parameters
Nint

Dimension of the unitary to be returned.

dimslist of lists of int, or None

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

Returns
UQobj

Unitary of dims [[dim], [dim]] drawn from the Haar measure.

rand_super(N=5, dims=None, seed=None)[source]

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

Parameters
Nint

Square root of the dimension of the superoperator to be returned.

dimslist

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

rand_super_bcsz(N=2, enforce_tp=True, rank=None, dims=None, seed=None)[source]

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

Parameters
Nint

Square root of the dimension of the superoperator to be returned.

enforce_tpbool

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

rankint or None

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

dimslist

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

Returns
rhoQobj

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

Three-Level Atoms

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

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

References

The naming of qutip operators follows the convention in [R0be8dcf25d86-1] .

R0be8dcf25d86-1

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

Notes

Contributed by Markus Baden, Oct. 07, 2011

three_level_basis()[source]

Basis states for a three level atom.

Returns
statesarray

array of three level atom basis vectors.

three_level_ops()[source]

Operators for a three level system (qutrit)

Returns
opsarray

array of three level operators.

Superoperators and Liouvillians

operator_to_vector(op)[source]

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

vector_to_operator(op)[source]

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

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

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

Parameters
HQobj or QobjEvo

System Hamiltonian.

c_opsarray_like of Qobj or QobjEvo

A list or array of collapse operators.

Returns
LQobj or QobjEvo

Liouvillian superoperator.

spost(A)[source]

Superoperator formed from post-multiplication by operator A

Parameters
AQobj or QobjEvo

Quantum operator for post multiplication.

Returns
superQobj or QobjEvo

Superoperator formed from input qauntum object.

spre(A)[source]

Superoperator formed from pre-multiplication by operator A.

Parameters
AQobj or QobjEvo

Quantum operator for pre-multiplication.

Returns
super :Qobj or QobjEvo

Superoperator formed from input quantum object.

sprepost(A, B)[source]

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

Parameters
AQobj or QobjEvo

Quantum operator for pre-multiplication.

BQobj or QobjEvo

Quantum operator for post-multiplication.

Returns
superQobj or QobjEvo

Superoperator formed from input quantum objects.

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.

Returns
Dqobj, QobjEvo

Lindblad dissipator superoperator.

Superoperator Representations

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

to_choi(q_oper)[source]

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

Parameters
q_operQobj

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

Returns
choiQobj

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

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

to Choi representation.

to_super(q_oper)[source]

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

Parameters
q_operQobj

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

Returns
superopQobj

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

Raises
TypeError

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

to_kraus(q_oper)[source]

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

Parameters
q_operQobj

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

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.

Functions acting on states and operators

Expectation Values

expect(oper, state)[source]

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

Parameters
operqobj/array-like

A single or a list or operators for expectation value.

stateqobj/array-like

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

Returns
exptfloat/complex/array-like

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

Examples

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

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

Parameters
operqobj

Operator for expectation value.

stateqobj/list

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

Returns
varfloat

Variance of operator ‘oper’ for given state.

Tensor

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

tensor(*args)[source]

Calculates the tensor product of input operators.

Parameters
argsarray_like

list or array of quantum objects for tensor product.

Returns
objqobj

A composite quantum object.

Examples

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

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

Parameters
argsarray_like

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

Returns
objqobj

A composite quantum object.

composite(*args)[source]

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

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

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 the i and j dimensions of the original qobj should be contracted.

Returns
cqobjQobj

The original Qobj with all named index pairs contracted away.

Partial Transpose

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

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

Parameters
rhoqutip.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).

Returns
rho_pr: qutip.qobj

A density matrix with the selected subsystems transposed.

Entropy Functions

concurrence(rho)[source]

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

Parameters
stateqobj

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

Returns
concurfloat

Concurrence

References

1

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

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

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

Parameters
rhoqobj

Density matrix of composite object

selBint/list

Selected components for density matrix B

base{e,2}

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_vn(rho, base=2.718281828459045, sparse=False)[source]

Von-Neumann entropy of density matrix

Parameters
rhoqobj

Density matrix.

base{e,2}

Base of logarithm.

sparse{False,True}

Use sparse eigensolver.

Returns
entropyfloat

Von-Neumann entropy of rho.

Examples

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

Density Matrix Metrics

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

fidelity(A, B)[source]

Calculates the fidelity (pseudo-metric) 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 pseudo-metric between A and B.

Examples

>>> x = fock_dm(5,3)
>>> y = coherent_dm(5,1)
>>> fidelity(x,y)
0.24104350624628332
tracedist(A, B, sparse=False, tol=0)[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)
>>> tracedist(x,y)
0.9705143161472971
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.

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.

hilbert_dist(A, B)[source]

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

Parameters
Aqobj

Density matrix or state vector.

Bqobj

Density matrix or state vector with same dimensions as A.

Returns
distfloat

Hilbert-Schmidt distance between density matrices.

Notes

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

average_gate_fidelity(oper, target=None)[source]

Given a Qobj representing the supermatrix form of a map, returns the average gate fidelity (pseudo-metric) of that map.

Parameters
AQobj

Quantum object representing a superoperator.

targetQobj

Quantum object representing the target unitary; the inverse is applied before evaluating the fidelity.

Returns
fidfloat

Fidelity pseudo-metric between A and the identity superoperator, or between A and the target superunitary.

process_fidelity(U1, U2, normalize=True)[source]

Calculate the process fidelity given two process operators.

Continuous Variables

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

correlation_matrix(basis, rho=None)[source]

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

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

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

rhoQobj

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

Returns
corr_matndarray

A 2-dimensional array of correlation values or operators.

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 non-symmetrized correlation matrix is to be calculated.

Returns
corr_matndarray

A 2-dimensional array of covariance values.

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 2-dimensional array of covariance values, or, if rho=0, a matrix of operators.

correlation_matrix_quadrature(a1, a2, rho=None)[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.

Returns
corr_matndarray

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

wigner_covariance_matrix(a1=None, a2=None, R=None, rho=None)[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.

Returns
cov_matndarray

A 2-dimensional array of covariance values.

logarithmic_negativity(V)[source]

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

Parameters
V2d array

The covariance matrix.

Returns
Nfloat

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

Dynamics and Time-Evolution

Schrödinger Equation

This module provides solvers for the unitary Schrodinger equation.

sesolve(H, psi0, tlist, e_ops=[], args={}, options=<qutip.solver.Options object at 0x2b2261cb9eb8>, progress_bar=<qutip.ui.progressbar.BaseProgressBar object at 0x2b2261cb9ef0>, _safe_mode=True)[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

Parameters
Hqutip.qobj, qutip.qobjevo, list, callable

system Hamiltonian as a Qobj, list of Qobj and coefficient, QobjEvo, or a callback function for time-dependent Hamiltonians. list format and options can be found in QobjEvo’s description.

psi0qutip.qobj

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

tlistlist / array

list of times for \(t\).

e_opslist of qutip.qobj / callback function

single operator or list of operators for which to evaluate expectation values. For list operator evolution, the overlapse is computed:

tr(e_ops[i].dag()*op(t))

argsdictionary

dictionary of parameters for time-dependent Hamiltonians

optionsqutip.Qdeoptions

with options for the ODE solver.

progress_barBaseProgressBar

Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation.

Returns
output: qutip.solver

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

Master Equation

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

mesolve(H, rho0, tlist, c_ops=[], e_ops=[], args={}, options=<qutip.solver.Options object at 0x2b225f643f98>, progress_bar=<qutip.ui.progressbar.BaseProgressBar object at 0x2b225f643fd0>, _safe_mode=True)[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 (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 to solve master equations that are not on standard Lindblad form by passing a custom Liouvillian in place of either the H or c_ops elements.

Time-dependent operators

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

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

Examples

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

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

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

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

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

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

Additional options

Additional options to mesolve can be set via the options argument, which should be an instance of qutip.solver.Options. 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

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

Note

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

Parameters
Hqutip.Qobj

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

rho0qutip.Qobj

initial density matrix or state vector (ket).

tlistlist / array

list of times for \(t\).

c_opslist of qutip.Qobj

single collapse operator, or list of collapse operators, or a list of Liouvillian superoperators.

e_opslist of qutip.Qobj / callback function single

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

argsdictionary

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

optionsqutip.Options

with options for the solver.

progress_barBaseProgressBar

Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation.

Returns
result: qutip.Result

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

Monte Carlo Evolution

mcsolve(H, psi0, tlist, c_ops=[], e_ops=[], ntraj=0, args={}, options=<qutip.solver.Options object at 0x2b2261d09978>, progress_bar=True, map_func=<function parallel_map at 0x2b225f61c620>, map_kwargs={}, _safe_mode=True, _exp=False)[source]

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

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

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

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

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

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

H = [H0, [H1, H1_coeff]]

c_ops = [C0, [C1, C1_coeff]]

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

or in String (Cython) format we could write:

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

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

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

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

Parameters
Hqutip.Qobj, list

System Hamiltonian.

psi0qutip.Qobj

Initial state vector

tlistarray_like

Times at which results are recorded.

ntrajint

Number of trajectories to run.

c_opsqutip.Qobj, list

single collapse operator or a list of collapse operators.

e_opsqutip.Qobj, list

single operator as Qobj or list or equivalent of Qobj operators for calculating expectation values.

argsdict

Arguments for time-dependent Hamiltonian and collapse operator terms.

optionsOptions

Instance of ODE solver options.

progress_bar: BaseProgressBar

Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation. Set to None to disable the progress bar.

map_func: function

A map function for managing the calls to the single-trajactory solver.

map_kwargs: dictionary

Optional keyword arguments to the map_func function.

Returns
resultsqutip.solver.Result

Object storing all results from the simulation.

Note

It is possible to reuse the random number seeds from a previous run of the mcsolver by passing the output Result object seeds via the Options class, i.e. Options(seeds=prev_result.seeds).

Exponential Series

essolve(H, rho0, tlist, c_op_list, e_ops)[source]

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

Parameters
Hqobj/function_type

System Hamiltonian.

rho0qutip.qobj

Initial state density matrix.

tlistlist/array

list of times for \(t\).

c_op_listlist of qutip.qobj

list of qutip.qobj collapse operators.

e_opslist of qutip.qobj

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

Returns
expt_arrayarray

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

Note

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

ode2es(L, rho0)[source]

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

Parameters
Lqobj

Liouvillian of the system.

rho0qobj

Initial state vector or density matrix.

Returns
eseriesqutip.eseries

eseries represention of the system dynamics.

Bloch-Redfield Master Equation

brmesolve(H, psi0, tlist, a_ops=[], e_ops=[], c_ops=[], args={}, use_secular=True, sec_cutoff=0.1, tol=1e-12, spectra_cb=None, options=None, progress_bar=None, _safe_mode=True, verbose=False)[source]

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

For time-independent systems, the Hamiltonian must be given as a Qobj, whereas the bath-coupling terms (a_ops), must be written as a nested list of operator - spectrum function pairs, where the frequency is specified by the w variable.

Example

a_ops = [[a+a.dag(),lambda w: 0.2*(w>=0)]]

For time-dependent systems, the Hamiltonian, a_ops, and Lindblad collapse operators (c_ops), can be specified in the QuTiP string-based time-dependent format. For the a_op spectra, the frequency variable must be w, and the string cannot contain any other variables other than the possibility of having a time-dependence through the time variable t:

Example

a_ops = [[a+a.dag(), ‘0.2*exp(-t)*(w>=0)’]]

It is also possible to use Cubic_Spline objects for time-dependence. In the case of a_ops, Cubic_Splines must be passed as a tuple:

Example

a_ops = [ [a+a.dag(), ( f(w), g(t)] ]

where f(w) and g(t) are strings or Cubic_spline objects for the bath spectrum and time-dependence, respectively.

Finally, if one has bath-couplimg terms of the form H = f(t)*a + conj[f(t)]*a.dag(), then the correct input format is

Example

a_ops = [ [(a,a.dag()), (f(w), g1(t), g2(t))],… ]

where f(w) is the spectrum of the operators while g1(t) and g2(t) are the time-dependence of the operators a and a.dag(), respectively

Parameters
HQobj / list

System Hamiltonian given as a Qobj or nested list in string-based format.

psi0: Qobj

Initial density matrix or state vector (ket).

tlistarray_like

List of times for evaluating evolution

a_opslist

Nested list of Hermitian system operators that couple to the bath degrees of freedom, along with their associated spectra.

e_opslist

List of operators for which to evaluate expectation values.

c_opslist

List of system collapse operators, or nested list in string-based format.

argsdict

Placeholder for future implementation, kept for API consistency.

use_secularbool {True}

Use secular approximation when evaluating bath-coupling terms.

sec_cutofffloat {0.1}

Cutoff for secular approximation.

tolfloat {qutip.setttings.atol}

Tolerance used for removing small values after basis transformation.

spectra_cblist

DEPRECIATED. Do not use.

optionsqutip.solver.Options

Options for the solver.

progress_barBaseProgressBar

Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation.

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.

bloch_redfield_tensor()

Calculates the time-independent Bloch-Redfield tensor for a system given a set of operators and corresponding spectral functions that describes the system’s couplingto its environment.

Parameters
Hqutip.qobj

System Hamiltonian.

a_opslist

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

spectra_cblist

Depreciated.

c_opslist

List of system collapse operators.

use_secularbool {True, False}

Flag that indicates if the secular approximation should be used.

sec_cutofffloat {0.1}

Threshold for secular approximation.

atolfloat {qutip.settings.atol}

Threshold for removing small parameters.

Returns
R, kets: qutip.Qobj, list of qutip.Qobj

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

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

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

Parameters
Rqutip.qobj

Bloch-Redfield tensor.

eketsarray of qutip.qobj

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

rho0qutip.qobj

Initial density matrix.

tlistlist / array

List of times for \(t\).

e_opslist of qutip.qobj / callback function

List of operators for which to evaluate expectation values.

optionsqutip.Qdeoptions

Options for the ODE solver.

Returns
output: qutip.solver

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

Floquet States and Floquet-Markov Master Equation

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

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

Note

This solver currently does not support multiple collapse operators.

Parameters
Hqutip.qobj

system Hamiltonian.

rho0 / psi0qutip.qobj

initial density matrix or state vector (ket).

tlistlist / array

list of times for \(t\).

c_opslist of qutip.qobj

list of collapse operators.

e_opslist of qutip.qobj / callback function

list of operators for which to evaluate expectation values.

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 time-dependence of the hamiltonian. The default value ‘None’ indicates that the ‘tlist’ spans a single period of the driving.

argsdictionary

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

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

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

options for the ODE solver.

k_maxint

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

Returns
outputqutip.solver

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

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

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

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

Parameters
Hqutip.qobj

system Hamiltonian, time-dependent with period T

argsdictionary

dictionary with variables required to evaluate H

Tfloat

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

Uqutip.qobj

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

Returns
outputlist of kets, list of quasi energies

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

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

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

Parameters
f_modes_0list of qutip.qobj (kets)

Floquet modes at \(t\)

f_energieslist

Floquet energies.

tfloat

The time at which to evaluate the floquet modes.

Hqutip.qobj

system Hamiltonian, time-dependent with period T

argsdictionary

dictionary with variables required to evaluate H

Tfloat

The period of the time-dependence of the hamiltonian.

Returns
outputlist of kets

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

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

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

Parameters
f_modes_0list of qutip.qobj (kets)

Floquet modes at \(t\)

f_energieslist

Floquet energies.

tlistarray

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

Hqutip.qobj

system Hamiltonian, time-dependent with period T

Tfloat

The period of the time-dependence of the hamiltonian.

argsdictionary

dictionary with variables required to evaluate H

Returns
outputnested list

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

floquet_modes_t_lookup(f_modes_table_t, t, T)[source]

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

Parameters
f_modes_table_tnested list of qutip.qobj (kets)

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

tfloat

The time for which to evaluate the Floquet modes.

Tfloat

The period of the time-dependence of the hamiltonian.

Returns
outputnested list

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

floquet_states(f_modes_t, f_energies, t)[source]

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

Parameters
f_modes_tlist of qutip.qobj (kets)

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

f_energiesarray

The Floquet energies.

tfloat

The time for which to evaluate the Floquet states.

Returns
outputlist

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

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

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

Parameters
f_modes_tlist of qutip.qobj (kets)

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

f_energiesarray

The Floquet energies.

tfloat

The time for which to evaluate the Floquet states.

Hqutip.qobj

System Hamiltonian, time-dependent with period T.

Tfloat

The period of the time-dependence of the hamiltonian.

argsdictionary

Dictionary with variables required to evaluate H.

Returns
outputlist

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

floquet_wavefunction(f_modes_t, f_energies, f_coeff, t)[source]

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

Parameters
f_modes_tlist of qutip.qobj (kets)

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

f_energiesarray

The Floquet energies.

f_coeffarray

The coefficients for Floquet decomposition of the initial wavefunction.

tfloat

The time for which to evaluate the Floquet states.

Returns
outputqutip.qobj

The wavefunction for the time \(t\).

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

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

Parameters
f_modes_tlist of qutip.qobj (kets)

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

f_energiesarray

The Floquet energies.

f_coeffarray

The coefficients for Floquet decomposition of the initial wavefunction.

tfloat

The time for which to evaluate the Floquet states.

Hqutip.qobj

System Hamiltonian, time-dependent with period T.

Tfloat

The period of the time-dependence of the hamiltonian.

argsdictionary

Dictionary with variables required to evaluate H.

Returns
outputqutip.qobj

The wavefunction for the time \(t\).

floquet_state_decomposition(f_states, f_energies, psi)[source]

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

Parameters
f_stateslist of qutip.qobj (kets)

A list of Floquet modes.

f_energiesarray

The Floquet energies.

psiqutip.qobj

The wavefunction to decompose in the Floquet state basis.

Returns
outputarray

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

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

Solve the Schrodinger equation using the Floquet formalism.

Parameters
Hqutip.qobj.Qobj

System Hamiltonian, time-dependent with period T.

psi0qutip.qobj

Initial state vector (ket).

tlistlist / array

list of times for \(t\).

e_opslist of qutip.qobj / callback function

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

Tfloat

The period of the time-dependence of the hamiltonian.

argsdictionary

Dictionary with variables required to evaluate H.

Tstepsinteger

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

Returns
outputqutip.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.

floquet_master_equation_rates(f_modes_0, f_energies, c_op, H, T, args, J_cb, w_th, kmax=5, f_modes_table_t=None)[source]

Calculate the rates and matrix elements for the Floquet-Markov master equation.

Parameters
f_modes_0list of qutip.qobj (kets)

A list of initial Floquet modes.

f_energiesarray

The Floquet energies.

c_opqutip.qobj

The collapse operators describing the dissipation.

Hqutip.qobj

System Hamiltonian, time-dependent with period T.

Tfloat

The period of the time-dependence of the hamiltonian.

argsdictionary

Dictionary with variables required to evaluate H.

J_cbcallback functions

A callback function that computes the noise power spectrum, as a function of frequency, associated with the collapse operator c_op.

w_thfloat

The temperature in units of frequency.

k_maxint

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

f_modes_table_tnested list of qutip.qobj (kets)

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

Returns
outputlist

A list (Delta, X, Gamma, A) containing the matrices Delta, X, Gamma and A used in the construction of the Floquet-Markov master equation.

floquet_master_equation_steadystate(H, A)[source]

Returns the steadystate density matrix (in the floquet basis!) for the Floquet-Markov master equation.

floquet_basis_transform(f_modes, f_energies, rho0)[source]

Make a basis transform that takes rho0 from the floquet basis to the computational basis.

floquet_markov_mesolve(R, ekets, rho0, tlist, e_ops, f_modes_table=None, options=None, floquet_basis=True)[source]

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

Stochastic Schrödinger Equation and Master Equation

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
Hqutip.Qobj, or time dependent system.

System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.

rho0qutip.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.

Returns
output: qutip.solver.Result

An instance of the class qutip.solver.Result.

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
Hqutip.Qobj, or time dependent system.

System Hamiltonian. Can depend on time, see StochasticSolverOptions help for format.

psi0qutip.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.

Returns
output: qutip.solver.Result

An instance of the class qutip.solver.Result.

smepdpsolve(H, rho0, times, c_ops, e_ops, **kwargs)[source]

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

Parameters
Hqutip.Qobj

System Hamiltonian.

rho0qutip.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.

Returns
output: qutip.solver.Result

An instance of the class qutip.solver.Result.

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
Hqutip.Qobj

System Hamiltonian.

psi0qutip.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.

Returns
output: qutip.solver.Result

An instance of the class qutip.solver.Result.

Correlation Functions

correlation(H, state0, tlist, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args={}, options=<qutip.solver.Options object at 0x2b22624eab00>)[source]

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

tlistarray_like

list of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\); here tlist is automatically set, ignoring user input.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

reversebool

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

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_matarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_ss(H, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args={}, options=<qutip.solver.Options object at 0x2b22624eaac8>)[source]

Calculate the two-operator two-time correlation function:

\[\lim_{t \to \infty} \left<A(t+\tau)B(t)\right>\]

along one time axis (given steady-state initial conditions) using the quantum regression theorem and the evolution solver indicated by the solver parameter.

Parameters
HQobj

system Hamiltonian.

taulistarray_like

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

c_opslist

list of collapse operators.

a_opQobj

operator A.

b_opQobj

operator B.

reversebool

If True, calculate \(\lim_{t \to \infty} \left<A(t)B(t+\tau)\right>\) instead of \(\lim_{t \to \infty} \left<A(t+\tau)B(t)\right>\).

solverstr

choice of solver (me for master-equation and es for exponential series).

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_vecarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_2op_1t(H, state0, taulist, c_ops, a_op, b_op, solver='me', reverse=False, args={}, options=<qutip.solver.Options object at 0x2b22624ea978>)[source]

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

reversebool {False, True}

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

solverstr {‘me’, ‘mc’, ‘es’}

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

optionsOptions

Solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_vecndarray

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

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=<qutip.solver.Options object at 0x2b22624ea9b0>)[source]

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

state0Qobj

Initial state density matrix \(\rho_0\) or state vector \(\psi_0\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

tlistarray_like

list of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\); here tlist is automatically set, ignoring user input.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

reversebool {False, True}

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

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_matndarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_3op_1t(H, state0, taulist, c_ops, a_op, b_op, c_op, solver='me', args={}, options=<qutip.solver.Options object at 0x2b22624ea9e8>)[source]

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

rho0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

c_opQobj

operator C.

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_vecarray

An array of correlation values for the times specified by taulist

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=<qutip.solver.Options object at 0x2b22624eaa20>)[source]

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

rho0Qobj

Initial state density matrix \(\rho_0\) or state vector \(\psi_0\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

tlistarray_like

list of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\); here tlist is automatically set, ignoring user input.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

c_opQobj

operator C.

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_matarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

correlation_4op_1t(H, state0, taulist, c_ops, a_op, b_op, c_op, d_op, solver='me', args={}, options=<qutip.solver.Options object at 0x2b22624eab38>)[source]

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

rho0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

c_opQobj

operator C.

d_opQobj

operator D.

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_vecarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

Note

Deprecated in QuTiP 3.1 Use correlation_3op_1t() instead.

correlation_4op_2t(H, state0, tlist, taulist, c_ops, a_op, b_op, c_op, d_op, solver='me', args={}, options=<qutip.solver.Options object at 0x2b22624eab70>)[source]

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

rho0Qobj

Initial state density matrix \(\rho_0\) or state vector \(\psi_0\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

tlistarray_like

list of times for \(t\). tlist must be positive and contain the element 0. When taking steady-steady correlations only one tlist value is necessary, i.e. when \(t \rightarrow \infty\); here tlist is automatically set, ignoring user input.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

b_opQobj

operator B.

c_opQobj

operator C.

d_opQobj

operator D.

solverstr

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

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
corr_matarray

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

References

See, Gardiner, Quantum Noise, Section 5.2.

spectrum(H, wlist, c_ops, a_op, b_op, solver='es', use_pinv=False)[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
Hqutip.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 psuedo-inverse).

use_pinvbool

For use with the pi solver: if True use numpy’s pinv method, otherwise use a generic solver.

Returns
spectrumarray

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

spectrum_ss(H, wlist, c_ops, a_op, b_op)[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 an eseries based solver Note: this spectrum is only defined for stationary statistics (uses steady state rho0).

Parameters
Hqutip.qobj

system Hamiltonian.

wlistarray_like

list of frequencies for \(\omega\).

c_opslist of qutip.qobj

list of collapse operators.

a_opqutip.qobj

operator A.

b_opqutip.qobj

operator B.

use_pinvbool

If True use numpy’s pinv method, otherwise use a generic solver.

Returns
spectrumarray

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

spectrum_pi(H, wlist, c_ops, a_op, b_op, use_pinv=False)[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 a psuedo-inverse method. Note: this spectrum is only defined for stationary statistics (uses steady state rho0)

Parameters
Hqutip.qobj

system Hamiltonian.

wlistarray_like

list of frequencies for \(\omega\).

c_opslist of qutip.qobj

list of collapse operators.

a_opqutip.qobj

operator A.

b_opqutip.qobj

operator B.

use_pinvbool

If True use numpy’s pinv method, otherwise use a generic solver.

Returns
spectrumarray

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

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

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

Parameters
tlistarray_like

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

yarray_like

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

inverse: 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 two-sided power spectrum ‘S(w)’.

coherence_function_g1(H, state0, taulist, c_ops, a_op, solver='me', args={}, options=<qutip.solver.Options object at 0x2b22624eaa58>)[source]

Calculate the normalized first-order quantum coherence function:

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

solverstr

choice of solver (me for master-equation and es for exponential series).

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
g1, G1tuple

The normalized and unnormalized second-order coherence function.

coherence_function_g2(H, state0, taulist, c_ops, a_op, solver='me', args={}, options=<qutip.solver.Options object at 0x2b22624eaa90>)[source]

Calculate the normalized second-order quantum coherence function:

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

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

Parameters
HQobj

system Hamiltonian, may be time-dependent for solver choice of me or mc.

state0Qobj

Initial state density matrix \(\rho(t_0)\) or state vector \(\psi(t_0)\). If ‘state0’ is ‘None’, then the steady state will be used as the initial state. The ‘steady-state’ is only implemented for the me and es solvers.

taulistarray_like

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

c_opslist

list of collapse operators, may be time-dependent for solver choice of me or mc.

a_opQobj

operator A.

argsdict

Dictionary of arguments to be passed to solver.

solverstr

choice of solver (me for master-equation and es for exponential series).

optionsOptions

solver options class. ntraj is taken as a two-element list because the mc correlator calls mcsolve() recursively; by default, ntraj=[20, 100]. mc_corr_eps prevents divide-by-zero errors in the mc correlator; by default, mc_corr_eps=1e-10.

Returns
g2, G2tuple

The normalized and unnormalized second-order coherence function.

Steady-state Solvers

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

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

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

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

Parameters
Aqobj

A Hamiltonian or Liouvillian operator.

c_op_listlist

A list of collapse operators.

solverstr {None, ‘scipy’, ‘mkl’}

Selects the sparse solver to use. Default is auto-select based on the availability of the MKL library.

methodstr {‘direct’, ‘eigen’, ‘iterative-gmres’,

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

Method for solving the underlying linear equation. Direct LU solver ‘direct’ (default), sparse eigenvalue problem ‘eigen’, iterative GMRES method ‘iterative-gmres’, iterative LGMRES method ‘iterative-lgmres’, iterative BICGSTAB method ‘iterative-bicgstab’, SVD ‘svd’ (dense), or inverse-power method ‘power’. The iterative power methods ‘power-gmres’, ‘power-lgmres’, ‘power-bicgstab’ use the same solvers as their direct counterparts.

return_infobool, optional, default = False

Return a dictionary of solver-specific infomation about the solution and how it was obtained.

sparsebool, optional, default = True

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

use_rcmbool, optional, default = False

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

use_wbmbool, optional, default = False

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

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.

max_iter_refineint {10}

MKL ONLY. Max. number of iterative refinements to perform.

scaling_vectorsbool {True, False}

MKL ONLY. Scale matrix to unit norm columns and rows.

weighted_matchingbool {True, False}

MKL ONLY. Use weighted matching to better condition diagonal.

x0ndarray, optional

ITERATIVE ONLY. Initial guess for solution vector.

maxiterint, optional, default=1000

ITERATIVE ONLY. Maximum number of iterations to perform.

tolfloat, optional, default=1e-12

ITERATIVE ONLY. Tolerance used for terminating solver.

mtolfloat, optional, default=None

ITERATIVE ‘power’ methods ONLY. Tolerance for lu solve method. If None given then max(0.1*tol, 1e-15) is used

matolfloat, optional, default=1e-15

ITERATIVE ONLY. Absolute tolerance for lu solve method.

permc_specstr, optional, default=’COLAMD’

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

use_precondbool optional, default = False

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

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

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

fill_factorfloat, optional, default = 100

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

drop_tolfloat, optional, default = 1e-4

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

diag_pivot_threshfloat, optional, default = None

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

ILU_MILUstr, optional, default = ‘smilu_2’

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

Returns
dmqobj

Steady state density matrix.

infodict, optional

Dictionary containing solver-specific information about the solution.

Notes

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

build_preconditioner(A, c_op_list=[], **kwargs)[source]

Constructs a iLU preconditioner necessary for solving for the steady state density matrix using the iterative linear solvers in the ‘steadystate’ function.

Parameters
Aqobj

A Hamiltonian or Liouvillian operator.

c_op_listlist

A list of collapse operators.

return_infobool, optional, default = False

Return a dictionary of solver-specific infomation about the solution and how it was obtained.

use_rcmbool, optional, default = False

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

use_wbmbool, optional, default = False

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

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.

methodstr, default = ‘iterative’

Tells the preconditioner what type of Liouvillian to build for iLU factorization. For direct iterative methods use ‘iterative’. For power iterative methods use ‘power’.

permc_specstr, optional, default=’COLAMD’

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

fill_factorfloat, optional, default = 100

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

drop_tolfloat, optional, default = 1e-4

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

diag_pivot_threshfloat, optional, default = None

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

ILU_MILUstr, optional, default = ‘smilu_2’

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

Returns
luobject

Returns a SuperLU object representing iLU preconditioner.

infodict, optional

Dictionary containing solver-specific information.

Propagators

propagator(H, t, c_op_list=[], args={}, options=None, unitary_mode='batch', parallel=False, progress_bar=None, _safe_mode=True, **kwargs)[source]

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

Parameters
Hqobj or list

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

tfloat or array-like

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

c_op_listlist

List of qobj collapse operators.

argslist/array/dictionary

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

optionsqutip.Options

with options for the ODE solver.

unitary_mode = str (‘batch’, ‘single’)

Solve all basis vectors simulaneously (‘batch’) or individually (‘single’).

parallelbool {False, True}

Run the propagator in parallel mode. This will override the unitary_mode settings if set to True.

progress_bar: BaseProgressBar

Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation. By default no progress bar is used, and if set to True a TextProgressBar will be used.

Returns
aqobj

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

propagator_steadystate(U)[source]

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

Parameters
Uqobj

Operator representing the propagator.

Returns
aqobj

Instance representing the steady-state density matrix.

Time-dependent problems

rhs_generate(H, c_ops, args={}, options=<qutip.solver.Options object at 0x2b225f631c18>, name=None, cleanup=True)[source]

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

Parameters
Hqobj

System Hamiltonian.

c_opslist

list of collapse operators.

argsdict

Arguments for time-dependent Hamiltonian and collapse operator terms.

optionsOptions

Instance of ODE solver options.

name: str

Name of generated RHS

cleanup: bool

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

Notes

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

rhs_clear()[source]

Resets the string-format time-dependent Hamiltonian parameters.

Returns
Nothing, just clears data from internal config module.

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).

temporal_basis_vector(waveguide_emission_indices, n_time_bins)[source]

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

Parameters
waveguide_emission_indiceslist or tuple

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

n_time_binsint

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

Returns
temporal_basis_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 n-photon state projected onto the temporal basis.

Parameters
H:class: qutip.Qobj or list

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

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).

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

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

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.

Permutational Invariance

Permutational Invariant Quantum Solver (PIQS)

This module calculates the Liouvillian for the dynamics of ensembles of identical two-level systems (TLS) in the presence of local and collective processes by exploiting permutational symmetry and using the Dicke basis.

jspin(N, op=None, basis='dicke')[source]

Calculate the list of collective operators of the total algebra.

The Dicke basis \(|j,m\rangle\langle j,m'|\) is used by default. Otherwise with “uncoupled” the operators are in a \(2^N\) space.

Parameters
N: int

Number of two-level systems.

op: str

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.

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 \(|j, m\rangle = |1, 0\rangle\) for N = 2, and the state is represented as a density matrix of size (nds, nds) or (4, 4), with the (1, 1) element set to 1.

Parameters
N: int

The number of two-level systems.

j: float

The eigenvalue j of the Dicke state (j, m).

m: float

The eigenvalue m of the Dicke state (j, m).

Returns
rho: :class: qutip.Qobj

The density matrix.

superradiant(N, basis='dicke')[source]

Generate the density matrix of the superradiant state.

This state is given by (N/2, 0) or (N/2, 0.5) in the Dicke basis. If the argument basis is “uncoupled” then it generates the state in a 2**N dim Hilbert space.

Parameters
N: int

The number of two-level systems.

basis: str

The basis to use. Either “dicke” or “uncoupled”.

Returns
state: :class: qutip.Qobj

The superradiant state density matrix in the requested basis.

ghz(N, basis='dicke')[source]

Generate the density matrix of the GHZ state.

If the argument basis is “uncoupled” then it generates the state in a \(2^N\)-dimensional Hilbert space.

Parameters
N: int

The number of two-level systems.

basis: str

The basis to use. Either “dicke” or “uncoupled”.

Returns
state: :class: qutip.Qobj

The GHZ state density matrix in the requested basis.

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, \(|CSS \rangle = \prod_i^N(a|1\rangle_i + b|0\rangle_i)\) with \(a = sin(\frac{\theta}{2})\), \(b = e^{i \phi}\cos(\frac{\theta}{2})\). The default basis is that of Dicke space \(|j, m\rangle \langle j, m'|\). The default state is the symmetric CSS, \(|CSS\rangle = |+\rangle\).

Parameters
N: int

The number of two-level 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.

excited(N, basis='dicke')[source]

Generate the density matrix for the excited state.

This state is given by (N/2, N/2) in the default Dicke basis. If the argument basis is “uncoupled” then it generates the state in a 2**N dim Hilbert space.

Parameters
N: int

The number of two-level systems.

basis: str

The basis to use. Either “dicke” or “uncoupled”.

Returns
state: :class: qutip.Qobj

The excited state density matrix in the requested basis.

ground(N, basis='dicke')[source]

Generate the density matrix of the ground state.

This state is given by (N/2, -N/2) in the Dicke basis. If the argument basis is “uncoupled” then it generates the state in a \(2^N\)-dimensional Hilbert space.

Parameters
N: int

The number of two-level systems.

basis: str

The basis to use. Either “dicke” or “uncoupled”

Returns
state: :class: qutip.Qobj

The ground state density matrix in the requested basis.

num_dicke_states(N)[source]

Calculate the number of Dicke states.

Parameters
N: int

The number of two-level systems.

Returns
nds: int

The number of Dicke states.

num_dicke_ladders(N)[source]

Calculate the total number of ladders in the Dicke space.

For a collection of N two-level systems it counts how many different “j” exist or the number of blocks in the block-diagonal matrix.

Parameters
N: int

The number of two-level systems.

Returns
Nj: int

The number of Dicke ladders.

num_tls(nds)[source]

Calculate the number of two-level systems.

Parameters
nds: int

The number of Dicke states.

Returns
N: int

The number of two-level systems.

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.

state_degeneracy(N, j)[source]

Calculate the degeneracy of the Dicke state.

Each state \(|j, m\rangle\) includes D(N,j) irreducible representations \(|j, m, \alpha\rangle\).

Uses Decimals to calculate higher numerator and denominators numbers.

Parameters
N: int

The number of two-level systems.

j: float

Total spin eigenvalue (cooperativity).

Returns
degeneracy: int

The state degeneracy.

m_degeneracy(N, m)[source]

Calculate the number of Dicke states \(|j, m\rangle\) with same energy.

Parameters
N: int

The number of two-level systems.

m: float

Total spin z-axis projection eigenvalue (proportional to the total energy).

Returns
degeneracy: int

The m-degeneracy.

ap(j, m)[source]

Calculate the coefficient ap by applying J_+ |j, m>.

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

Parameters
j, m: float

The value for j and m in the dicke basis |j,m>.

Returns
a_plus: float

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

am(j, m)[source]

Calculate the operator am used later.

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

Parameters
j: float

The value for j.

m: float

The value for m.

Returns
a_minus: float

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

spin_algebra(N, op=None)[source]

Create the list [sx, sy, sz] with the spin operators.

The operators are constructed for a collection of N two-level systems (TLSs). Each element of the list, i.e., sx, is a vector of qutip.Qobj objects (spin matrices), as it cointains the list of the SU(2) Pauli matrices for the N TLSs. Each TLS operator sx[i], with i = 0, …, (N-1), is placed in a \(2^N\)-dimensional Hilbert space.

Parameters
N: int

The number of two-level systems.

Returns
spin_operators: list or :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.

collapse_uncoupled(N, emission=0.0, dephasing=0.0, pumping=0.0, collective_emission=0.0, collective_dephasing=0.0, collective_pumping=0.0)[source]

Create the collapse operators (c_ops) of the Lindbladian in the uncoupled basis

These operators are in the uncoupled basis of the two-level system (TLS) SU(2) Pauli matrices.

Parameters
N: int

The number of two-level systems.

emission: float

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).

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 \(|j, m\rangle \langle j, m^{\prime}|\). 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 |j, m> values is given by the cythonized function jmm1_dictionary. A density matrix is created from the given dictionary of coefficients for each (j, m, m1).

Parameters
N: int

The number of two-level systems.

jmm1: dict

A dictionary of {(j, m, m1): p} that gives a density p for the (j, m, m1) matrix element.

Returns
rho: :class: qutip.Qobj

The density matrix in the Dicke basis.

Visualization

Pseudoprobability Functions

qfunc(state, xvec, yvec, g=1.4142135623730951)[source]

Q-function of a given state vector or density matrix at points xvec + i * yvec.

Parameters
stateqobj

A state vector or density matrix.

xvecarray_like

x-coordinates at which to calculate the Wigner function.

yvecarray_like

y-coordinates at which to calculate the Wigner function.

gfloat

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

Returns
Qarray

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

spin_q_function(rho, theta, phi)[source]

Husimi Q-function for spins.

Parameters
stateqobj

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

thetaarray_like

theta-coordinates at which to calculate the Q function.

phiarray_like

phi-coordinates at which to calculate the Q function.

Returns
Q, THETA, PHI2d-array

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

spin_wigner(rho, theta, phi)[source]

Wigner function for spins on the Bloch sphere.

Parameters
stateqobj

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

thetaarray_like

theta-coordinates at which to calculate the Q function.

phiarray_like

phi-coordinates at which to calculate the Q function.

Returns
W, THETA, PHI2d-array

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

Notes

Experimental.

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

x-coordinates at which to calculate the Wigner function.

yvecarray_like

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

gfloat

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

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 y-coordinate values calculated via the Fourier transform.

Notes

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

References

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

Graphs and Visualization

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

hinton(rho, xlabels=None, ylabels=None, title=None, ax=None, cmap=None, label_top=True)[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, x-axis labels will be placed on top, otherwise they will appear below the plot.

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.

matrix_histogram(M, xlabels=None, ylabels=None, title=None, limits=None, colorbar=True, fig=None, ax=None)[source]

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

Parameters
MMatrix of Qobj

The matrix to visualize

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 z-axis limits [min, max] (optional)

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.

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 z-axis limits [min, max] (optional)

phase_limitslist/array with two float numbers

The phase-axis (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_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
rhoqutip.qobj.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).

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
rhoqutip.qobj.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’).

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
rhoqutip.qobj.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’).

Returns
fig, axtuple

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

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 z-axis

phifloat

Angle in x-y 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.

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

More information:

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

Parameters
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.

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 y-axis 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).

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.

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.

Parameters
thetalist/array

Polar angles

philist/array

Azimuthal angles

argslist/array

list of ket vectors.

Returns
array for angular wave function

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

Quantum Information Processing

Gates

rx(phi, N=None, target=0)[source]

Single-qubit rotation for operator sigmax with angle phi.

Returns
resultqobj

Quantum object for operator describing the rotation.

ry(phi, N=None, target=0)[source]

Single-qubit rotation for operator sigmay with angle phi.

Returns
resultqobj

Quantum object for operator describing the rotation.

rz(phi, N=None, target=0)[source]

Single-qubit rotation for operator sigmaz with angle phi.

Returns
resultqobj

Quantum object for operator describing the rotation.

sqrtnot(N=None, target=0)[source]

Single-qubit square root NOT gate.

Returns
resultqobj

Quantum object for operator describing the square root NOT gate.

snot(N=None, target=0)[source]

Quantum object representing the SNOT (Hadamard) gate.

Returns
snot_gateqobj

Quantum object representation of SNOT gate.

Examples

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

Returns quantum object representing the phase shift gate.

Parameters
thetafloat

Phase rotation angle.

Returns
phase_gateqobj

Quantum object representation of phase shift gate.

Examples

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

Returns quantum object representing the controlled phase shift gate.

Parameters
thetafloat

Phase rotation angle.

Ninteger

The number of qubits in the target space.

controlinteger

The index of the control qubit.

targetinteger

The index of the target qubit.

Returns
Uqobj

Quantum object representation of controlled phase gate.

cnot(N=None, control=0, target=1)[source]

Quantum object representing the CNOT gate.

Returns
cnot_gateqobj

Quantum object representation of CNOT gate

Examples

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

Quantum object representing the CSIGN gate.

Returns
csign_gateqobj

Quantum object representation of CSIGN gate

Examples

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

Quantum object representing the Berkeley gate.

Returns
berkeley_gateqobj

Quantum object representation of Berkeley gate

Examples

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

Quantum object representing the SWAPalpha gate.

Returns
swapalpha_gateqobj

Quantum object representation of SWAPalpha gate

Examples

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

Quantum object representing the SWAP gate.

Returns
swap_gateqobj

Quantum object representation of SWAP gate

Examples

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

Quantum object representing the iSWAP gate.

Returns
iswap_gateqobj

Quantum object representation of iSWAP gate

Examples

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

Quantum object representing the square root SWAP gate.

Returns
sqrtswap_gateqobj

Quantum object representation of square root SWAP gate

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

Quantum object representing the square root iSWAP gate.

Returns
sqrtiswap_gateqobj

Quantum object representation of square root iSWAP gate

Examples

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

Quantum object representing the Fredkin gate.

Returns
fredkin_gateqobj

Quantum object representation of Fredkin gate.

Examples

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

Quantum object representing the Toffoli gate.

Returns
toff_gateqobj

Quantum object representation of Toffoli gate.

Examples

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

Single-qubit rotation for operator op with angle phi.

Returns
resultqobj

Quantum object for operator describing the rotation.

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

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

Parameters
UQobj

Arbitrary single-qubit gate.

Ninteger

The number of qubits in the target space.

controlinteger

The index of the first control qubit.

targetinteger

The index of the target qubit.

control_valueinteger (1)

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

Returns
resultqobj

Quantum object representing the controlled-U gate.

globalphase(theta, N=1)[source]

Returns quantum object representing the global phase shift gate.

Parameters
thetafloat

Phase rotation angle.

Returns
phase_gateqobj

Quantum object representation of global phase shift gate.

Examples

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

Quantum object representing the N-qubit Hadamard gate.

Returns
qqobj

Quantum object representation of the N-qubit Hadamard gate.

gate_sequence_product(U_list, left_to_right=True)[source]

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

Parameters
U_listlist

List of gates implementing the quantum circuit.

left_to_rightBoolean

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

Returns
U_overallqobj

Overall unitary matrix of a given quantum circuit.

gate_expand_1toN(U, N, target)[source]

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

Parameters
UQobj

The one-qubit gate

Ninteger

The number of qubits in the target space.

targetinteger

The index of the target qubit.

Returns
gateqobj

Quantum object representation of N-qubit gate.

gate_expand_2toN(U, N, control=None, target=None, targets=None)[source]

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

Parameters
UQobj

The two-qubit gate

Ninteger

The number of qubits in the target space.

controlinteger

The index of the control qubit.

targetinteger

The index of the target qubit.

targetslist

List of target qubits.

Returns
gateqobj

Quantum object representation of N-qubit gate.

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

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

Parameters
UQobj

The three-qubit gate

Ninteger

The number of qubits in the target space.

controlslist

The list of the control qubits.

targetinteger

The index of the target qubit.

Returns
gateqobj

Quantum object representation of N-qubit gate.

Qubits

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

Function to define initial state of the qubits.

Parameters
NInteger

Number of qubits in the register.

statesList

Initial state of each qubit.

Returns
qstatesQobj

List of qubits.

Algorithms

This module provides the circuit implementation for Quantum Fourier Transform.

qft(N=1)[source]

Quantum Fourier Transform operator on N qubits.

Parameters
Nint

Number of qubits.

Returns
QFT: qobj

Quantum Fourier transform operator.

qft_steps(N=1, swapping=True)[source]

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

Parameters
N: int

Number of qubits.

swap: boolean

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

Returns
U_step_list: list of qobj

List of Hadamard and controlled rotation gates implementing QFT.

qft_gate_sequence(N=1, swapping=True)[source]

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

Parameters
N: int

Number of qubits.

swap: boolean

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

Returns
qc: instance of QubitCircuit

Gate sequence of Hadamard and controlled rotation gates implementing QFT.

Non-Markovian Solvers

This module contains an implementation of the non-Markovian transfer tensor method (TTM), introduced in [1].

[1] Javier Cerrillo and Jianshu Cao, Phys. Rev. Lett 112, 110401 (2014)

ttmsolve(dynmaps, rho0, times, e_ops=[], learningtimes=None, tensors=None, **kwargs)[source]

Solve time-evolution 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.

rho0qutip.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.ttm.TTMSolverOptions.

Returns
output: qutip.solver.Result

An instance of the class qutip.solver.Result.

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 Nelder-Mead method for fidelity error minimisation.

References

  1. 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).

  2. Shai Machnes et.al DYNAMO - Dynamic Framework for Quantum Optimal Control arXiv.1011.4874

  3. Doria, P., Calarco, T. & Montangero, S. Optimal Control Technique for Many-Body Quantum Dynamics. Phys. Rev. Lett. 106, 1–4 (2011).

  4. Caneva, T., Calarco, T. & Montangero, S. Chopped random-basis quantum optimization. Phys. Rev. A - At. Mol. Opt. Phys. 84, (2011).

optimize_pulse(drift, ctrls, initial, target, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e-10, min_grad=1e-10, 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 intital (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 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 and evo_time are dervived from it None implies that timeslot durations will be equal and calculated as evo_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 FMIN

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

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=1e-10, min_grad=1e-10, 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 intital (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 is 1 - 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 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 and evo_time are dervived from it None implies that timeslot durations will be equal and calculated as evo_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 FMIN

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

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

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

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

create_pulse_optimizer(drift, ctrls, initial, target, num_tslots=None, evo_time=None, tau=None, amp_lbound=None, amp_ubound=None, fid_err_targ=1e-10, min_grad=1e-10, 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 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 and evo_time are dervived from it None implies that timeslot durations will be equal and calculated as evo_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 Nelder-Mead

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=1e-05, 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 and evo_time are dervived from it None implies that timeslot durations will be equal and calculated as evo_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

Multi-variable optimisation method The only tested options are ‘fmin’ and ‘Nelder-mead’ In theory any non-gradient 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 the scipy.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 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

type / shape of pulse(s) used modulate the control amplitudes. Options include:

RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW, GAUSSIAN

Default is None

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

Determines how the guess pulse is applied to the pulse generated by the basis expansion. Options are: MODULATE, ADD Default is MODULATE

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=1e-05, 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 and evo_time are dervived from it None implies that timeslot durations will be equal and calculated as evo_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

Multi-variable optimisation method The only tested options are ‘fmin’ and ‘Nelder-mead’ In theory any non-gradient 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 the scipy.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

type / shape of pulse(s) used modulate the control amplitudes. Options include:

RND, LIN, ZERO, SINE, SQUARE, TRIANGLE, SAW, GAUSSIAN

Default is None

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

Determines how the guess pulse is applied to the pulse generated by the basis expansion. Options are: MODULATE, ADD Default is MODULATE

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

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 non-periodic 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

Graph Theory Routines

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

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

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

Parameters
Acsc_matrix, csr_matrix

Input graph in CSC or CSR matrix format

startint

Staring node for BFS traversal.

Returns
orderarray

Order in which nodes are traversed from starting node.

levelsarray

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

graph_degree(A)[source]

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

Parameters
Aqobj, csr_matrix, csc_matrix

Input quantum object or csr_matrix.

Returns
degreearray

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

reverse_cuthill_mckee(A, sym=False)[source]

Returns the permutation array that orders a sparse CSR or CSC matrix in Reverse-Cuthill McKee ordering. Since the input matrix must be symmetric, this routine works on the matrix A+Trans(A) if the sym flag is set to False (Default).

It is assumed by default (sym=False) that the input matrix is not symmetric. This is because it is faster to do A+Trans(A) than it is to check for symmetry for a generic matrix. If you are guaranteed that the matrix is symmetric in structure (values of matrix element do not matter) then set sym=True

Parameters
Acsc_matrix, csr_matrix

Input sparse CSC or CSR sparse matrix format.

symbool {False, True}

Flag to set whether input matrix is symmetric.

Returns
permarray

Array of permuted row and column indices.

Notes

This routine is used primarily for internal reordering of Lindblad superoperators for use in iterative solver routines.

References

E. Cuthill and J. McKee, “Reducing the Bandwidth of Sparse Symmetric Matrices”, ACM ‘69 Proceedings of the 1969 24th national conference, (1969).

maximum_bipartite_matching(A, perm_type='row')[source]

Returns an array of row or column permutations that removes nonzero elements from the diagonal of a nonsingular square CSC sparse matrix. Such a permutation is always possible provided that the matrix is nonsingular. This function looks at the structure of the matrix only.

The input matrix will be converted to CSC matrix format if necessary.

Parameters
Asparse matrix

Input matrix

perm_typestr {‘row’, ‘column’}

Type of permutation to generate.

Returns
permarray

Array of row or column permutations.

Notes

This function relies on a maximum cardinality bipartite matching algorithm based on a breadth-first search (BFS) of the underlying graph[1]_.

References

I. S. Duff, K. Kaya, and B. Ucar, “Design, Implementation, and Analysis of Maximum Transversal Algorithms”, ACM Trans. Math. Softw. 38, no. 2, (2011).

weighted_bipartite_matching(A, perm_type='row')[source]

Returns an array of row permutations that attempts to maximize the product of the ABS values of the diagonal elements in a nonsingular square CSC sparse matrix. Such a permutation is always possible provided that the matrix is nonsingular.

This function looks at both the structure and ABS values of the underlying matrix.

Parameters
Acsc_matrix

Input matrix

perm_typestr {‘row’, ‘column’}

Type of permutation to generate.

Returns
permarray

Array of row or column permutations.

Notes

This function uses a weighted maximum cardinality bipartite matching algorithm based on breadth-first search (BFS). The columns are weighted according to the element of max ABS value in the associated rows and are traversed in descending order by weight. When performing the BFS traversal, the row associated to a given column is the one with maximum weight. Unlike other techniques[1]_, this algorithm does not guarantee the product of the diagonal is maximized. However, this limitation is offset by the substantially faster runtime of this method.

References

I. S. Duff and J. Koster, “The design and use of algorithms for permuting large entries to the diagonal of sparse matrices”, SIAM J. Matrix Anal. and Applics. 20, no. 4, 889 (1997).

Utility Functions

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

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.

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

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

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

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

Parameters
startint

The starting value of the sequence.

stopint

The stoping values of the sequence.

numint, optional

Number of samples to generate.

elemslist/ndarray, optional

Requested elements to include in array

Returns
samplesndadrray

Original equally spaced sample array with additional elements added.

clebsch(j1, j2, j3, m1, m2, m3)[source]

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

Parameters
j1float

Total angular momentum 1.

j2float

Total angular momentum 2.

j3float

Total angular momentum 3.

m1float

z-component of angular momentum 1.

m2float

z-component of angular momentum 2.

m3float

z-component of angular momentum 3.

Returns
cg_coefffloat

Requested Clebsch-Gordan coefficient.

convert_unit(value, orig='meV', to='GHz')[source]

Convert an energy from unit orig to unit to.

Parameters
valuefloat / array

The energy in the old unit.

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.

File I/O Functions

file_data_read(filename, sep=None)[source]

Retrieves an array of data from the requested file.

Parameters
filenamestr

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

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

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

qload(name)[source]

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

Parameters
namestr

Name of data file to be loaded.

Returns
qobjectinstance / array_like

Object retrieved from requested file.

qsave(data, name='qutip_data')[source]

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

Parameters
datainstance/array_like

Input Python object to be stored.

filenamestr

Name of output data file.

Parallelization

This function provides functions for parallel execution of loops and function mappings, using the builtin Python module multiprocessing.

parfor(func, *args, **kwargs)[source]

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

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

Note

From QuTiP 3.1, we recommend to use qutip.parallel_map instead of this function.

Parameters
funcfunction_type

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

The following keyword argument is reserved:
num_cpusint

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

Returns
resultlist

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

parallel_map(task, values, task_args=(), task_kwargs={}, **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.

progress_barProgressBar

Progress bar class instance for showing progress.

Returns
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values.

serial_map(task, values, task_args=(), task_kwargs={}, **kwargs)[source]

Serial mapping function with the same call signature as parallel_map, for easy switching between serial and parallel execution. This is functionally equivalent to:

result = [task(value, *task_args, **task_kwargs) for value in values]

This function work as a drop-in replacement of 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.

progress_barProgressBar

Progress bar class instance for showing progress.

Returns
resultlist

The result list contains the value of task(value, *task_args, **task_kwargs) for each value in values.

IPython Notebook Tools

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

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

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

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

Parameters
task: a Python function

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

task_vec: array / list

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

args: list / dictionary

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

client: IPython.parallel.Client

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

view: a IPython.parallel.Client view

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

show_scheduling: bool {False, True}, default False

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

show_progressbar: bool {False, True}, default False

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

Returns
resultlist

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

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 in values using a cluster of IPython engines. The function task should have the signature task(value, *args, **kwargs).

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

Parameters
task: a Python function

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

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 load-balanced view, which is obtained from the IPython.parallel.Client instance client by calling, view = client.load_balanced_view().

show_scheduling: bool {False, True}, default False

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

show_progressbar: bool {False, True}, default False

Display a HTML-based progress bar 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 in values.

version_table(verbose=False)[source]

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

Returns
version_table: string

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

Miscellaneous

about()[source]

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

simdiag(ops, evals=True)[source]

Simultaneous diagonalization of commuting Hermitian matrices.

Parameters
opslist/array

list or array of qobjs representing commuting Hermitian operators.

Returns
eigstuple

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