Classes

Qobj

class Qobj(arg=None, dims=None, type=None, copy=True, superrep=None, isherm=None, isunitary=None)[source]

A class for representing quantum objects, such as quantum operators and states.

The Qobj class is the QuTiP representation of quantum operators and state vectors. This class also implements math operations +,-,* between Qobj instances (and / by a C-number), as well as a collection of common operator/state operations. The Qobj constructor optionally takes a dimension list and/or shape list as arguments.

Parameters
inpt: array_like

Data for vector/matrix representation of the quantum object.

dims: list

Dimensions of object used for tensor products.

type: {‘bra’, ‘ket’, ‘oper’, ‘operator-ket’, ‘operator-bra’, ‘super’}

The type of quantum object to be represented.

shape: list

Shape of underlying data structure (matrix shape).

copy: bool

Flag specifying whether Qobj should get a copy of the input data, or use the original.

Attributes
dataarray_like

Sparse matrix characterizing the quantum object.

dimslist

List of dimensions keeping track of the tensor structure.

shapelist

Shape of the underlying data array.

typestr

Type of quantum object: ‘bra’, ‘ket’, ‘oper’, ‘operator-ket’, ‘operator-bra’, or ‘super’.

superrepstr

Representation used if type is ‘super’. One of ‘super’ (Liouville form) or ‘choi’ (Choi matrix with tr = dimension).

ishermbool

Indicates if quantum object represents Hermitian operator.

isunitarybool

Indictaes if quantum object represents unitary operator.

iscpbool

Indicates if the quantum object represents a map, and if that map is completely positive (CP).

ishpbool

Indicates if the quantum object represents a map, and if that map is hermicity preserving (HP).

istpbool

Indicates if the quantum object represents a map, and if that map is trace preserving (TP).

iscptpbool

Indicates if the quantum object represents a map that is completely positive and trace preserving (CPTP).

isketbool

Indicates if the quantum object represents a ket.

isbrabool

Indicates if the quantum object represents a bra.

isoperbool

Indicates if the quantum object represents an operator.

issuperbool

Indicates if the quantum object represents a superoperator.

isoperketbool

Indicates if the quantum object represents an operator in column vector form.

isoperbrabool

Indicates if the quantum object represents an operator in row vector form.

Methods

copy()

Create copy of Qobj

conj()

Conjugate of quantum object.

cosm()

Cosine of quantum object.

dag()

Adjoint (dagger) of quantum object.

dnorm()

Diamond norm of quantum operator.

dual_chan()

Dual channel of quantum object representing a CP map.

eigenenergies(sparse=False, sort=’low’, eigvals=0, tol=0, maxiter=100000)

Returns eigenenergies (eigenvalues) of a quantum object.

eigenstates(sparse=False, sort=’low’, eigvals=0, tol=0, maxiter=100000)

Returns eigenenergies and eigenstates of quantum object.

expm()

Matrix exponential of quantum object.

full(order=’C’)

Returns dense array of quantum object data attribute.

groundstate(sparse=False, tol=0, maxiter=100000)

Returns eigenvalue and eigenket for the groundstate of a quantum object.

inv()

Return a Qobj corresponding to the matrix inverse of the operator.

matrix_element(bra, ket)

Returns the matrix element of operator between bra and ket vectors.

norm(norm=’tr’, sparse=False, tol=0, maxiter=100000)

Returns norm of a ket or an operator.

permute(order)

Returns composite qobj with indices reordered.

proj()

Computes the projector for a ket or bra vector.

ptrace(sel)

Returns quantum object for selected dimensions after performing partial trace.

sinm()

Sine of quantum object.

sqrtm()

Matrix square root of quantum object.

tidyup(atol=1e-12)

Removes small elements from quantum object.

tr()

Trace of quantum object.

trans()

Transpose of quantum object.

transform(inpt, inverse=False)

Performs a basis transformation defined by inpt matrix.

trunc_neg(method=’clip’)

Removes negative eigenvalues and returns a new Qobj that is a valid density operator.

unit(norm=’tr’, sparse=False, tol=0, maxiter=100000)

Returns normalized quantum object.

check_herm()[source]

Check if the quantum object is hermitian.

Returns
ishermbool

Returns the new value of isherm property.

conj()[source]

Get the element-wise conjugation of the quantum object.

contract(inplace=False)[source]

Contract subspaces of the tensor structure which are 1D. Not defined on superoperators. If all dimensions are scalar, a Qobj of dimension [[1], [1]] is returned, i.e. _multiple_ scalar dimensions are contracted, but one is left.

Parameters
inplace: bool, optional

If True, modify the dimensions in place. If False, return a copied object.

Returns
out: Qobj

Quantum object with dimensions contracted. Will be self if inplace is True.

copy()[source]

Create identical copy

cosm()[source]

Cosine of a quantum operator.

Operator must be square.

Returns
operqutip.Qobj

Matrix cosine of operator.

Raises
TypeError

Quantum object is not square.

Notes

Uses the Q.expm() method.

dag()[source]

Get the Hermitian adjoint of the quantum object.

diag()[source]

Diagonal elements of quantum object.

Returns
diagsarray

Returns array of real values if operators is Hermitian, otherwise complex values are returned.

dnorm(B=None)[source]

Calculates the diamond norm, or the diamond distance to another operator.

Parameters
Bqutip.Qobj or None

If B is not None, the diamond distance d(A, B) = dnorm(A - B) between this operator and B is returned instead of the diamond norm.

Returns
dfloat

Either the diamond norm of this operator, or the diamond distance from this operator to B.

dual_chan()[source]

Dual channel of quantum object representing a completely positive map.

eigenenergies(sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000)[source]

Eigenenergies of a quantum object.

Eigenenergies (eigenvalues) are defined for operators or superoperators only.

Parameters
sparsebool

Use sparse Eigensolver

sortstr

Sort eigenvalues ‘low’ to high, or ‘high’ to low.

eigvalsint

Number of requested eigenvalues. Default is all eigenvalues.

tolfloat

Tolerance used by sparse Eigensolver (0=machine precision). The sparse solver may not converge if the tolerance is set too low.

maxiterint

Maximum number of iterations performed by sparse solver (if used).

Returns
eigvalsarray

Array of eigenvalues for operator.

Notes

The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it.

eigenstates(sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000, phase_fix=None)[source]

Eigenstates and eigenenergies.

Eigenstates and eigenenergies are defined for operators and superoperators only.

Parameters
sparsebool

Use sparse Eigensolver

sortstr

Sort eigenvalues (and vectors) ‘low’ to high, or ‘high’ to low.

eigvalsint

Number of requested eigenvalues. Default is all eigenvalues.

tolfloat

Tolerance used by sparse Eigensolver (0 = machine precision). The sparse solver may not converge if the tolerance is set too low.

maxiterint

Maximum number of iterations performed by sparse solver (if used).

phase_fixint, None

If not None, set the phase of each kets so that ket[phase_fix,0] is real positive.

Returns
eigvalsarray

Array of eigenvalues for operator.

eigvecsarray

Array of quantum operators representing the oprator eigenkets. Order of eigenkets is determined by order of eigenvalues.

Notes

The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it.

expm(dtype=<class 'qutip.core.data.dense.Dense'>)[source]

Matrix exponential of quantum operator.

Input operator must be square.

Parameters
dtypetype

The data-layer type that should be output. As the matrix exponential is almost dense, this defaults to outputting dense matrices.

Returns
operqutip.Qobj

Exponentiated quantum operator.

Raises
TypeError

Quantum operator is not square.

full(order='C', squeeze=False)[source]

Dense array from quantum object.

Parameters
orderstr {‘C’, ‘F’}

Return array in C (default) or Fortran ordering.

squeezebool {False, True}

Squeeze output array.

Returns
dataarray

Array of complex data from quantum objects data attribute.

groundstate(sparse=False, tol=0, maxiter=100000, safe=True)[source]

Ground state Eigenvalue and Eigenvector.

Defined for quantum operators or superoperators only.

Parameters
sparsebool

Use sparse Eigensolver

tolfloat

Tolerance used by sparse Eigensolver (0 = machine precision). The sparse solver may not converge if the tolerance is set too low.

maxiterint

Maximum number of iterations performed by sparse solver (if used).

safebool (default=True)

Check for degenerate ground state

Returns
eigvalfloat

Eigenvalue for the ground state of quantum operator.

eigvecqutip.Qobj

Eigenket for the ground state of quantum operator.

Notes

The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it.

inv(sparse=False)[source]

Matrix inverse of a quantum operator

Operator must be square.

Returns
operqutip.Qobj

Matrix inverse of operator.

Raises
TypeError

Quantum object is not square.

logm()[source]

Matrix logarithm of quantum operator.

Input operator must be square.

Returns
operqutip.Qobj

Logarithm of the quantum operator.

Raises
TypeError

Quantum operator is not square.

matrix_element(bra, ket)[source]

Calculates a matrix element.

Gives the matrix element for the quantum object sandwiched between a bra and ket vector.

Parameters
braqutip.Qobj

Quantum object of type ‘bra’ or ‘ket’

ketqutip.Qobj

Quantum object of type ‘ket’.

Returns
elemcomplex

Complex valued matrix element.

Notes

It is slightly more computationally efficient to use a ket vector for the ‘bra’ input.

norm(norm=None, kwargs=None)[source]

Norm of a quantum object.

Default norm is L2-norm for kets and trace-norm for operators. Other ket and operator norms may be specified using the norm parameter.

Parameters
normstr

Which type of norm to use. Allowed values for vectors are ‘l2’ and ‘max’. Allowed values for matrices are ‘tr’ for the trace norm, ‘fro’ for the Frobenius norm, ‘one’ and ‘max’.

kwargsdict

Additional keyword arguments to pass on to the relevant norm solver. See details for each norm function in data.norm.

Returns
normfloat

The requested norm of the operator or state quantum object.

overlap(other)[source]

Overlap between two state vectors or two operators.

Gives the overlap (inner product) between the current bra or ket Qobj and and another bra or ket Qobj. It gives the Hilbert-Schmidt overlap when one of the Qobj is an operator/density matrix.

Parameters
otherqutip.Qobj

Quantum object for a state vector of type ‘ket’, ‘bra’ or density matrix.

Returns
overlapcomplex

Complex valued overlap.

Raises
TypeError

Can only calculate overlap between a bra, ket and density matrix quantum objects.

permute(order)[source]

Permute the tensor structure of a quantum object. For example, qutip.tensor(x, y).permute([1, 0]) will give the same result as qutip.tensor(y, x) and qutip.tensor(a, b, c).permute([1, 2, 0]) will be the same as qutip.tensor(b, c, a)

For regular objects (bras, kets and operators) we expect order to be a flat list of integers, which specifies the new order of the tensor product.

For superoperators, we expect order to be something like [[0, 2], [1, 3]] which tells us to permute according to [0, 2, 1, 3], and then group indices according to the length of each sublist. As another example, permuting a superoperator with dimensions of [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]] by an order [[0, 3], [1, 4], [2, 5]] should give a new object with dimensions [[[1, 1], [2, 2], [3, 3]], [[1, 1], [2, 2], [3, 3]]].

Parameters
orderlist

List of indices specifying the new tensor order.

Returns
Pqutip.Qobj

Permuted quantum object.

proj()[source]

Form the projector from a given ket or bra vector.

Parameters
Qqutip.Qobj

Input bra or ket vector

Returns
Pqutip.Qobj

Projection operator.

ptrace(sel, dtype=None)[source]

Take the partial trace of the quantum object leaving the selected subspaces. In other words, trace out all subspaces which are _not_ passed.

This is typically a function which acts on operators; bras and kets will be promoted to density matrices before the operation takes place since the partial trace is inherently undefined on pure states.

For operators which are currently being represented as states in the superoperator formalism (i.e. the object has type operator-ket or operator-bra), the partial trace is applied as if the operator were in the conventional form. This means that for any operator x, operator_to_vector(x).ptrace(0) == operator_to_vector(x.ptrace(0)) and similar for operator-bra.

The story is different for full superoperators. In the formalism that QuTiP uses, if an operator has dimensions (dims) of [[2, 3], [2, 3]] then it can be represented as a state on a Hilbert space of dimensions [2, 3, 2, 3], and a superoperator would be an operator which acts on this joint space. This function performs the partial trace on superoperators by letting the selected components refer to elements of the _joint_ _space_, and then returns a regular operator (of type oper).

Parameters
selint or iterable of int

An int or list of components to keep after partial trace. The selected subspaces will _not_ be reordered, no matter order they are supplied to ptrace.

Returns
operqutip.Qobj

Quantum object representing partial trace with selected components remaining.

purity()[source]

Calculate purity of a quantum object.

Returns
state_purityfloat

Returns the purity of a quantum object. For a pure state, the purity is 1. For a mixed state of dimension d, 1/d<=purity<1.

sinm()[source]

Sine of a quantum operator.

Operator must be square.

Returns
operqutip.Qobj

Matrix sine of operator.

Raises
TypeError

Quantum object is not square.

Notes

Uses the Q.expm() method.

sqrtm(sparse=False, tol=0, maxiter=100000)[source]

Sqrt of a quantum operator. Operator must be square.

Parameters
sparsebool

Use sparse eigenvalue/vector solver.

tolfloat

Tolerance used by sparse solver (0 = machine precision).

maxiterint

Maximum number of iterations used by sparse solver.

Returns
operqutip.Qobj

Matrix square root of operator.

Raises
TypeError

Quantum object is not square.

Notes

The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it.

tidyup(atol=None)[source]

Removes small elements from the quantum object.

Parameters
atolfloat

Absolute tolerance used by tidyup. Default is set via qutip global settings parameters.

Returns
operqutip.Qobj

Quantum object with small elements removed.

to(data_type)[source]

Convert the underlying data store of this Qobj into a different storage representation.

The different storage representations available are the “data-layer types” which are known to qutip.data.to. By default, these are qutip.data.Dense and qutip.data.CSR, which respectively construct a dense matrix store and a compressed sparse row one. Certain algorithms and operations may be faster or more accurate when using a more appropriate data store.

If the data store is already in the format requested, the function returns self. Otherwise, it returns a copy of itself with the data store in the new type.

Parameters
data_typetype

The data-layer type that the data of this Qobj should be converted to.

Returns
Qobj

A new Qobj if a type conversion took place with the data stored in the requested format, or self if not.

tr()[source]

Trace of a quantum object.

Returns
tracefloat

Returns the trace of the quantum object.

trans()[source]

Get the matrix transpose of the quantum operator.

Returns
operQobj

Transpose of input operator.

transform(inpt, inverse=False)[source]

Basis transform defined by input array.

Input array can be a matrix defining the transformation, or a list of kets that defines the new basis.

Parameters
inptarray_like

A matrix or list of kets defining the transformation.

inversebool

Whether to return inverse transformation.

Returns
operqutip.Qobj

Operator in new basis.

Notes

This function is still in development.

trunc_neg(method='clip')[source]

Truncates negative eigenvalues and renormalizes.

Returns a new Qobj by removing the negative eigenvalues of this instance, then renormalizing to obtain a valid density operator.

Parameters
methodstr

Algorithm to use to remove negative eigenvalues. “clip” simply discards negative eigenvalues, then renormalizes. “sgs” uses the SGS algorithm (doi:10/bb76) to find the positive operator that is nearest in the Shatten 2-norm.

Returns
operqutip.Qobj

A valid density operator.

unit(inplace=False, norm=None, kwargs=None)[source]

Operator or state normalized to unity. Uses norm from Qobj.norm().

Parameters
inplacebool

Do an in-place normalization

normstr

Requested norm for states / operators.

kwargsdict

Additional key-word arguments to be passed on to the relevant norm function (see norm for more details).

Returns
objqutip.Qobj

Normalized quantum object. Will be the self object if in place.

QobjEvo

class QobjEvo

A class for representing time-dependent quantum objects, such as quantum operators and states.

Importantly, QobjEvo instances are used to represent such time-dependent quantum objects when working with QuTiP solvers.

A QobjEvo instance may be constructed from one of the following:

  • a callable f(t: double, args: dict) -> Qobj that returns the value of the quantum object at time t.

  • a [Qobj, Coefficient] pair, where Coefficient may also be any item that can be used to construct a coefficient (e.g. a function, a numpy array of coefficient values, a string expression).

  • a Qobj (which creates a constant QobjEvo term).

  • a list of such callables, pairs or Qobjs.

  • a QobjEvo (in which case a copy is created, all other arguments are ignored except args which, if passed, replaces the existing arguments).

Parameters
Q_objectcallable, list or Qobj

A specification of the time-depedent quantum object. See the paragraph above for a full description and the examples section below for examples.

argsdict, optional

A dictionary that contains the arguments for the coefficients. Arguments may be omitted if no function or string coefficients that require arguments are present.

tlistarray-like, optional

A list of times corresponding to the values of the coefficients supplied as numpy arrays. If no coefficients are supplied as numpy arrays, tlist may be omitted, otherwise it is required.

The times in tlist do not need to be equidistant, but must be sorted.

By default, a cubic spline interpolation will be used to interpolate the value of the (numpy array) coefficients at time t. If the coefficients are to be treated as step functions, pass the argument order=0 (see below).

orderint, default=3

Order of the spline interpolation that is to be used to interpolate the value of the (numpy array) coefficients at time t. 0 use previous or left value.

copybool, default=True

Whether to make a copy of the Qobj instances supplied in the Q_object parameter.

compressbool, default=True

Whether to compress the QobjEvo instance terms after the instance has been created.

This sums the constant terms in a single term and combines [Qobj, coefficient] pairs with the same Qobj into a single pair containing the sum of the coefficients.

See compress.

function_style{None, “pythonic”, “dict”, “auto”}

The style of function signature used by callables in Q_object. If style is None, the value of qutip.settings.core["function_coefficient_style"] is used. Otherwise the supplied value overrides the global setting.

Examples

A QobjEvo constructed from a function:

def f(t, args):
    return qutip.qeye(N) * np.exp(args['w'] * t)

QobjEvo(f, args={'w': 1j})

For list based QobjEvo, the list must consist of :obj`~Qobj` or [Qobj, Coefficient] pairs:

QobjEvo([H0, [H1, coeff1], [H2, coeff2]], args=args)

The coefficients may be specified either using a Coefficient object or by a function, string, numpy array or any object that can be passed to the coefficient function. See the documentation of coefficient for a full description.

An example of a coefficient specified by a function:

def f1_t(t, args):
    return np.exp(-1j * t * args["w1"])

QobjEvo([[H1, f1_t]], args={"w1": 1.})

And of coefficients specified by string expressions:

H = QobjEvo(
    [H0, [H1, 'exp(-1j*w1*t)'], [H2, 'cos(w2*t)']],
    args={"w1": 1., "w2": 2.}
)

Coefficients maybe also be expressed as numpy arrays giving a list of the coefficient values:

tlist = np.logspace(-5, 0, 100)
H = QobjEvo(
    [H0, [H1, np.exp(-1j * tlist)], [H2, np.cos(2. * tlist)]],
    tlist=tlist
)

The coeffients array must have the same len as the tlist.

A QobjEvo may also be built using simple arithmetic operations combining Qobj with Coefficient, for example:

coeff = qutip.coefficient("exp(-1j*w1*t)", args={"w1": 1})
qevo = H0 + H1 * coeff
Attributes
dimslist

List of dimensions keeping track of the tensor structure.

shape(int, int)

List of dimensions keeping track of the tensor structure.

typestr

Type of quantum object: ‘bra’, ‘ket’, ‘oper’, ‘operator-ket’, ‘operator-bra’, or ‘super’.

superrepstr

Representation used if type is ‘super’. One of ‘super’ (Liouville form) or ‘choi’ (Choi matrix with tr = dimension).

arguments()

Update the arguments.

Parameters
_argsdict [optional]

New arguments as a dict. Update args with arguments(new_args).

**kwargs :

New arguments as a keywors. Update args with arguments(**new_args).

.. note::

If both the positional _args and keywords are passed new values from both will be used. If a key is present with both, the _args dict value will take priority.

compress()

Look for redundance in the QobjEvo components:

Constant parts, (Qobj without Coefficient) will be summed. Pairs [Qobj, Coefficient] with the same Qobj are merged.

Example: [[sigmax(), f1], [sigmax(), f2]] -> [[sigmax(), f1+f2]]

The QobjEvo is transformed inplace.

Returns
None
conj()

Get the element-wise conjugation of the quantum object.

copy()

Return a copy of this QobjEvo

dag()

Get the Hermitian adjoint of the quantum object.

expect()

Expectation value of this operator at time t with the state.

Parameters
tfloat

Time of the operator to apply.

stateQobj

right matrix of the product

Returns
expectfloat or complex

state.adjoint() @ self @ state if state is a ket. trace(self @ matrix) is state is an operator or operator-ket.

expect_data()

Expectation is defined as state.adjoint() @ self @ state if state is a vector, or state is an operator and self is a superoperator. If state is an operator and self is an operator, then expectation is trace(self @ matrix).

isconstant

Does the system change depending on t

isoper

Indicates if the system represents an operator.

issuper

Indicates if the system represents a superoperator.

linear_map()

Apply mapping to each Qobj contribution.

Example: QobjEvo([sigmax(), coeff]).linear_map(spre) gives the same result has QobjEvo([spre(sigmax()), coeff])

Returns
QobjEvo

Modified object

Notes

Does not modify the coefficients, thus linear_map(conj) would not give the the conjugate of the QobjEvo. It’s only valid for linear transformations.

matmul()

Product of this operator at time t to the state. self(t) @ state

Parameters
tfloat

Time of the operator to apply.

stateQobj

right matrix of the product

Returns
productQobj

The result product as a Qobj

matmul_data()

Compute out += self(t) @ state

num_elements

Number of parts composing the system

tidyup()

Removes small elements from quantum object.

to()

Convert the underlying data store of all component into the desired storage representation.

The different storage representations available are the “data-layer types”. By default, these are qutip.data.Dense and qutip.data.CSR, which respectively construct a dense matrix store and a compressed sparse row one.

The QobjEvo is transformed inplace.

Parameters
data_typetype

The data-layer type that the data of this Qobj should be converted to.

Returns
None
trans()

Transpose of the quantum object

Bloch sphere

class Bloch(fig=None, axes=None, view=None, figsize=None, background=False)[source]

Class for plotting data on the Bloch sphere. Valid data can be either points, vectors, or Qobj objects.

Attributes
axesmatplotlib.axes.Axes

User supplied Matplotlib axes for Bloch sphere animation.

figmatplotlib.figure.Figure

User supplied Matplotlib Figure instance for plotting Bloch sphere.

font_colorstr, default ‘black’

Color of font used for Bloch sphere labels.

font_sizeint, default 20

Size of font used for Bloch sphere labels.

frame_alphafloat, default 0.1

Sets transparency of Bloch sphere frame.

frame_colorstr, default ‘gray’

Color of sphere wireframe.

frame_widthint, default 1

Width of wireframe.

point_colorlist, default [“b”, “r”, “g”, “#CC6600”]

List of colors for Bloch sphere point markers to cycle through, i.e. by default, points 0 and 4 will both be blue (‘b’).

point_markerlist, default [“o”, “s”, “d”, “^”]

List of point marker shapes to cycle through.

point_sizelist, default [25, 32, 35, 45]

List of point marker sizes. Note, not all point markers look the same size when plotted!

sphere_alphafloat, default 0.2

Transparency of Bloch sphere itself.

sphere_colorstr, default ‘#FFDDDD’

Color of Bloch sphere.

figsizelist, default [7, 7]

Figure size of Bloch sphere plot. Best to have both numbers the same; otherwise you will have a Bloch sphere that looks like a football.

vector_colorlist, [“g”, “#CC6600”, “b”, “r”]

List of vector colors to cycle through.

vector_widthint, default 5

Width of displayed vectors.

vector_stylestr, default ‘-|>’

Vector arrowhead style (from matplotlib’s arrow style).

vector_mutationint, default 20

Width of vectors arrowhead.

viewlist, default [-60, 30]

Azimuthal and Elevation viewing angles.

xlabellist, default [“$x$”, “”]

List of strings corresponding to +x and -x axes labels, respectively.

xlposlist, default [1.1, -1.1]

Positions of +x and -x labels respectively.

ylabellist, default [“$y$”, “”]

List of strings corresponding to +y and -y axes labels, respectively.

ylposlist, default [1.2, -1.2]

Positions of +y and -y labels respectively.

zlabellist, default [‘$\left|0\right>$’, ‘$\left|1\right>$’]

List of strings corresponding to +z and -z axes labels, respectively.

zlposlist, default [1.2, -1.2]

Positions of +z and -z labels respectively.

add_annotation(state_or_vector, text, **kwargs)[source]

Add a text or LaTeX annotation to Bloch sphere, parametrized by a qubit state or a vector.

Parameters
state_or_vectorQobj/array/list/tuple

Position for the annotaion. Qobj of a qubit or a vector of 3 elements.

textstr

Annotation text. You can use LaTeX, but remember to use raw string e.g. r”$langle x rangle$” or escape backslashes e.g. “$\langle x \rangle$”.

kwargs :

Options as for mplot3d.axes3d.text, including: fontsize, color, horizontalalignment, verticalalignment.

add_arc(start, end, fmt='b', steps=None, **kwargs)[source]

Adds an arc between two points on a sphere. The arc is set to be blue solid curve by default.

The start and end points must be on the same sphere (i.e. have the same radius) but need not be on the unit sphere.

Parameters
startQobj or array-like

Array with cartesian coordinates of the first point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

endQobj or array-like

Array with cartesian coordinates of the second point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

fmtstr, default: “b”

A matplotlib format string for rendering the arc.

stepsint, default: None

The number of segments to use when rendering the arc. The default uses 100 steps times the distance between the start and end points, with a minimum of 2 steps.

**kwargsdict

Additional parameters to pass to the matplotlib .plot function when rendering this arc.

add_line(start, end, fmt='k', **kwargs)[source]

Adds a line segment connecting two points on the bloch sphere.

The line segment is set to be a black solid line by default.

Parameters
startQobj or array-like

Array with cartesian coordinates of the first point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

endQobj or array-like

Array with cartesian coordinates of the second point, or a state vector or density matrix that can be mapped to a point on or within the Bloch sphere.

fmtstr, default: “k”

A matplotlib format string for rendering the line.

**kwargsdict

Additional parameters to pass to the matplotlib .plot function when rendering this line.

add_points(points, meth='s', colors=None, alpha=1.0)[source]

Add a list of data points to bloch sphere.

Parameters
pointsarray_like

Collection of data points.

meth{‘s’, ‘m’, ‘l’}

Type of points to plot, use ‘m’ for multicolored, ‘l’ for points connected with a line.

colorsarray_like

Optional array with colors for the points. A single color for meth ‘s’, and list of colors for meth ‘m’

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

.. note::

When using meth=l in QuTiP 4.6, the line transparency defaulted to 0.75 and there was no way to alter it. When the alpha parameter was added in QuTiP 4.7, the default became alpha=1.0 for values of meth.

add_states(state, kind='vector', colors=None, alpha=1.0)[source]

Add a state vector Qobj to Bloch sphere.

Parameters
stateQobj

Input state vector.

kind{‘vector’, ‘point’}

Type of object to plot.

colorsarray_like

Optional array with colors for the states.

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

add_vectors(vectors, colors=None, alpha=1.0)[source]

Add a list of vectors to Bloch sphere.

Parameters
vectorsarray_like

Array with vectors of unit length or smaller.

colorsarray_like

Optional array with colors for the vectors.

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

clear()[source]

Resets Bloch sphere data sets to empty.

make_sphere()[source]

Plots Bloch sphere and data sets.

render()[source]

Render the Bloch sphere and its data sets in on given figure and axes.

save(name=None, format='png', dirc=None, dpin=None)[source]

Saves Bloch sphere to file of type format in directory dirc.

Parameters
namestr

Name of saved image. Must include path and format as well. i.e. ‘/Users/Paul/Desktop/bloch.png’ This overrides the ‘format’ and ‘dirc’ arguments.

formatstr

Format of output image.

dircstr

Directory for output images. Defaults to current working directory.

dpinint

Resolution in dots per inch.

Returns
File containing plot of Bloch sphere.
set_label_convention(convention)[source]

Set x, y and z labels according to one of conventions.

Parameters
conventionstring

One of the following:

show()[source]

Display Bloch sphere and corresponding data sets.

Notes

When using inline plotting in Jupyter notebooks, any figure created in a notebook cell is displayed after the cell executes. Thus if you create a figure yourself and use it create a Bloch sphere with b = Bloch(..., fig=fig) and then call b.show() in the same cell, then the figure will be displayed twice. If you do create your own figure, the simplest solution to this is to not call .show() in the cell you create the figure in.

vector_mutation

Sets the width of the vectors arrowhead

vector_style

Style of Bloch vectors, default = ‘-|>’ (or ‘simple’)

vector_width

Width of Bloch vectors, default = 5

class Bloch3d(fig=None)[source]

Class for plotting data on a 3D Bloch sphere using mayavi. Valid data can be either points, vectors, or qobj objects corresponding to state vectors or density matrices. for a two-state system (or subsystem).

Notes

The use of mayavi for 3D rendering of the Bloch sphere comes with a few limitations: I) You can not embed a Bloch3d figure into a matplotlib window. II) The use of LaTex is not supported by the mayavi rendering engine. Therefore all labels must be defined using standard text. Of course you can post-process the generated figures later to add LaTeX using other software if needed.

Attributes
figinstance {None}

User supplied Matplotlib Figure instance for plotting Bloch sphere.

font_colorstr {‘black’}

Color of font used for Bloch sphere labels.

font_scalefloat {0.08}

Scale for font used for Bloch sphere labels.

framebool {True}

Draw frame for Bloch sphere

frame_alphafloat {0.05}

Sets transparency of Bloch sphere frame.

frame_colorstr {‘gray’}

Color of sphere wireframe.

frame_numint {8}

Number of frame elements to draw.

frame_radiusfloats {0.005}

Width of wireframe.

point_colorlist {[‘r’, ‘g’, ‘b’, ‘y’]}

List of colors for Bloch sphere point markers to cycle through. i.e. By default, points 0 and 4 will both be blue (‘r’).

point_modestring {‘sphere’,’cone’,’cube’,’cylinder’,’point’}

Point marker shapes.

point_sizefloat {0.075}

Size of points on Bloch sphere.

sphere_alphafloat {0.1}

Transparency of Bloch sphere itself.

sphere_colorstr {‘#808080’}

Color of Bloch sphere.

sizelist {[500,500]}

Size of Bloch sphere plot in pixels. Best to have both numbers the same otherwise you will have a Bloch sphere that looks like a football.

vector_colorlist {[‘r’, ‘g’, ‘b’, ‘y’]}

List of vector colors to cycle through.

vector_widthint {3}

Width of displayed vectors.

viewlist {[45,65]}

Azimuthal and Elevation viewing angles.

xlabellist {['|x>', '']}

List of strings corresponding to +x and -x axes labels, respectively.

xlposlist {[1.07,-1.07]}

Positions of +x and -x labels respectively.

ylabellist {['|y>', '']}

List of strings corresponding to +y and -y axes labels, respectively.

ylposlist {[1.07,-1.07]}

Positions of +y and -y labels respectively.

zlabellist {['|0>', '|1>']}

List of strings corresponding to +z and -z axes labels, respectively.

zlposlist {[1.07,-1.07]}

Positions of +z and -z labels respectively.

add_points(points, meth='s', alpha=1.0)[source]

Add a list of data points to bloch sphere.

Parameters
pointsarray/list

Collection of data points.

methstr {‘s’,’m’}

Type of points to plot, use ‘m’ for multicolored.

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

add_states(state, kind='vector', alpha=1.0)[source]

Add a state vector Qobj to Bloch sphere.

Parameters
stateqobj

Input state vector.

kindstr {‘vector’,’point’}

Type of object to plot.

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

add_vectors(vectors, alpha=1.0)[source]

Add a list of vectors to Bloch sphere.

Parameters
vectorsarray/list

Array with vectors of unit length or smaller.

alphafloat, default=1.

Transparency value for the vectors. Values between 0 and 1.

clear()[source]

Resets the Bloch sphere data sets to empty.

make_sphere()[source]

Plots Bloch sphere and data sets.

plot_points()[source]

Plots points on the Bloch sphere.

plot_vectors()[source]

Plots vectors on the Bloch sphere.

save(name=None, format='png', dirc=None)[source]

Saves Bloch sphere to file of type format in directory dirc.

Parameters
namestr

Name of saved image. Must include path and format as well. i.e. ‘/Users/Paul/Desktop/bloch.png’ This overrides the ‘format’ and ‘dirc’ arguments.

formatstr

Format of output image. Default is ‘png’.

dircstr

Directory for output images. Defaults to current working directory.

Returns
File containing plot of Bloch sphere.
show()[source]

Display the Bloch sphere and corresponding data sets.

Distributions

class QFunc(xvec, yvec, g: float = 1.4142135623730951, memory: float = 1024)[source]

Class-based method of calculating the Husimi-Q function of many different quantum states at fixed phase-space points 0.5*g* (xvec + i*yvec). This class has slightly higher first-usage costs than qfunc, but subsequent operations will be several times faster. However, it can require quite a lot of memory. Call the created object as a function to retrieve the Husimi-Q function.

Parameters
xvec, yvecarray_like

x- and y-coordinates at which to calculate the Husimi-Q function.

gfloat, default sqrt(2)

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

memoryreal, default 1024

Size in MB that may be used internally as workspace. This class will raise MemoryError if subsequently passed a state of sufficiently large dimension that this bound would be exceeded. In those cases, use qfunc with precompute_memory=None instead to force using the slower, more memory-efficient algorithm.

See also

qfunc

a single function version, which will involve computing several quantities multiple times in order to use less memory.

Examples

Initialise the class for a square set of coordinates, with some states we want to investigate.

>>> xvec = np.linspace(-2, 2, 101)
>>> states = [qutip.rand_dm(10) for _ in [None]*10]
>>> qfunc = qutip.QFunc(xvec, xvec)

Now we can calculate the Husimi-Q function over each of the states more efficiently with:

>>> husimiq = np.array([qfunc(state) for state in states])

Solver

class SESolver(H, *, options=None)[source]

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

Parameters
HQobj, QobjEvo

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

optionsdict, optional

Options for the solver, see SESolver.options and Integrator for a list of all options.

Attributes
stats: dict

Diverse diagnostic statistics of the evolution.

property options

Solver’s options:

store_final_state: bool, default=False

Whether or not to store the final state of the evolution in the result class.

store_states: bool, default=None

Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.

normalize_output: bool, default=True

Normalize output state to hide ODE numerical errors.

progress_bar: str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}, {}

How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.

progress_kwargs: dict, default={“chunk_size”: 10}

Arguments to pass to the progress_bar. Qutip’s bars use chunk_size.

method: str, default=”adams”

Which ordinary differential equation integration method to use.

class MESolver(H, c_ops=None, *, options=None)[source]

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

Evolve the density matrix (rho0) using a given Hamiltonian or Liouvillian (H) and an optional set of collapse operators (c_ops), by integrating the set of ordinary differential equations that define the system.

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

Parameters
HQobj, QobjEvo

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

c_opslist of Qobj, QobjEvo

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

optionsdict, optional

Options for the solver, see SESolver.options and Integrator for a list of all options.

Attributes
stats: dict

Diverse diagnostic statistics of the evolution.

class BRSolver(H, a_ops, c_ops=None, sec_cutoff=0.1, *, options=None)[source]

Bloch Redfield equation evolution of a density matrix for a given Hamiltonian and set of bath coupling operators.

Parameters
HQobj, QobjEvo

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

a_opslist of (a_op, spectra)

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

a_opqutip.Qobj, qutip.QobjEvo

The operator coupling to the environment. Must be hermitian.

spectraCoefficient

The corresponding bath spectra. As a Coefficient using an ‘w’ args. Can depend on t only if a_op is a qutip.QobjEvo. SpectraCoefficient can be used to conver a coefficient depending on t to one depending on w.

Example:

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

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

optionsdict, optional

Options for the solver, see BRSolver.options and Integrator for a list of all options.

sec_cutofffloat {0.1}

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

Attributes
stats: dict

Diverse diagnostic statistics of the evolution.

property options

Options for bloch redfield solver:

store_final_state: bool, default=False

Whether or not to store the final state of the evolution in the result class.

store_states: bool, default=None

Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.

normalize_output: bool, default=False

Normalize output state to hide ODE numerical errors.

progress_bar: str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}, default=”text”

How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.

progress_kwargs: dict, default={“chunk_size”:10}

Arguments to pass to the progress_bar. Qutip’s bars use chunk_size.

tensor_type: str [‘sparse’, ‘dense’, ‘data’], default=”sparse”

Which data type to use when computing the brtensor. With a cutoff ‘sparse’ is usually the most efficient.

sparse_eigensolver: bool, default=False

Whether to use the sparse eigensolver

method: str, default=”adams”

Which ODE integrator methods are supported.

Non-Markovian HEOM Solver

class HEOMSolver(H, bath, max_depth, *, options=None)[source]

HEOM solver that supports multiple baths.

The baths must be all either bosonic or fermionic baths.

Parameters
HQobj, QobjEvo

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

bathBath or list of Bath

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

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

max_depthint

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

optionsdict, optional

Generic solver options. If set to None the default options will be used. Keyword only. Default: None.

Attributes
adosHierarchyADOs

The description of the hierarchy constructed from the given bath and maximum depth.

property options

Options for HEOMSolver:

store_final_state: bool, default=False

Whether or not to store the final state of the evolution in the result class.

store_states: bool, default=None

Whether or not to store the state vectors or density matrices. On None the states will be saved if no expectation operators are given.

normalize_output: bool, default=False

Normalize output state to hide ODE numerical errors.

progress_bar: str {‘text’, ‘enhanced’, ‘tqdm’, ‘’}, default=”text”

How to present the solver progress. ‘tqdm’ uses the python module of the same name and raise an error if not installed. Empty string or False will disable the bar.

progress_kwargs: dict, default={“chunk_size”: 10}

Arguments to pass to the progress_bar. Qutip’s bars use chunk_size.

method: str, default=”adams”

Which ordinary differential equation integration method to use.

state_data_type: str, default=”dense”

Name of the data type of the state used during the ODE evolution. Use an empty string to keep the input state type. Many integrator can only work with Dense.

store_adosbool, default=False

Whether or not to store the HEOM ADOs. Only relevant when using the HEOM solver.

resultclass

alias of qutip.solver.heom.bofin_solvers.HEOMResult

run(state0, tlist, *, args=None, e_ops=None)[source]

Solve for the time evolution of the system.

Parameters
state0Qobj or HierarchyADOsState or array-like

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

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

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

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

tlistlist

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

argsdict, optional {None}

Change the args of the RHS for the evolution.

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

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

Returns
HEOMResult

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

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

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

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

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

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

See HEOMResult and Result for the complete list of attributes.

start(state0, t0)[source]

Set the initial state and time for a step evolution.

Parameters
state0Qobj

Initial state of the evolution. This may provide either just the initial density matrix of the system, or the full set of ADOs for the hierarchy. See the documentation for rho0 in the .run(...) method for details.

t0double

Initial time of the evolution.

steady_state(use_mkl=True, mkl_max_iter_refine=100, mkl_weighted_matching=False)[source]

Compute the steady state of the system.

Parameters
use_mklbool, default=False

Whether to use mkl or not. If mkl is not installed or if this is false, use the scipy splu solver instead.

mkl_max_iter_refineint

Specifies the the maximum number of iterative refinement steps that the MKL PARDISO solver performs.

For a complete description, see iparm(8) in http://cali2.unilim.fr/intel-xe/mkl/mklman/GUID-264E311E-ACED-4D56-AC31-E9D3B11D1CBF.htm.

mkl_weighted_matchingbool

MKL PARDISO can use a maximum weighted matching algorithm to permute large elements close the diagonal. This strategy adds an additional level of reliability to the factorization methods.

For a complete description, see iparm(13) in http://cali2.unilim.fr/intel-xe/mkl/mklman/GUID-264E311E-ACED-4D56-AC31-E9D3B11D1CBF.htm.

Returns
steady_stateQobj

The steady state density matrix of the system.

steady_adosHierarchyADOsState

The steady state of the full ADO hierarchy. A particular ADO may be extracted from the full state by calling extract.

property sys_dims

Dimensions of the space that the system use, excluding any environment:

qutip.basis(sovler.dims) will create a state with proper dimensions for this solver.

class HSolverDL(H_sys, coup_op, coup_strength, temperature, N_cut, N_exp, cut_freq, *, bnd_cut_approx=False, options=None, combine=True)[source]

A helper class for creating an HEOMSolver that is backwards compatible with the HSolverDL provided in qutip.nonmarkov.heom in QuTiP 4.6 and below.

See HEOMSolver and DrudeLorentzBath for more descriptions of the underlying solver and bath construction.

An exact copy of the QuTiP 4.6 HSolverDL is provided in qutip.nonmarkov.dlheom_solver for cases where the functionality of the older solver is required. The older solver will be completely removed in QuTiP 5.

Note

Unlike the version of HSolverDL in QuTiP 4.6, this solver supports supplying a time-dependent or Liouvillian H_sys.

Note

For compatibility with HSolverDL in QuTiP 4.6 and below, the parameter N_exp specifying the number of exponents to keep in the expansion of the bath correlation function is one more than the equivalent Nk used in the DrudeLorentzBath. I.e., Nk = N_exp - 1. The Nk parameter in the DrudeLorentzBath does not count the zeroeth exponent in order to better match common usage in the literature.

Note

The stats and renorm arguments accepted in QuTiP 4.6 and below are no longer supported.

Parameters
H_sysQobj or QobjEvo or list

The system Hamiltonian or Liouvillian. See HEOMSolver for a complete description.

coup_opQobj

Operator describing the coupling between system and bath. See parameter Q in BosonicBath for a complete description.

coup_strengthfloat

Coupling strength. Referred to as lam in DrudeLorentzBath.

temperaturefloat

Bath temperature. Referred to as T in DrudeLorentzBath.

N_cutint

The maximum depth of the hierarchy. See max_depth in HEOMSolver for a full description.

N_expint

Number of exponential terms used to approximate the bath correlation functions. The equivalent Nk in DrudeLorentzBath is one less than N_exp (see note above).

cut_freqfloat

Bath spectral density cutoff frequency. Referred to as gamma in DrudeLorentzBath.

bnd_cut_approxbool

Use boundary cut off approximation. If true, the Matsubara terminator is added to the system Liouvillian (and H_sys is promoted to a Liouvillian if it was a Hamiltonian). Keyword only. Default: False.

optionsdict, optional

Generic solver options. If set to None the default options will be used. Keyword only. Default: None.

combinebool, default True

Whether to combine exponents with the same frequency (and coupling operator). See BosonicBath.combine for details. Keyword only. Default: True.

class BathExponent(type, dim, Q, ck, vk, ck2=None, sigma_bar_k_offset=None, tag=None)[source]

Represents a single exponent (naively, an excitation mode) within the decomposition of the correlation functions of a bath.

Parameters
type{“R”, “I”, “RI”, “+”, “-“} or BathExponent.ExponentType

The type of bath exponent.

“R” and “I” are bosonic bath exponents that appear in the real and imaginary parts of the correlation expansion.

“RI” is combined bosonic bath exponent that appears in both the real and imaginary parts of the correlation expansion. The combined exponent has a single vk. The ck is the coefficient in the real expansion and ck2 is the coefficient in the imaginary expansion.

“+” and “-” are fermionic bath exponents. These fermionic bath exponents must specify sigma_bar_k_offset which specifies the amount to add to k (the exponent index within the bath of this exponent) to determine the k of the corresponding exponent with the opposite sign (i.e. “-” or “+”).

dimint or None

The dimension (i.e. maximum number of excitations for this exponent). Usually 2 for fermionic exponents or None (i.e. unlimited) for bosonic exponents.

QQobj

The coupling operator for this excitation mode.

vkcomplex

The frequency of the exponent of the excitation term.

ckcomplex

The coefficient of the excitation term.

ck2optional, complex

For exponents of type “RI” this is the coefficient of the term in the imaginary expansion (and ck is the coefficient in the real expansion).

sigma_bar_k_offsetoptional, int

For exponents of type “+” this gives the offset (within the list of exponents within the bath) of the corresponding “-” bath exponent. For exponents of type “-” it gives the offset of the corresponding “+” exponent.

tagoptional, str, tuple or any other object

A label for the exponent (often the name of the bath). It defaults to None.

Attributes
All of the parameters are available as attributes.
types

alias of qutip.solver.heom.bofin_baths.ExponentType

class Bath(exponents)[source]

Represents a list of bath expansion exponents.

Parameters
exponentslist of BathExponent

The exponents of the correlation function describing the bath.

Attributes
All of the parameters are available as attributes.
class BosonicBath(Q, ck_real, vk_real, ck_imag, vk_imag, combine=True, tag=None)[source]

A helper class for constructing a bosonic bath from the expansion coefficients and frequencies for the real and imaginary parts of the bath correlation function.

If the correlation functions C(t) is split into real and imaginary parts:

C(t) = C_real(t) + i * C_imag(t)

then:

C_real(t) = sum(ck_real * exp(- vk_real * t))
C_imag(t) = sum(ck_imag * exp(- vk_imag * t))

Defines the coefficients ck and the frequencies vk.

Note that the ck and vk may be complex, even through C_real(t) and C_imag(t) (i.e. the sum) is real.

Parameters
QQobj

The coupling operator for the bath.

ck_reallist of complex

The coefficients of the expansion terms for the real part of the correlation function. The corresponding frequencies are passed as vk_real.

vk_reallist of complex

The frequencies (exponents) of the expansion terms for the real part of the correlation function. The corresponding ceofficients are passed as ck_real.

ck_imaglist of complex

The coefficients of the expansion terms in the imaginary part of the correlation function. The corresponding frequencies are passed as vk_imag.

vk_imaglist of complex

The frequencies (exponents) of the expansion terms for the imaginary part of the correlation function. The corresponding ceofficients are passed as ck_imag.

combinebool, default True

Whether to combine exponents with the same frequency (and coupling operator). See combine for details.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

classmethod combine(exponents, rtol=1e-05, atol=1e-07)[source]

Group bosonic exponents with the same frequency and return a single exponent for each frequency present.

Exponents with the same frequency are only combined if they share the same coupling operator .Q.

Note that combined exponents take their tag from the first exponent in the group being combined (i.e. the one that occurs first in the given exponents list).

Parameters
exponentslist of BathExponent

The list of exponents to combine.

rtolfloat, default 1e-5

The relative tolerance to use to when comparing frequencies and coupling operators.

atolfloat, default 1e-7

The absolute tolerance to use to when comparing frequencies and coupling operators.

Returns
list of BathExponent

The new reduced list of exponents.

class DrudeLorentzBath(Q, lam, gamma, T, Nk, combine=True, tag=None)[source]

A helper class for constructing a Drude-Lorentz bosonic bath from the bath parameters (see parameters below).

Parameters
QQobj

Operator describing the coupling between system and bath.

lamfloat

Coupling strength.

gammafloat

Bath spectral density cutoff frequency.

Tfloat

Bath temperature.

Nkint

Number of exponential terms used to approximate the bath correlation functions.

combinebool, default True

Whether to combine exponents with the same frequency (and coupling operator). See BosonicBath.combine for details.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

terminator()[source]

Return the Matsubara terminator for the bath and the calculated approximation discrepancy.

Returns
delta: float

The approximation discrepancy. That is, the difference between the true correlation function of the Drude-Lorentz bath and the sum of the Nk exponential terms is approximately 2 * delta * dirac(t), where dirac(t) denotes the Dirac delta function.

terminatorQobj

The Matsubara terminator – i.e. a liouvillian term representing the contribution to the system-bath dynamics of all exponential expansion terms beyond Nk. It should be used by adding it to the system liouvillian (i.e. liouvillian(H_sys)).

class DrudeLorentzPadeBath(Q, lam, gamma, T, Nk, combine=True, tag=None)[source]

A helper class for constructing a Padé expansion for a Drude-Lorentz bosonic bath from the bath parameters (see parameters below).

A Padé approximant is a sum-over-poles expansion ( see https://en.wikipedia.org/wiki/Pad%C3%A9_approximant).

The application of the Padé method to spectrum decompoisitions is described in “Padé spectrum decompositions of quantum distribution functions and optimal hierarchical equations of motion construction for quantum open systems” [1].

The implementation here follows the approach in the paper.

[1] J. Chem. Phys. 134, 244106 (2011); https://doi.org/10.1063/1.3602466

This is an alternative to the DrudeLorentzBath which constructs a simpler exponential expansion.

Parameters
QQobj

Operator describing the coupling between system and bath.

lamfloat

Coupling strength.

gammafloat

Bath spectral density cutoff frequency.

Tfloat

Bath temperature.

Nkint

Number of Padé exponentials terms used to approximate the bath correlation functions.

combinebool, default True

Whether to combine exponents with the same frequency (and coupling operator). See BosonicBath.combine for details.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

terminator()[source]

Return the Padé terminator for the bath and the calculated approximation discrepancy.

Returns
delta: float

The approximation discrepancy. That is, the difference between the true correlation function of the Drude-Lorentz bath and the sum of the Nk exponential terms is approximately 2 * delta * dirac(t), where dirac(t) denotes the Dirac delta function.

terminatorQobj

The Padé terminator – i.e. a liouvillian term representing the contribution to the system-bath dynamics of all exponential expansion terms beyond Nk. It should be used by adding it to the system liouvillian (i.e. liouvillian(H_sys)).

class UnderDampedBath(Q, lam, gamma, w0, T, Nk, combine=True, tag=None)[source]

A helper class for constructing an under-damped bosonic bath from the bath parameters (see parameters below).

Parameters
QQobj

Operator describing the coupling between system and bath.

lamfloat

Coupling strength.

gammafloat

Bath spectral density cutoff frequency.

w0float

Bath spectral density resonance frequency.

Tfloat

Bath temperature.

Nkint

Number of exponential terms used to approximate the bath correlation functions.

combinebool, default True

Whether to combine exponents with the same frequency (and coupling operator). See BosonicBath.combine for details.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

class FermionicBath(Q, ck_plus, vk_plus, ck_minus, vk_minus, tag=None)[source]

A helper class for constructing a fermionic bath from the expansion coefficients and frequencies for the + and - modes of the bath correlation function.

There must be the same number of + and - modes and their coefficients must be specified in the same order so that ck_plus[i], vk_plus[i] are the plus coefficient and frequency corresponding to the minus mode ck_minus[i], vk_minus[i].

In the fermionic case the order in which excitations are created or destroyed is important, resulting in two different correlation functions labelled C_plus(t) and C_plus(t):

C_plus(t) = sum(ck_plus * exp(- vk_plus * t))
C_minus(t) = sum(ck_minus * exp(- vk_minus * t))

where the expansions above define the coeffiients ck and the frequencies vk.

Parameters
QQobj

The coupling operator for the bath.

ck_pluslist of complex

The coefficients of the expansion terms for the + part of the correlation function. The corresponding frequencies are passed as vk_plus.

vk_pluslist of complex

The frequencies (exponents) of the expansion terms for the + part of the correlation function. The corresponding ceofficients are passed as ck_plus.

ck_minuslist of complex

The coefficients of the expansion terms for the - part of the correlation function. The corresponding frequencies are passed as vk_minus.

vk_minuslist of complex

The frequencies (exponents) of the expansion terms for the - part of the correlation function. The corresponding ceofficients are passed as ck_minus.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

class LorentzianBath(Q, gamma, w, mu, T, Nk, tag=None)[source]

A helper class for constructing a Lorentzian fermionic bath from the bath parameters (see parameters below).

Note

This Matsubara expansion used in this bath converges very slowly and Nk > 20 may be required to get good convergence. The Padé expansion used by LorentzianPadeBath converges much more quickly.

Parameters
QQobj

Operator describing the coupling between system and bath.

gammafloat

The coupling strength between the system and the bath.

wfloat

The width of the environment.

mufloat

The chemical potential of the bath.

Tfloat

Bath temperature.

Nkint

Number of exponential terms used to approximate the bath correlation functions.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

class LorentzianPadeBath(Q, gamma, w, mu, T, Nk, tag=None)[source]

A helper class for constructing a Padé expansion for Lorentzian fermionic bath from the bath parameters (see parameters below).

A Padé approximant is a sum-over-poles expansion ( see https://en.wikipedia.org/wiki/Pad%C3%A9_approximant).

The application of the Padé method to spectrum decompoisitions is described in “Padé spectrum decompositions of quantum distribution functions and optimal hierarchical equations of motion construction for quantum open systems” [1].

The implementation here follows the approach in the paper.

[1] J. Chem. Phys. 134, 244106 (2011); https://doi.org/10.1063/1.3602466

This is an alternative to the LorentzianBath which constructs a simpler exponential expansion that converges much more slowly in this particular case.

Parameters
QQobj

Operator describing the coupling between system and bath.

gammafloat

The coupling strength between the system and the bath.

wfloat

The width of the environment.

mufloat

The chemical potential of the bath.

Tfloat

Bath temperature.

Nkint

Number of exponential terms used to approximate the bath correlation functions.

tagoptional, str, tuple or any other object

A label for the bath exponents (for example, the name of the bath). It defaults to None but can be set to help identify which bath an exponent is from.

class HierarchyADOs(exponents, max_depth)[source]

A description of ADOs (auxilliary density operators) with the hierarchical equations of motion.

The list of ADOs is constructed from a list of bath exponents (corresponding to one or more baths). Each ADO is referred to by a label that lists the number of “excitations” of each bath exponent. The level of a label within the hierarchy is the sum of the “excitations” within the label.

For example the label (0, 0, ..., 0) represents the density matrix of the system being solved and is the only 0th level label.

The labels with a single 1, i.e. (1, 0, ..., 0), (0, 1, 0, ... 0), etc. are the 1st level labels.

The second level labels all have either two 1s or a single 2, and so on for the third and higher levels of the hierarchy.

Parameters
exponentslist of BathExponent

The exponents of the correlation function describing the bath or baths.

max_depthint

The maximum depth of the hierarchy (i.e. the maximum sum of “excitations” in the hierarchy ADO labels or maximum ADO level).

Attributes
exponentslist of BathExponent

The exponents of the correlation function describing the bath or baths.

max_depthint

The maximum depth of the hierarchy (i.e. the maximum sum of “excitations” in the hierarchy ADO labels).

dimslist of int

The dimensions of each exponent within the bath(s).

vklist of complex

The frequency of each exponent within the bath(s).

cklist of complex

The coefficient of each exponent within the bath(s).

ck2: list of complex

For exponents of type “RI”, the coefficient of the exponent within the imaginary expansion. For other exponent types, the entry is None.

sigma_bar_k_offset: list of int

For exponents of type “+” or “-” the offset within the list of modes of the corresponding “-” or “+” exponent. For other exponent types, the entry is None.

labels: list of tuples

A list of the ADO labels within the hierarchy.

exps(label)[source]

Converts an ADO label into a tuple of exponents, with one exponent for each “excitation” within the label.

The number of exponents returned is always equal to the level of the label within the hierarchy (i.e. the sum of the indices within the label).

Parameters
labeltuple

The ADO label to convert to a list of exponents.

Returns
tuple of BathExponent

A tuple of BathExponents.

Examples

ados.exps((1, 0, 0)) would return [ados.exponents[0]]

ados.exps((2, 0, 0)) would return [ados.exponents[0], ados.exponents[0]].

ados.exps((1, 2, 1)) would return [ados.exponents[0], ados.exponents[1], ados.exponents[1],            ados.exponents[2]].

filter(level=None, tags=None, dims=None, types=None)[source]

Return a list of ADO labels for ADOs whose “excitations” match the given patterns.

Each of the filter parameters (tags, dims, types) may be either unspecified (None) or a list. Unspecified parameters are excluded from the filtering.

All specified filter parameters must be lists of the same length. Each position in the lists describes a particular excitation and any exponent that matches the filters may supply that excitation. The level of all labels returned is thus equal to the length of the filter parameter lists.

Within a filter parameter list, items that are None represent wildcards and match any value of that exponent attribute

Parameters
levelint

The hierarchy depth to return ADOs from.

tagslist of object or None

Filter parameter that matches the .tag attribute of exponents.

dimslist of int

Filter parameter that matches the .dim attribute of exponents.

typeslist of BathExponent types or list of str

Filter parameter that matches the .type attribute of exponents. Types may be supplied by name (e.g. “R”, “I”, “+”) instead of by the actual type (e.g. BathExponent.types.R).

Returns
list of tuple

The ADO label for each ADO whose exponent excitations (i.e. label) match the given filters or level.

idx(label)[source]

Return the index of the ADO label within the list of labels, i.e. within self.labels.

Parameters
labeltuple

The label to look up.

Returns
int

The index of the label within the list of ADO labels.

next(label, k)[source]

Return the ADO label with one more excitation in the k’th exponent dimension or None if adding the excitation would exceed the dimension or maximum depth of the hierarchy.

Parameters
labeltuple

The ADO label to add an excitation to.

kint

The exponent to add the excitation to.

Returns
tuple or None

The next label.

prev(label, k)[source]

Return the ADO label with one fewer excitation in the k’th exponent dimension or None if the label has no exciations in the k’th exponent.

Parameters
labeltuple

The ADO label to remove the excitation from.

kint

The exponent to remove the excitation from.

Returns
tuple or None

The previous label.

class HierarchyADOsState(rho, ados, ado_state)[source]

Provides convenient access to the full hierarchy ADO state at a particular point in time, t.

Parameters
rhoQobj

The current state of the system (i.e. the 0th component of the hierarchy).

adosHierarchyADOs

The description of the hierarchy.

ado_statenumpy.array

The full state of the hierarchy.

Attributes
rhoQobj

The system state.

In addition, all of the attributes of the hierarchy description,
i.e. ``HierarchyADOs``, are provided directly on this class for
convenience. E.g. one can access ``.labels``, or ``.exponents`` or
call ``.idx(label)`` directly.
See :class:`HierarchyADOs` for a full list of the available attributes
and methods.
extract(idx_or_label)[source]

Extract a Qobj representing the specified ADO from a full representation of the ADO states.

Parameters
idxint or label

The index of the ADO to extract. If an ADO label, e.g. (0, 1, 0, ...) is supplied instead, then the ADO is extracted by label instead.

Returns
Qobj

A Qobj representing the state of the specified ADO.

class HEOMResult(e_ops, options, *, solver=None, stats=None, **kw)[source]

Integrator

class IntegratorScipyAdams(system, options)[source]

Integrator using Scipy ode with zvode integrator using adams method. Ordinary Differential Equation solver by netlib (http://www.netlib.org/odepack).

Usable with method="adams"

property options

Supported options by zvode integrator:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

orderint, default=12, ‘adams’ or 5, ‘bdf’

Order of integrator <=12 ‘adams’, <=5 ‘bdf’

nstepsint, default=2500

Max. number of internal steps/call.

first_stepfloat, default=0

Size of initial step (0 = automatic).

min_stepfloat, default=0

Minimum step size (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic) When using pulses, change to half the thinest pulse otherwise it may be skipped.

class IntegratorScipyBDF(system, options)[source]

Integrator using Scipy ode with zvode integrator using bdf method. Ordinary Differential Equation solver by netlib (http://www.netlib.org/odepack).

Usable with method="bdf"

property options

Supported options by zvode integrator:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

orderint, default=12, ‘adams’ or 5, ‘bdf’

Order of integrator <=12 ‘adams’, <=5 ‘bdf’

nstepsint, default=2500

Max. number of internal steps/call.

first_stepfloat, default=0

Size of initial step (0 = automatic).

min_stepfloat, default=0

Minimum step size (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic) When using pulses, change to half the thinest pulse otherwise it may be skipped.

class IntegratorScipylsoda(system, options)[source]

Integrator using Scipy ode with lsoda integrator. ODE solver by netlib (http://www.netlib.org/odepack) Automatically choose between ‘Adams’ and ‘BDF’ methods to solve both stiff and non-stiff systems.

Usable with method="lsoda"

property options

Supported options by lsoda integrator:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

nstepsint, default=2500

Max. number of internal steps/call.

max_order_nsint, default=12

Maximum order used in the nonstiff case (<= 12).

max_order_sint, default=5

Maximum order used in the stiff case (<= 5).

first_stepfloat, default=0

Size of initial step (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic) When using pulses, change to half the thinest pulse otherwise it may be skipped.

min_stepfloat, default=0

Minimum step size (0 = automatic)

class IntegratorScipyDop853(system, options)[source]

Integrator using Scipy ode with dop853 integrator. Eight order runge-kutta method by Dormand & Prince. Use fortran implementation from [E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary Differential Equations i. Nonstiff Problems. 2nd edition. Springer Series in Computational Mathematics, Springer-Verlag (1993)].

Usable with method="dop853"

property options

Supported options by dop853 integrator:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

nstepsint, default=2500

Max. number of internal steps/call.

first_stepfloat, default=0

Size of initial step (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic)

ifactor, dfactorfloat, default=6., 0.3

Maximum factor to increase/decrease step size by in one step

betafloat, default=0

Beta parameter for stabilised step size control.

See scipy.integrate.ode ode for more detail

class IntegratorVern7(system, options)[source]

QuTiP’s implementation of Verner’s “most efficient” Runge-Kutta method of order 7. These are Runge-Kutta methods with variable steps and dense output.

The implementation uses QuTiP’s Data objects for the state, allowing sparse, GPU or other data layer objects to be used efficiently by the solver in their native formats.

See http://people.math.sfu.ca/~jverner/ for a detailed description of the methods.

Usable with method="vern7"

property options

Supported options by verner method:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

nstepsint, default=1000

Max. number of internal steps/call.

first_stepfloat, default=0

Size of initial step (0 = automatic).

min_stepfloat, default=0

Minimum step size (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic) When using pulses, change to half the thinest pulse otherwise it may be skipped.

interpolatebool, default=True

Whether to use interpolation step, faster most of the time.

class IntegratorVern9(system, options)[source]

QuTiP’s implementation of Verner’s “most efficient” Runge-Kutta method of order 9. These are Runge-Kutta methods with variable steps and dense output.

The implementation uses QuTiP’s Data objects for the state, allowing sparse, GPU or other data layer objects to be used efficiently by the solver in their native formats.

See http://people.math.sfu.ca/~jverner/ for a detailed description of the methods.

Usable with method="vern9"

property options

Supported options by verner method:

atolfloat, default=1e-8

Absolute tolerance.

rtolfloat, default=1e-6

Relative tolerance.

nstepsint, default=1000

Max. number of internal steps/call.

first_stepfloat, default=0

Size of initial step (0 = automatic).

min_stepfloat, default=0

Minimum step size (0 = automatic).

max_stepfloat, default=0

Maximum step size (0 = automatic) When using pulses, change to half the thinest pulse otherwise it may be skipped.

interpolatebool, default=True

Whether to use interpolation step, faster most of the time.

class IntegratorDiag(system, options)[source]

Integrator solving the ODE by diagonalizing the system and solving analytically. It can only solve constant system and has a long preparation time, but the integration is fast.

Usable with method="diag"

property options

Supported options by “diag” method:

eigensolver_dtypestr, default=”dense”

Qutip data type {“dense”, “csr”, etc.} to use when computing the eigenstates. The dense eigen solver is usually faster and more stable.

class IntegratorKrylov(system, options)[source]

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

property options

Supported options by krylov method:

atolfloat, default=1e-7

Absolute tolerance.

nstepsint, default=100

Max. number of internal steps/call.

min_step, max_stepfloat, default=(1e-5, 1e5)

Minimum and maximum step size.

krylov_dim: int, default=0

Dimension of Krylov approximation subspaces used for the time evolution approximation. If the defaut 0 is given, the dimension is calculated from the system size N, using min(int((N + 100)**0.5), N-1).

sub_system_tol: float, default=1e-7

Tolerance to detect a happy breakdown. A happy breakdown occurs when the initial ket is in a subspace of the Hamiltonian smaller than krylov_dim.

always_compute_step: bool, default=False

If True, the step length is computed each time a new Krylov subspace is computed. Otherwise it is computed only once when creating the integrator.

Non-Markovian Memory Cascade and Transfer Tensor Solvers

class MemoryCascade(H_S, L1, L2, S_matrix=None, c_ops_markov=None, integrator='propagator', parallel=False, options=None)[source]

Class for running memory cascade simulations of open quantum systems with time-delayed coherent feedback.

Attributes
H_Squtip.Qobj

System Hamiltonian (can also be a Liouvillian)

L1qutip.Qobj / list of qutip.Qobj

System operators coupling into the feedback loop. Can be a single operator or a list of operators.

L2qutip.Qobj / list of qutip.Qobj

System operators coupling out of the feedback loop. Can be a single operator or a list of operators. L2 must have the same length as L1.

S_matrix: *array*

S matrix describing which operators in L1 are coupled to which operators in L2 by the feedback channel. Defaults to an n by n identity matrix where n is the number of elements in L1/L2.

c_ops_markovqutip.Qobj / list of qutip.Qobj

Decay operators describing conventional Markovian decay channels. Can be a single operator or a list of operators.

integratorstr {‘propagator’, ‘mesolve’}

Integrator method to use. Defaults to ‘propagator’ which tends to be faster for long times (i.e., large Hilbert space).

parallelbool

Run integrator in parallel if True. Only implemented for ‘propagator’ as the integrator method.

optionsdict

Generic solver options.

outfieldcorr(rho0, blist, tlist, tau, c1=None, c2=None)[source]

Compute output field expectation value <O_n(tn)…O_2(t2)O_1(t1)> for times t1,t2,… and O_i = I, b_out, b_out^dagger, b_loop, b_loop^dagger

Parameters
rho0qutip.Qobj

initial density matrix or state vector (ket).

blistarray_like

List of integers specifying the field operators: 0: I (nothing) 1: b_out 2: b_out^dagger 3: b_loop 4: b_loop^dagger

tlistarray_like

list of corresponding times t1,..,tn at which to evaluate the field operators

taufloat

time-delay

c1qutip.Qobj

system collapse operator that couples to the in-loop field in question (only needs to be specified if self.L1 has more than one element)

c2qutip.Qobj

system collapse operator that couples to the output field in question (only needs to be specified if self.L2 has more than one element)

Returns
: complex

expectation value of field correlation function

outfieldpropagator(blist, tlist, tau, c1=None, c2=None, notrace=False)[source]

Compute propagator for computing output field expectation values <O_n(tn)…O_2(t2)O_1(t1)> for times t1,t2,… and O_i = I, b_out, b_out^dagger, b_loop, b_loop^dagger

Parameters
blistarray_like

List of integers specifying the field operators: 0: I (nothing) 1: b_out 2: b_out^dagger 3: b_loop 4: b_loop^dagger

tlistarray_like

list of corresponding times t1,..,tn at which to evaluate the field operators

taufloat

time-delay

c1qutip.Qobj

system collapse operator that couples to the in-loop field in question (only needs to be specified if self.L1 has more than one element)

c2qutip.Qobj

system collapse operator that couples to the output field in question (only needs to be specified if self.L2 has more than one element)

notracebool {False}

If this optional is set to True, a propagator is returned for a cascade of k systems, where \((k-1) tau < t < k tau\). If set to False (default), a generalized partial trace is performed and a propagator for a single system is returned.

Returns
: qutip.Qobj

time-propagator for computing field correlation function

propagator(t, tau, notrace=False)[source]

Compute propagator for time t and time-delay tau

Parameters
tfloat

current time

taufloat

time-delay

notracebool {False}

If this optional is set to True, a propagator is returned for a cascade of k systems, where \((k-1) tau < t < k tau\). If set to False (default), a generalized partial trace is performed and a propagator for a single system is returned.

Returns
——-
: :class:`qutip.Qobj`

time-propagator for reduced system dynamics

rhot(rho0, t, tau)[source]

Compute the reduced system density matrix \(\rho(t)\)

Parameters
rho0qutip.Qobj

initial density matrix or state vector (ket)

tfloat

current time

taufloat

time-delay

Returns
: qutip.Qobj

density matrix at time \(t\)

class TTMSolverOptions(dynmaps=None, times=[], learningtimes=[], thres=0.0, options=None)[source]

Class of options for the Transfer Tensor Method solver.

Attributes
dynmapslist of qutip.Qobj

List of precomputed dynamical maps (superoperators), or a callback function that returns the superoperator at a given time.

timesarray_like

List of times \(t_n\) at which to calculate \(\rho(t_n)\)

learningtimesarray_like

List of times \(t_k\) to use as learning times if argument dynmaps is a callback function.

thresfloat

Threshold for halting. Halts if \(||T_{n}-T_{n-1}||\) is below treshold.

optionsqutip.solver.SolverOptions

Generic solver options.

Solver Options and Results

class Result(e_ops, options, *, solver=None, stats=None, **kw)[source]

Base class for storing solver results.

Parameters
e_opsQobj, QobjEvo, function or list or dict of these

The e_ops parameter defines the set of values to record at each time step t. If an element is a Qobj or QobjEvo the value recorded is the expectation value of that operator given the state at t. If the element is a function, f, the value recorded is f(t, state).

The values are recorded in the e_data and expect attributes of this result object. e_data is a dictionary and expect is a list, where each item contains the values of the corresponding e_op.

optionsdict

The options for this result class.

solverstr or None

The name of the solver generating these results.

statsdict or None

The stats generated by the solver while producing these results. Note that the solver may update the stats directly while producing results.

kwdict

Additional parameters specific to a result sub-class.

Attributes
timeslist

A list of the times at which the expectation values and states were recorded.

stateslist of Qobj

The state at each time t (if the recording of the state was requested).

final_stateQobj:

The final state (if the recording of the final state was requested).

expectlist of arrays of expectation values

A list containing the values of each e_op. The list is in the same order in which the e_ops were supplied and empty if no e_ops were given.

Each element is itself a list and contains the values of the corresponding e_op, with one value for each time in .times.

The same lists of values may be accessed via the .e_data dictionary and the original e_ops are available via the .e_ops attribute.

e_datadict

A dictionary containing the values of each e_op. If the e_ops were supplied as a dictionary, the keys are the same as in that dictionary. Otherwise the keys are the index of the e_op in the .expect list.

The lists of expectation values returned are the same lists as those returned by .expect.

e_opsdict

A dictionary containing the supplied e_ops as ExpectOp instances. The keys of the dictionary are the same as for .e_data. Each value is object where .e_ops[k](t, state) calculates the value of e_op k at time t and the given state, and .e_ops[k].op is the original object supplied to create the e_op.

solverstr or None

The name of the solver generating these results.

statsdict or None

The stats generated by the solver while producing these results.

optionsdict

The options for this result class.

add(t, state)[source]

Add a state to the results for the time t of the evolution.

Adding a state calculates the expectation value of the state for each of the supplied e_ops and stores the result in .expect.

The state is recorded in .states and .final_state if specified by the supplied result options.

Parameters
tfloat

The time of the added state.

statetypically a Qobj

The state a time t. Usually this is a Qobj with suitable dimensions, but it sub-classes of result might support other forms of the state.

.. note::

The expectation values, i.e. e_ops, and states are recorded by the state processors (see .add_processor).

Additional processors may be added by sub-classes.

Permutational Invariance

class Dicke(N, hamiltonian=None, emission=0.0, dephasing=0.0, pumping=0.0, collective_emission=0.0, collective_dephasing=0.0, collective_pumping=0.0)[source]

The Dicke class which builds the Lindbladian and Liouvillian matrix.

Parameters
N: int

The number of two-level systems.

hamiltonianqutip.Qobj

A Hamiltonian in the Dicke basis.

The matrix dimensions are (nds, nds), with nds being the number of Dicke states. The Hamiltonian can be built with the operators given by the jspin functions.

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

Examples

>>> from piqs import Dicke, jspin
>>> N = 2
>>> jx, jy, jz = jspin(N)
>>> jp = jspin(N, "+")
>>> jm = jspin(N, "-")
>>> ensemble = Dicke(N, emission=1.)
>>> L = ensemble.liouvillian()
Attributes
N: int

The number of two-level systems.

hamiltonianqutip.Qobj

A Hamiltonian in the Dicke basis.

The matrix dimensions are (nds, nds), with nds being the number of Dicke states. The Hamiltonian can be built with the operators given by the jspin function in the “dicke” basis.

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_dephasing: float

Collective dephasing coefficient. default: 0.0

collective_pumping: float

Collective pumping coefficient. default: 0.0

nds: int

The number of Dicke states.

dshape: tuple

The shape of the Hilbert space in the Dicke or uncoupled basis. default: (nds, nds).

c_ops()[source]

Build collapse operators in the full Hilbert space 2^N.

Returns
c_ops_list: list

The list with the collapse operators in the 2^N Hilbert space.

coefficient_matrix()[source]

Build coefficient matrix for ODE for a diagonal problem.

Returns
M: ndarray

The matrix M of the coefficients for the ODE dp/dt = Mp. p is the vector of the diagonal matrix elements of the density matrix rho in the Dicke basis.

lindbladian()[source]

Build the Lindbladian superoperator of the dissipative dynamics.

Returns
lindbladianqutip.Qobj

The Lindbladian matrix as a qutip.Qobj.

liouvillian()[source]

Build the total Liouvillian using the Dicke basis.

Returns
liouvqutip.Qobj

The Liouvillian matrix for the system.

pisolve(initial_state, tlist, options=None)[source]

Solve for diagonal Hamiltonians and initial states faster.

Parameters
initial_statequtip.Qobj

An initial state specified as a density matrix of qutip.Qbj type.

tlist: ndarray

A 1D numpy array of list of timesteps to integrate

optionsqutip.solver.SolverOptions

The options for the solver.

Returns
result: list

A dictionary of the type qutip.solver.Result which holds the results of the evolution.

class Pim(N, emission=0.0, dephasing=0, pumping=0, collective_emission=0, collective_pumping=0, collective_dephasing=0)[source]

The Permutation Invariant Matrix class.

Initialize the class with the parameters for generating a Permutation Invariant matrix which evolves a given diagonal initial state p as:

dp/dt = Mp

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

Attributes
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_dephasing: float

Collective dephasing coefficient. default: 0.0

collective_pumping: float

Collective pumping coefficient. default: 0.0

M: dict

A nested dictionary of the structure {row: {col: val}} which holds non zero elements of the matrix M

calculate_j_m(dicke_row, dicke_col)[source]

Get the value of j and m for the particular Dicke space element.

Parameters
dicke_row, dicke_col: int

The row and column from the Dicke space matrix

Returns
j, m: float

The j and m values.

calculate_k(dicke_row, dicke_col)[source]

Get k value from the current row and column element in the Dicke space.

Parameters
dicke_row, dicke_col: int

The row and column from the Dicke space matrix.

Returns
——-
k: int

The row index for the matrix M for given Dicke space element.

coefficient_matrix()[source]

Generate the matrix M governing the dynamics for diagonal cases.

If the initial density matrix and the Hamiltonian is diagonal, the evolution of the system is given by the simple ODE: dp/dt = Mp.

isdicke(dicke_row, dicke_col)[source]

Check if an element in a matrix is a valid element in the Dicke space. Dicke row: j value index. Dicke column: m value index. The function returns True if the element exists in the Dicke space and False otherwise.

Parameters
dicke_row, dicke_colint

Index of the element in Dicke space which needs to be checked

solve(rho0, tlist, options=None)[source]

Solve the ODE for the evolution of diagonal states and Hamiltonians.

tau1(j, m)[source]

Calculate coefficient matrix element relative to (j, m, m).

tau2(j, m)[source]

Calculate coefficient matrix element relative to (j, m+1, m+1).

tau3(j, m)[source]

Calculate coefficient matrix element relative to (j+1, m+1, m+1).

tau4(j, m)[source]

Calculate coefficient matrix element relative to (j-1, m+1, m+1).

tau5(j, m)[source]

Calculate coefficient matrix element relative to (j+1, m, m).

tau6(j, m)[source]

Calculate coefficient matrix element relative to (j-1, m, m).

tau7(j, m)[source]

Calculate coefficient matrix element relative to (j+1, m-1, m-1).

tau8(j, m)[source]

Calculate coefficient matrix element relative to (j, m-1, m-1).

tau9(j, m)[source]

Calculate coefficient matrix element relative to (j-1, m-1, m-1).

tau_valid(dicke_row, dicke_col)[source]

Find the Tau functions which are valid for this value of (dicke_row, dicke_col) given the number of TLS. This calculates the valid tau values and reurns a dictionary specifying the tau function name and the value.

Parameters
dicke_row, dicke_colint

Index of the element in Dicke space which needs to be checked.

Returns
taus: dict

A dictionary of key, val as {tau: value} consisting of the valid taus for this row and column of the Dicke space element.

Distribution functions

class Distribution(data=None, xvecs=[], xlabels=[])[source]

A class for representation spatial distribution functions.

The Distribution class can be used to prepresent spatial distribution functions of arbitray dimension (although only 1D and 2D distributions are used so far).

It is indented as a base class for specific distribution function, and provide implementation of basic functions that are shared among all Distribution functions, such as visualization, calculating marginal distributions, etc.

Parameters
dataarray_like

Data for the distribution. The dimensions must match the lengths of the coordinate arrays in xvecs.

xvecslist

List of arrays that spans the space for each coordinate.

xlabelslist

List of labels for each coordinate.

marginal(dim=0)[source]

Calculate the marginal distribution function along the dimension dim. Return a new Distribution instance describing this reduced- dimensionality distribution.

Parameters
dimint

The dimension (coordinate index) along which to obtain the marginal distribution.

Returns
dDistributions

A new instances of Distribution that describes the marginal distribution.

project(dim=0)[source]

Calculate the projection (max value) distribution function along the dimension dim. Return a new Distribution instance describing this reduced-dimensionality distribution.

Parameters
dimint

The dimension (coordinate index) along which to obtain the projected distribution.

Returns
dDistributions

A new instances of Distribution that describes the projection.

visualize(fig=None, ax=None, figsize=(8, 6), colorbar=True, cmap=None, style='colormap', show_xlabel=True, show_ylabel=True)[source]

Visualize the data of the distribution in 1D or 2D, depending on the dimensionality of the underlaying distribution.

Parameters:

figmatplotlib Figure instance

If given, use this figure instance for the visualization,

axmatplotlib Axes instance

If given, render the visualization using this axis instance.

figsizetuple

Size of the new Figure instance, if one needs to be created.

colorbar: Bool

Whether or not the colorbar (in 2D visualization) should be used.

cmap: matplotlib colormap instance

If given, use this colormap for 2D visualizations.

stylestring

Type of visualization: ‘colormap’ (default) or ‘surface’.

Returns
fig, axtuple

A tuple of matplotlib figure and axes instances.

class WignerDistribution(rho=None, extent=[[- 5, 5], [- 5, 5]], steps=250)[source]
class QDistribution(rho=None, extent=[[- 5, 5], [- 5, 5]], steps=250)[source]
class TwoModeQuadratureCorrelation(state=None, theta1=0.0, theta2=0.0, extent=[[- 5, 5], [- 5, 5]], steps=250)[source]
update(state)[source]

calculate probability distribution for quadrature measurement outcomes given a two-mode wavefunction or density matrix

update_psi(psi)[source]

calculate probability distribution for quadrature measurement outcomes given a two-mode wavefunction

update_rho(rho)[source]

calculate probability distribution for quadrature measurement outcomes given a two-mode density matrix

class HarmonicOscillatorWaveFunction(psi=None, omega=1.0, extent=[- 5, 5], steps=250)[source]
update(psi)[source]

Calculate the wavefunction for the given state of an harmonic oscillator

class HarmonicOscillatorProbabilityFunction(rho=None, omega=1.0, extent=[- 5, 5], steps=250)[source]
update(rho)[source]

Calculate the probability function for the given state of an harmonic oscillator (as density matrix)

Optimal control

class Optimizer(config, dyn, params=None)[source]

Base class for all control pulse optimisers. This class should not be instantiated, use its subclasses. This class implements the fidelity, gradient and interation callback functions. All subclass objects must be initialised with a

  • OptimConfig instance - various configuration options

  • Dynamics instance - describes the dynamics of the (quantum) system to be control optimised

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

params: Dictionary

The key value pairs are the attribute name and value. Note: attributes are created if they do not exist already, and are overwritten if they do.

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 pulse optim algorithm alg.

disp_conv_msgbool

Set true to display a convergence message (for scipy.optimize.minimize methods anyway)

optim_methodstring

a scipy.optimize.minimize method that will be used to optimise the pulse for minimum fidelity error

method_paramsDictionary

Options for the optim_method. Note that where there is an equivalent attribute of this instance or the termination_conditions (for example maxiter) it will override an value in these options

approx_gradbool

If set True then the method will approximate the gradient itself (if it has requirement and facility for this) This will mean that the fid_err_grad_wrapper will not get called Note it should be left False when using the Dynamics to calculate approximate gradients Note it is set True automatically when the alg is CRAB

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

boundsList of floats

Bounds for the parameters. If not set before the run_optimization call then the list is built automatically based on the amp_lbound and amp_ubound attributes. Setting this attribute directly allows specific bounds to be set for individual parameters. Note: Only some methods use bounds

dynamicsDynamics (subclass instance)

describes the dynamics of the (quantum) system to be control optimised (see Dynamics classes for details)

configOptimConfig instance

various configuration options (see OptimConfig for details)

termination_conditionsTerminationCondition instance

attributes determine when the optimisation will end

pulse_generatorPulseGen (subclass instance)

(can be) used to create initial pulses not used by the class, but set by pulseoptim.create_pulse_optimizer

statsStats

attributes of which give performance stats for the optimisation set to None to reduce overhead of calculating stats. Note it is (usually) shared with the Dynamics instance

dumpqutip.control.dump.OptimDump

Container for data dumped during the optimisation. Can be set by specifying the dumping level or set directly. Note this is mainly intended for user and a development debugging but could be used for status information during a long optimisation.

dumpingstring

The level of data dumping that will occur during the optimisation

dump_to_filebool

If set True then data will be dumped to file during the optimisation dumping will be set to SUMMARY during init_optim if dump_to_file is True and dumping not set. Default is False

dump_dirstring

Basically a link to dump.dump_dir. Exists so that it can be set through optim_params. If dump is None then will return None or will set dumping to SUMMARY when setting a path

iter_summaryOptimIterSummary

Summary of the most recent iteration. Note this is only set if dummping is on

apply_method_params(params=None)[source]

Loops through all the method_params (either passed here or the method_params attribute) If the name matches an attribute of this object or the termination conditions object, then the value of this attribute is set. Otherwise it is assumed to a method_option for the scipy.optimize.minimize function

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

property dumping

The level of data dumping that will occur during the optimisation

  • NONE : No processing data dumped (Default)

  • SUMMARY : A summary at each iteration will be recorded

  • FULL : All logs will be generated and dumped

  • CUSTOM : Some customised level of dumping

When first set to CUSTOM this is equivalent to SUMMARY. It is then up to the user to specify which logs are dumped

fid_err_func_wrapper(*args)[source]

Get the fidelity error achieved using the ctrl amplitudes passed in as the first argument.

This is called by generic optimisation algorithm as the func to the minimised. The argument is the current variable values, i.e. control amplitudes, passed as a flat array. Hence these are reshaped as [nTimeslots, n_ctrls] and then used to update the stored ctrl values (if they have changed)

The error is checked against the target, and the optimisation is terminated if the target has been achieved.

fid_err_grad_wrapper(*args)[source]

Get the gradient of the fidelity error with respect to all of the variables, i.e. the ctrl amplidutes in each timeslot

This is called by generic optimisation algorithm as the gradients of func to the minimised wrt the variables. The argument is the current variable values, i.e. control amplitudes, passed as a flat array. Hence these are reshaped as [nTimeslots, n_ctrls] and then used to update the stored ctrl values (if they have changed)

Although the optimisation algorithms have a check within them for function convergence, i.e. local minima, the sum of the squares of the normalised gradient is checked explicitly, and the optimisation is terminated if this is below the min_gradient_norm condition

init_optim(term_conds)[source]

Check optimiser attribute status and passed parameters before running the optimisation. This is called by run_optimization, but could called independently to check the configuration.

iter_step_callback_func(*args)[source]

Check the elapsed wall time for the optimisation run so far. Terminate if this has exceeded the maximum allowed time

run_optimization(term_conds=None)[source]

This default function optimisation method is a wrapper to the scipy.optimize.minimize function.

It will attempt to minimise the fidelity error with respect to some parameters, which are determined by _get_optim_var_vals (see below)

The optimisation end when one of the passed termination conditions has been met, e.g. target achieved, wall time, or function call or iteration count exceeded. Note these conditions include gradient minimum met (local minima) for methods that use a gradient.

The function minimisation method is taken from the optim_method attribute. Note that not all of these methods have been tested. Note that some of these use a gradient and some do not. See the scipy documentation for details. Options specific to the method can be passed setting the method_params attribute.

If the parameter term_conds=None, then the termination_conditions attribute must already be set. It will be overwritten if the parameter is not None

The result is returned in an OptimResult object, which includes the final fidelity, time evolution, reason for termination etc

class OptimizerBFGS(config, dyn, params=None)[source]

Implements the run_optimization method using the BFGS algorithm

run_optimization(term_conds=None)[source]

Optimise the control pulse amplitudes to minimise the fidelity error using the BFGS (Broyden–Fletcher–Goldfarb–Shanno) algorithm The optimisation end when one of the passed termination conditions has been met, e.g. target achieved, gradient minimum met (local minima), wall time / iteration count exceeded.

Essentially this is wrapper to the: scipy.optimize.fmin_bfgs function

If the parameter term_conds=None, then the termination_conditions attribute must already be set. It will be overwritten if the parameter is not None

The result is returned in an OptimResult object, which includes the final fidelity, time evolution, reason for termination etc

class OptimizerLBFGSB(config, dyn, params=None)[source]

Implements the run_optimization method using the L-BFGS-B algorithm

Attributes
max_metric_corrinteger

The maximum number of variable metric corrections used to define the limited memory matrix. That is the number of previous gradient values that are used to approximate the Hessian see the scipy.optimize.fmin_l_bfgs_b documentation for description of m argument

init_optim(term_conds)[source]

Check optimiser attribute status and passed parameters before running the optimisation. This is called by run_optimization, but could called independently to check the configuration.

run_optimization(term_conds=None)[source]

Optimise the control pulse amplitudes to minimise the fidelity error using the L-BFGS-B algorithm, which is the constrained (bounded amplitude values), limited memory, version of the Broyden–Fletcher–Goldfarb–Shanno algorithm.

The optimisation end when one of the passed termination conditions has been met, e.g. target achieved, gradient minimum met (local minima), wall time / iteration count exceeded.

Essentially this is wrapper to the: scipy.optimize.fmin_l_bfgs_b function This in turn is a warpper for well established implementation of the L-BFGS-B algorithm written in Fortran, which is therefore very fast. See SciPy documentation for credit and details on this function.

If the parameter term_conds=None, then the termination_conditions attribute must already be set. It will be overwritten if the parameter is not None

The result is returned in an OptimResult object, which includes the final fidelity, time evolution, reason for termination etc

class OptimizerCrab(config, dyn, params=None)[source]

Optimises the pulse using the CRAB algorithm [1]. It uses the scipy.optimize.minimize function with the method specified by the optim_method attribute. See Optimizer.run_optimization for details It minimises the fidelity error function with respect to the CRAB basis function coefficients.

AJGP ToDo: Add citation here

init_optim(term_conds)[source]

Check optimiser attribute status and passed parameters before running the optimisation. This is called by run_optimization, but could called independently to check the configuration.

class OptimizerCrabFmin(config, dyn, params=None)[source]

Optimises the pulse using the CRAB algorithm [1], [2]. It uses the scipy.optimize.fmin function which is effectively a wrapper for the Nelder-Mead method. It minimises the fidelity error function with respect to the CRAB basis function coefficients. This is the default Optimizer for CRAB.

References

1

P. Doria, T. Calarco & S. Montangero. Phys. Rev. Lett. 106, 190501 (2011).

2

T. Caneva, T. Calarco, & S. Montangero. Phys. Rev. A 84, 022326 (2011).

run_optimization(term_conds=None)[source]

This function optimisation method is a wrapper to the scipy.optimize.fmin function.

It will attempt to minimise the fidelity error with respect to some parameters, which are determined by _get_optim_var_vals which in the case of CRAB are the basis function coefficients

The optimisation end when one of the passed termination conditions has been met, e.g. target achieved, wall time, or function call or iteration count exceeded. Specifically to the fmin method, the optimisation will stop when change parameter values is less than xtol or the change in function value is below ftol.

If the parameter term_conds=None, then the termination_conditions attribute must already be set. It will be overwritten if the parameter is not None

The result is returned in an OptimResult object, which includes the final fidelity, time evolution, reason for termination etc

class OptimIterSummary[source]

A summary of the most recent iteration of the pulse optimisation

Attributes
iter_numint

Iteration number of the pulse optimisation

fid_func_call_numint

Fidelity function call number of the pulse optimisation

grad_func_call_numint

Gradient function call number of the pulse optimisation

fid_errfloat

Fidelity error

grad_normfloat

fidelity gradient (wrt the control parameters) vector norm that is the magnitude of the gradient

wall_timefloat

Time spent computing the pulse optimisation so far (in seconds of elapsed time)

class TerminationConditions[source]

Base class for all termination conditions Used to determine when to stop the optimisation algorithm Note different subclasses should be used to match the type of optimisation being used

Attributes
fid_err_targfloat

Target fidelity error

fid_goalfloat

goal fidelity, e.g. 1 - self.fid_err_targ It its typical to set this for unitary systems

max_wall_timefloat

# maximum time for optimisation (seconds)

min_gradient_normfloat

Minimum normalised gradient after which optimisation will terminate

max_iterationsinteger

Maximum iterations of the optimisation algorithm

max_fid_func_callsinteger

Maximum number of calls to the fidelity function during the optimisation algorithm

accuracy_factorfloat

Determines the accuracy of the result. Typical values for accuracy_factor are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy scipy.optimize.fmin_l_bfgs_b factr argument. Only set for specific methods (fmin_l_bfgs_b) that uses this Otherwise the same thing is passed as method_option ftol (although the scale is different) Hence it is not defined here, but may be set by the user

class OptimResult[source]

Attributes give the result of the pulse optimisation attempt

Attributes
termination_reasonstring

Description of the reason for terminating the optimisation

fidelityfloat

final (normalised) fidelity that was achieved

initial_fid_errfloat

fidelity error before optimisation starting

fid_errfloat

final fidelity error that was achieved

goal_achievedboolean

True is the fidely error achieved was below the target

grad_norm_finalfloat

Final value of the sum of the squares of the (normalised) fidelity error gradients

grad_norm_min_reachedfloat

True if the optimisation terminated due to the minimum value of the gradient being reached

num_iterinteger

Number of iterations of the optimisation algorithm completed

max_iter_exceededboolean

True if the iteration limit was reached

max_fid_func_exceededboolean

True if the fidelity function call limit was reached

wall_timefloat

time elapsed during the optimisation

wall_time_limit_exceededboolean

True if the wall time limit was reached

timearray[num_tslots+1] of float

Time are the start of each timeslot with the final value being the total evolution time

initial_ampsarray[num_tslots, n_ctrls]

The amplitudes at the start of the optimisation

final_ampsarray[num_tslots, n_ctrls]

The amplitudes at the end of the optimisation

evo_full_finalQobj

The evolution operator from t=0 to t=T based on the final amps

evo_full_initialQobj

The evolution operator from t=0 to t=T based on the initial amps

statsStats

Object contaning the stats for the run (if any collected)

optimizerOptimizer

Instance of the Optimizer used to generate the result

class Dynamics(optimconfig, params=None)[source]

This is a base class only. See subclass descriptions and choose an appropriate one for the application.

Note that initialize_controls must be called before most of the methods can be used. init_timeslots can be called sometimes earlier in order to access timeslot related attributes

This acts as a container for the operators that are used to calculate time evolution of the system under study. That is the dynamics generators (Hamiltonians, Lindbladians etc), the propagators from one timeslot to the next, and the evolution operators. Due to the large number of matrix additions and multiplications, for small systems at least, the optimisation performance is much better using ndarrays to represent these operators. However

Attributes
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

params: Dictionary

The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

statsStats

Attributes of which give performance stats for the optimisation set to None to reduce overhead of calculating stats. Note it is (usually) shared with the Optimizer object

tslot_computerTimeslotComputer (subclass instance)

Used to manage when the timeslot dynamics generators, propagators, gradients etc are updated

prop_computerPropagatorComputer (subclass instance)

Used to compute the propagators and their gradients

fid_computerFidelityComputer (subclass instance)

Used to computer the fidelity error and the fidelity error gradient.

memory_optimizationint

Level of memory optimisation. Setting to 0 (default) means that execution speed is prioritized over memory. Setting to 1 means that some memory prioritisation steps will be taken, for instance using Qobj (and hence sparse arrays) as the the internal operator data type, and not caching some operators Potentially further memory saving maybe made with memory_optimization > 1. The options are processed in _set_memory_optimizations, see this for more information. Individual memory saving options can be switched by settting them directly (see below)

oper_dtypetype

Data type for internal dynamics generators, propagators and time evolution operators. This can be ndarray or Qobj. Qobj may perform better for larger systems, and will also perform better when (custom) fidelity measures use Qobj methods such as partial trace. See _choose_oper_dtype for how this is chosen when not specified

cache_phased_dyn_genbool

If True then the dynamics generators will be saved with and without the propagation prefactor (if there is one) Defaults to True when memory_optimization=0, otherwise False

cache_prop_gradbool

If the True then the propagator gradients (for exact gradients) will be computed when the propagator are computed and cache until the are used by the fidelity computer. If False then the fidelity computer will calculate them as needed. Defaults to True when memory_optimization=0, otherwise False

cache_dyn_gen_eigenvectors_adj: bool

If True then DynamicsUnitary will cached the adjoint of the Hamiltion eignvector matrix Defaults to True when memory_optimization=0, otherwise False

sparse_eigen_decomp: bool

If True then DynamicsUnitary will use the sparse eigenvalue decomposition. Defaults to True when memory_optimization<=1, otherwise False

num_tslotsinteger

Number of timeslots (aka timeslices)

num_ctrlsinteger

calculate the of controls from the length of the control list

evo_timefloat

Total time for the evolution

tauarray[num_tslots] of float

Duration of each timeslot Note that if this is set before initialize_controls is called then num_tslots and evo_time are calculated from tau, otherwise tau is generated from num_tslots and evo_time, that is equal size time slices

timearray[num_tslots+1] of float

Cumulative time for the evolution, that is the time at the start of each time slice

drift_dyn_genQobj or list of Qobj

Drift or system dynamics generator (Hamiltonian) Matrix defining the underlying dynamics of the system Can also be a list of Qobj (length num_tslots) for time varying drift dynamics

ctrl_dyn_genList of Qobj

Control dynamics generator (Hamiltonians) List of matrices defining the control dynamics

initialQobj

Starting state / gate The matrix giving the initial state / gate, i.e. at time 0 Typically the identity for gate evolution

targetQobj

Target state / gate: The matrix giving the desired state / gate for the evolution

ctrl_ampsarray[num_tslots, num_ctrls] of float

Control amplitudes The amplitude (scale factor) for each control in each timeslot

initial_ctrl_scalingfloat

Scale factor applied to be applied the control amplitudes when they are initialised This is used by the PulseGens rather than in any fucntions in this class

initial_ctrl_offsetfloat

Linear offset applied to be applied the control amplitudes when they are initialised This is used by the PulseGens rather than in any fucntions in this class

dyn_genList of Qobj

List of combined dynamics generators (Qobj) for each timeslot

proplist of Qobj

List of propagators (Qobj) for each timeslot

prop_gradarray[num_tslots, num_ctrls] of Qobj

Array of propagator gradients (Qobj) for each timeslot, control

fwd_evoList of Qobj

List of evolution operators (Qobj) from the initial to the given

onwd_evoList of Qobj

List of evolution operators (Qobj) from the initial to the given

onto_evoList of Qobj

List of evolution operators (Qobj) from the initial to the given

evo_currentBoolean

Used to flag that the dynamics used to calculate the evolution operators is current. It is set to False when the amplitudes change

fact_mat_round_precfloat

Rounding precision used when calculating the factor matrix to determine if two eigenvalues are equivalent Only used when the PropagatorComputer uses diagonalisation

def_amps_fnamestring

Default name for the output used when save_amps is called

unitarity_check_levelint

If > 0 then unitarity of the system evolution is checked at at evolution recomputation. level 1 checks all propagators level 2 checks eigen basis as well Default is 0

unitarity_tol :

Tolerance used in checking if operator is unitary Default is 1e-10

dumpqutip.control.dump.DynamicsDump

Store of historical calculation data. Set to None (Default) for no storing of historical data Use dumping property to set level of data dumping

dumpingstring

The level of data dumping that will occur during the time evolution calculation.

dump_to_filebool

If set True then data will be dumped to file during the calculations dumping will be set to SUMMARY during init_evo if dump_to_file is True and dumping not set. Default is False

dump_dirstring

Basically a link to dump.dump_dir. Exists so that it can be set through dyn_params. If dump is None then will return None or will set dumping to SUMMARY when setting a path

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

combine_dyn_gen(k)[source]

Computes the dynamics generator for a given timeslot The is the combined Hamiltion for unitary systems

compute_evolution()[source]

Recalculate the time evolution operators Dynamics generators (e.g. Hamiltonian) and prop (propagators) are calculated as necessary Actual work is completed by the recompute_evolution method of the timeslot computer

property dumping

The level of data dumping that will occur during the time evolution calculation.

  • NONE : No processing data dumped (Default)

  • SUMMARY : A summary of each time evolution will be recorded

  • FULL : All operators used or created in the calculation dumped

  • CUSTOM : Some customised level of dumping

When first set to CUSTOM this is equivalent to SUMMARY. It is then up to the user to specify which operators are dumped. WARNING: FULL could consume a lot of memory!

property dyn_gen

List of combined dynamics generators (Qobj) for each timeslot

property dyn_gen_phase

Some op that is applied to the dyn_gen before expontiating to get the propagator. See phase_application for how this is applied

flag_system_changed()[source]

Flag evolution, fidelity and gradients as needing recalculation

property full_evo

Full evolution - time evolution at final time slot

property fwd_evo

List of evolution operators (Qobj) from the initial to the given timeslot

get_ctrl_dyn_gen(j)[source]

Get the dynamics generator for the control Not implemented in the base class. Choose a subclass

get_drift_dim()[source]

Returns the size of the matrix that defines the drift dynamics that is assuming the drift is NxN, then this returns N

get_dyn_gen(k)[source]

Get the combined dynamics generator for the timeslot Not implemented in the base class. Choose a subclass

get_num_ctrls()[source]

calculate the of controls from the length of the control list sets the num_ctrls property, which can be used alternatively subsequently

init_timeslots()[source]

Generate the timeslot duration array ‘tau’ based on the evo_time and num_tslots attributes, unless the tau attribute is already set in which case this step in ignored Generate the cumulative time array ‘time’ based on the tau values

initialize_controls(amps, init_tslots=True)[source]

Set the initial control amplitudes and time slices Note this must be called after the configuration is complete before any dynamics can be calculated

property num_ctrls

calculate the of controls from the length of the control list sets the num_ctrls property, which can be used alternatively subsequently

property onto_evo

List of evolution operators (Qobj) from the initial to the given timeslot

property onwd_evo

List of evolution operators (Qobj) from the initial to the given timeslot

property phase_application

scalar(string), default=’preop’ Determines how the phase is applied to the dynamics generators

  • ‘preop’ : P = expm(phase*dyn_gen)

  • ‘postop’ : P = expm(dyn_gen*phase)

  • ‘custom’ : Customised phase application

The ‘custom’ option assumes that the _apply_phase method has been set to a custom function.

Type

phase_application

property prop

List of propagators (Qobj) for each timeslot

property prop_grad

Array of propagator gradients (Qobj) for each timeslot, control

refresh_drift_attribs()[source]

Reset the dyn_shape, dyn_dims and time_depend_drift attribs

save_amps(file_name=None, times=None, amps=None, verbose=False)[source]

Save a file with the current control amplitudes in each timeslot The first column in the file will be the start time of the slot

Parameters
file_namestring

Name of the file If None given the def_amps_fname attribuite will be used

timesList type (or string)

List / array of the start times for each slot If None given this will be retrieved through get_amp_times() If ‘exclude’ then times will not be saved in the file, just the amplitudes

ampsArray[num_tslots, num_ctrls]

Amplitudes to be saved If None given the ctrl_amps attribute will be used

verboseBoolean

If True then an info message will be logged

unitarity_check()[source]

Checks whether all propagators are unitary

update_ctrl_amps(new_amps)[source]

Determine if any amplitudes have changed. If so, then mark the timeslots as needing recalculation The actual work is completed by the compare_amps method of the timeslot computer

class DynamicsGenMat(optimconfig, params=None)[source]

This sub class can be used for any system where no additional operator is applied to the dynamics generator before calculating the propagator, e.g. classical dynamics, Lindbladian

class DynamicsUnitary(optimconfig, params=None)[source]

This is the subclass to use for systems with dynamics described by unitary matrices. E.g. closed systems with Hermitian Hamiltonians Note a matrix diagonalisation is used to compute the exponent The eigen decomposition is also used to calculate the propagator gradient. The method is taken from DYNAMO (see file header)

Attributes
drift_hamQobj

This is the drift Hamiltonian for unitary dynamics It is mapped to drift_dyn_gen during initialize_controls

ctrl_hamList of Qobj

These are the control Hamiltonians for unitary dynamics It is mapped to ctrl_dyn_gen during initialize_controls

HList of Qobj

The combined drift and control Hamiltonians for each timeslot These are the dynamics generators for unitary dynamics. It is mapped to dyn_gen during initialize_controls

check_unitarity()[source]

Checks whether all propagators are unitary For propagators found not to be unitary, the potential underlying causes are investigated.

initialize_controls(amplitudes, init_tslots=True)[source]

Set the initial control amplitudes and time slices Note this must be called after the configuration is complete before any dynamics can be calculated

property num_ctrls

calculate the of controls from the length of the control list sets the num_ctrls property, which can be used alternatively subsequently

class DynamicsSymplectic(optimconfig, params=None)[source]

Symplectic systems This is the subclass to use for systems where the dynamics is described by symplectic matrices, e.g. coupled oscillators, quantum optics

Attributes
omegaarray[drift_dyn_gen.shape]

matrix used in the calculation of propagators (time evolution) with symplectic systems.

property dyn_gen_phase

The phasing operator for the symplectic group generators usually refered to as Omega By default this is applied as ‘postop’ dyn_gen*-Omega If phase_application is ‘preop’ it is applied as Omega*dyn_gen

class PropagatorComputer(dynamics, params=None)[source]

Base for all Propagator Computer classes that are used to calculate the propagators, and also the propagator gradient when exact gradient methods are used Note: they must be instantiated with a Dynamics object, that is the container for the data that the functions operate on This base class cannot be used directly. See subclass descriptions and choose the appropriate one for the application

Attributes
log_levelinteger

level of messaging output from the logger. Options are attributes of qutip_utils.logging, 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

grad_exactboolean

indicates whether the computer class instance is capable of computing propagator gradients. It is used to determine whether to create the Dynamics prop_grad array

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

reset()[source]

reset any configuration data

class PropCompApproxGrad(dynamics, params=None)[source]

This subclass can be used when the propagator is calculated simply by expm of the dynamics generator, i.e. when gradients will be calculated using approximate methods.

reset()[source]

reset any configuration data

class PropCompDiag(dynamics, params=None)[source]

Coumputes the propagator exponentiation using diagonalisation of of the dynamics generator

reset()[source]

reset any configuration data

class PropCompFrechet(dynamics, params=None)[source]

Frechet method for calculating the propagator: exponentiating the combined dynamics generator and the propagator gradient. It should work for all systems, e.g. unitary, open, symplectic. There are other PropagatorComputer subclasses that may be more efficient.

reset()[source]

reset any configuration data

class FidelityComputer(dynamics, params=None)[source]

Base class for all Fidelity Computers. This cannot be used directly. See subclass descriptions and choose one appropriate for the application Note: this must be instantiated with a Dynamics object, that is the container for the data that the methods operate on

Attributes
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

dimensional_normfloat

Normalisation constant

fid_norm_funcfunction

Used to normalise the fidelity See SU and PSU options for the unitary dynamics

grad_norm_funcfunction

Used to normalise the fidelity gradient See SU and PSU options for the unitary dynamics

uses_onwd_evoboolean

flag to specify whether the onwd_evo evolution operator (see Dynamics) is used by the FidelityComputer

uses_onto_evoboolean
flag to specify whether the onto_evo evolution operator

(see Dynamics) is used by the FidelityComputer

fid_errfloat

Last computed value of the fidelity error

fidelityfloat

Last computed value of the normalised fidelity

fidelity_currentboolean

flag to specify whether the fidelity / fid_err are based on the current amplitude values. Set False when amplitudes change

fid_err_grad: array[num_tslot, num_ctrls] of float

Last computed values for the fidelity error gradients wrt the control in the timeslot

grad_normfloat

Last computed value for the norm of the fidelity error gradients (sqrt of the sum of the squares)

fid_err_grad_currentboolean

flag to specify whether the fidelity / fid_err are based on the current amplitude values. Set False when amplitudes change

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

clear()[source]

clear any temporarily held status data

flag_system_changed()[source]

Flag fidelity and gradients as needing recalculation

get_fid_err()[source]

returns the absolute distance from the maximum achievable fidelity

get_fid_err_gradient()[source]

Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array wrt the timeslot control amplitude

init_comp()[source]

initialises the computer based on the configuration of the Dynamics

reset()[source]

reset any configuration data and clear any temporarily held status data

class FidCompUnitary(dynamics, params=None)[source]

Computes fidelity error and gradient assuming unitary dynamics, e.g. closed qubit systems Note fidelity and gradient calculations were taken from DYNAMO (see file header)

Attributes
phase_optionstring
determines how global phase is treated in fidelity calculations:

PSU - global phase ignored SU - global phase included

fidelity_prenormcomplex

Last computed value of the fidelity before it is normalised It is stored to use in the gradient normalisation calculation

fidelity_prenorm_currentboolean

flag to specify whether fidelity_prenorm are based on the current amplitude values. Set False when amplitudes change

clear()[source]

clear any temporarily held status data

compute_fid_grad()[source]

Calculates exact gradient of function wrt to each timeslot control amplitudes. Note these gradients are not normalised These are returned as a (nTimeslots x n_ctrls) array

flag_system_changed()[source]

Flag fidelity and gradients as needing recalculation

get_fid_err()[source]

Gets the absolute error in the fidelity

get_fid_err_gradient()[source]

Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array The gradients are cached in case they are requested mutliple times between control updates (although this is not typically found to happen)

get_fidelity()[source]

Gets the appropriately normalised fidelity value The normalisation is determined by the fid_norm_func pointer which should be set in the config

get_fidelity_prenorm()[source]

Gets the current fidelity value prior to normalisation Note the gradient function uses this value The value is cached, because it is used in the gradient calculation

init_comp()[source]

Check configuration and initialise the normalisation

init_normalization()[source]

Calc norm of <Ufinal | Ufinal> to scale subsequent norms When considering unitary time evolution operators, this basically results in calculating the trace of the identity matrix and is hence equal to the size of the target matrix There may be situations where this is not the case, and hence it is not assumed to be so. The normalisation function called should be set to either the PSU - global phase ignored SU - global phase respected

normalize_gradient_PSU(grad)[source]

Normalise the gradient matrix passed as grad This PSU version is independent of global phase

normalize_gradient_SU(grad)[source]

Normalise the gradient matrix passed as grad This SU version respects global phase

reset()[source]

reset any configuration data and clear any temporarily held status data

set_phase_option(phase_option=None)[source]

Deprecated - use phase_option Phase options are SU - global phase important PSU - global phase is not important

class FidCompTraceDiff(dynamics, params=None)[source]

Computes fidelity error and gradient for general system dynamics by calculating the the fidelity error as the trace of the overlap of the difference between the target and evolution resulting from the pulses with the transpose of the same. This should provide a distance measure for dynamics described by matrices Note the gradient calculation is taken from: ‘Robust quantum gates for open systems via optimal control: Markovian versus non-Markovian dynamics’ Frederik F Floether, Pierre de Fouquieres, and Sophie G Schirmer

Attributes
scale_factorfloat

The fidelity error calculated is of some arbitary scale. This factor can be used to scale the fidelity error such that it may represent some physical measure If None is given then it is caculated as 1/2N, where N is the dimension of the drift, when the Dynamics are initialised.

compute_fid_err_grad()[source]

Calculate exact gradient of the fidelity error function wrt to each timeslot control amplitudes. Uses the trace difference norm fidelity These are returned as a (nTimeslots x n_ctrls) array

get_fid_err()[source]

Gets the absolute error in the fidelity

get_fid_err_gradient()[source]

Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array The gradients are cached in case they are requested mutliple times between control updates (although this is not typically found to happen)

init_comp()[source]

initialises the computer based on the configuration of the Dynamics Calculates the scale_factor is not already set

reset()[source]

reset any configuration data and clear any temporarily held status data

class FidCompTraceDiffApprox(dynamics, params=None)[source]

As FidCompTraceDiff, except uses the finite difference method to compute approximate gradients

Attributes
epsilonfloat

control amplitude offset to use when approximating the gradient wrt a timeslot control amplitude

compute_fid_err_grad()[source]

Calculates gradient of function wrt to each timeslot control amplitudes. Note these gradients are not normalised They are calulated These are returned as a (nTimeslots x n_ctrls) array

reset()[source]

reset any configuration data and clear any temporarily held status data

class TimeslotComputer(dynamics, params=None)[source]

Base class for all Timeslot Computers Note: this must be instantiated with a Dynamics object, that is the container for the data that the methods operate on

Attributes
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

evo_comp_summaryEvoCompSummary

A summary of the most recent evolution computation Used in the stats and dump Will be set to None if neither stats or dump are set

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value Note: attributes are created if they do not exist already, and are overwritten if they do.

dump_current()[source]

Store a copy of the current time evolution

class TSlotCompUpdateAll(dynamics, params=None)[source]

Timeslot Computer - Update All Updates all dynamics generators, propagators and evolutions when ctrl amplitudes are updated

compare_amps(new_amps)[source]

Determine if any amplitudes have changed. If so, then mark the timeslots as needing recalculation Returns: True if amplitudes are the same, False if they have changed

get_timeslot_for_fidelity_calc()[source]

Returns the timeslot index that will be used calculate current fidelity value. This (default) method simply returns the last timeslot

recompute_evolution()[source]

Recalculates the evolution operators. Dynamics generators (e.g. Hamiltonian) and prop (propagators) are calculated as necessary

class PulseGen(dyn=None, params=None)[source]

Pulse generator Base class for all Pulse generators The object can optionally be instantiated with a Dynamics object, in which case the timeslots and amplitude scaling and offset are copied from that. Otherwise the class can be used independently by setting: tau (array of timeslot durations) or num_tslots and pulse_time for equally spaced timeslots

Attributes
num_tslotsinteger

Number of timeslots, aka timeslices (copied from Dynamics if given)

pulse_timefloat

total duration of the pulse (copied from Dynamics.evo_time if given)

scalingfloat

linear scaling applied to the pulse (copied from Dynamics.initial_ctrl_scaling if given)

offsetfloat

linear offset applied to the pulse (copied from Dynamics.initial_ctrl_offset if given)

tauarray[num_tslots] of float

Duration of each timeslot (copied from Dynamics if given)

lboundfloat

Lower boundary for the pulse amplitudes Note that the scaling and offset attributes can be used to fully bound the pulse for all generators except some of the random ones This bound (if set) may result in additional shifting / scaling Default is -Inf

uboundfloat

Upper boundary for the pulse amplitudes Note that the scaling and offset attributes can be used to fully bound the pulse for all generators except some of the random ones This bound (if set) may result in additional shifting / scaling Default is Inf

periodicboolean

True if the pulse generator produces periodic pulses

randomboolean

True if the pulse generator produces random pulses

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

apply_params(params=None)[source]

Set object attributes based on the dictionary (if any) passed in the instantiation, or passed as a parameter This is called during the instantiation automatically. The key value pairs are the attribute name and value

gen_pulse()[source]

returns the pulse as an array of vales for each timeslot Must be implemented by subclass

init_pulse()[source]

Initialise the pulse parameters

reset()[source]

reset attributes to default values

class PulseGenRandom(dyn=None, params=None)[source]

Generates random pulses as simply random values for each timeslot

gen_pulse()[source]

Generate a pulse of random values between 1 and -1 Values are scaled using the scaling property and shifted using the offset property Returns the pulse as an array of vales for each timeslot

reset()[source]

reset attributes to default values

class PulseGenZero(dyn=None, params=None)[source]

Generates a flat pulse

gen_pulse()[source]

Generate a pulse with the same value in every timeslot. The value will be zero, unless the offset is not zero, in which case it will be the offset

class PulseGenLinear(dyn=None, params=None)[source]

Generates linear pulses

Attributes
gradientfloat

Gradient of the line. Note this is calculated from the start_val and end_val if these are given

start_valfloat

Start point of the line. That is the starting amplitude

end_valfloat

End point of the line. That is the amplitude at the start of the last timeslot

gen_pulse(gradient=None, start_val=None, end_val=None)[source]

Generate a linear pulse using either the gradient and start value or using the end point to calulate the gradient Note that the scaling and offset parameters are still applied, so unless these values are the default 1.0 and 0.0, then the actual gradient etc will be different Returns the pulse as an array of vales for each timeslot

init_pulse(gradient=None, start_val=None, end_val=None)[source]

Calculate the gradient if pulse is defined by start and end point values

reset()[source]

reset attributes to default values

class PulseGenPeriodic(dyn=None, params=None)[source]

Intermediate class for all periodic pulse generators All of the periodic pulses range from -1 to 1 All have a start phase that can be set between 0 and 2pi

Attributes
num_wavesfloat

Number of complete waves (cycles) that occur in the pulse. wavelen and freq calculated from this if it is given

wavelenfloat

Wavelength of the pulse (assuming the speed is 1) freq is calculated from this if it is given

freqfloat

Frequency of the pulse

start_phasefloat

Phase of the pulse signal when t=0

init_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)[source]

Calculate the wavelength, frequency, number of waves etc from the each other and the other parameters If num_waves is given then the other parameters are worked from this Otherwise if the wavelength is given then it is the driver Otherwise the frequency is used to calculate wavelength and num_waves

reset()[source]

reset attributes to default values

class PulseGenSine(dyn=None, params=None)[source]

Generates sine wave pulses

gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)[source]

Generate a sine wave pulse If no params are provided then the class object attributes are used. If they are provided, then these will reinitialise the object attribs. returns the pulse as an array of vales for each timeslot

class PulseGenSquare(dyn=None, params=None)[source]

Generates square wave pulses

gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)[source]

Generate a square wave pulse If no parameters are pavided then the class object attributes are used. If they are provided, then these will reinitialise the object attribs

class PulseGenSaw(dyn=None, params=None)[source]

Generates saw tooth wave pulses

gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)[source]

Generate a saw tooth wave pulse If no parameters are pavided then the class object attributes are used. If they are provided, then these will reinitialise the object attribs

class PulseGenTriangle(dyn=None, params=None)[source]

Generates triangular wave pulses

gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)[source]

Generate a sine wave pulse If no parameters are pavided then the class object attributes are used. If they are provided, then these will reinitialise the object attribs

class PulseGenGaussian(dyn=None, params=None)[source]

Generates pulses with a Gaussian profile

gen_pulse(mean=None, variance=None)[source]

Generate a pulse with Gaussian shape. The peak is centre around the mean and the variance determines the breadth The scaling and offset attributes are applied as an amplitude and fixed linear offset. Note that the maximum amplitude will be scaling + offset.

reset()[source]

reset attributes to default values

class PulseGenGaussianEdge(dyn=None, params=None)[source]

Generate pulses with inverted Gaussian ramping in and out It’s intended use for a ramping modulation, which is often required in experimental setups.

Attributes
decay_timefloat

Determines the ramping rate. It is approximately the time required to bring the pulse to full amplitude It is set to 1/10 of the pulse time by default

gen_pulse(decay_time=None)[source]

Generate a pulse that starts and ends at zero and 1.0 in between then apply scaling and offset The tailing in and out is an inverted Gaussian shape

reset()[source]

reset attributes to default values

class PulseGenCrab(dyn=None, num_coeffs=None, params=None)[source]

Base class for all CRAB pulse generators Note these are more involved in the optimisation process as they are used to produce piecewise control amplitudes each time new optimisation parameters are tried

Attributes
num_coeffsinteger

Number of coefficients used for each basis function

num_basis_funcsinteger

Number of basis functions In this case set at 2 and should not be changed

coeffsfloat array[num_coeffs, num_basis_funcs]

The basis coefficient values

randomize_coeffsbool

If True (default) then the coefficients are set to some random values when initialised, otherwise they will all be equal to self.scaling

estimate_num_coeffs(dim)[source]

Estimate the number coefficients based on the dimensionality of the system. :returns: num_coeffs – estimated number of coefficients :rtype: int

get_optim_var_vals()[source]

Get the parameter values to be optimised :returns: :rtype: list (or 1d array) of floats

init_coeffs(num_coeffs=None)[source]

Generate the initial ceofficent values.

Parameters
num_coeffsinteger

Number of coefficients used for each basis function If given this overides the default and sets the attribute of the same name.

init_pulse(num_coeffs=None)[source]

Set the initial freq and coefficient values

reset()[source]

reset attributes to default values

set_optim_var_vals(param_vals)[source]

Set the values of the any of the pulse generation parameters based on new values from the optimisation method Typically this will be the basis coefficients

class PulseGenCrabFourier(dyn=None, num_coeffs=None, params=None)[source]

Generates a pulse using the Fourier basis functions, i.e. sin and cos

Attributes
freqsfloat array[num_coeffs]

Frequencies for the basis functions

randomize_freqsbool

If True (default) the some random offset is applied to the frequencies

gen_pulse(coeffs=None)[source]

Generate a pulse using the Fourier basis with the freqs and coeffs attributes.

Parameters
coeffsfloat array[num_coeffs, num_basis_funcs]

The basis coefficient values If given this overides the default and sets the attribute of the same name.

init_freqs()[source]

Generate the frequencies These are the Fourier harmonics with a uniformly distributed random offset

init_pulse(num_coeffs=None)[source]

Set the initial freq and coefficient values

reset()[source]

reset attributes to default values

class Stats[source]

Base class for all optimisation statistics Used for configurations where all timeslots are updated each iteration e.g. exact gradients Note that all times are generated using timeit.default_timer() and are in seconds

Attributes
dyn_gen_namestring

Text used in some report functions. Makes sense to set it to ‘Hamiltonian’ when using unitary dynamics Default is simply ‘dynamics generator’

num_iterinteger

Number of iterations of the optimisation algorithm

wall_time_optim_startfloat

Start time for the optimisation

wall_time_optim_endfloat

End time for the optimisation

wall_time_optimfloat

Time elasped during the optimisation

wall_time_dyn_gen_computefloat

Total wall (elasped) time computing combined dynamics generator (for example combining drift and control Hamiltonians)

wall_time_prop_computefloat

Total wall (elasped) time computing propagators, that is the time evolution from one timeslot to the next Includes calculating the propagator gradient for exact gradients

wall_time_fwd_prop_computefloat

Total wall (elasped) time computing combined forward propagation, that is the time evolution from the start to a specific timeslot. Excludes calculating the propagators themselves

wall_time_onwd_prop_computefloat

Total wall (elasped) time computing combined onward propagation, that is the time evolution from a specific timeslot to the end time. Excludes calculating the propagators themselves

wall_time_gradient_computefloat

Total wall (elasped) time computing the fidelity error gradient. Excludes calculating the propagator gradients (in exact gradient methods)

num_fidelity_func_callsinteger

Number of calls to fidelity function by the optimisation algorithm

num_grad_func_callsinteger

Number of calls to gradient function by the optimisation algorithm

num_tslot_recomputeinteger

Number of time the timeslot evolution is recomputed (It is only computed if any amplitudes changed since the last call)

num_fidelity_computesinteger

Number of time the fidelity is computed (It is only computed if any amplitudes changed since the last call)

num_grad_computesinteger

Number of time the gradient is computed (It is only computed if any amplitudes changed since the last call)

num_ctrl_amp_updatesinteger

Number of times the control amplitudes are updated

mean_num_ctrl_amp_updates_per_iterfloat

Mean number of control amplitude updates per iteration

num_timeslot_changesinteger

Number of times the amplitudes of a any control in a timeslot changes

mean_num_timeslot_changes_per_updatefloat

Mean average number of timeslot amplitudes that are changed per update

num_ctrl_amp_changesinteger

Number of times individual control amplitudes that are changed

mean_num_ctrl_amp_changes_per_updatefloat

Mean average number of control amplitudes that are changed per update

calculate()[source]

Perform the calculations (e.g. averages) that are required on the stats Should be called before calling report

report()[source]

Print a report of the stats to the console

class Dump[source]

A container for dump items. The lists for dump items is depends on the type Note: abstract class

Attributes
parentsome control object (Dynamics or Optimizer)

aka the host. Object that generates the data that is dumped and is host to this dump object.

dump_dirstr

directory where files (if any) will be written out the path and be relative or absolute use ~/ to specify user home directory Note: files are only written when write_to_file is True of writeout is called explicitly Defaults to ~/.qtrl_dump

levelstring

The level of data dumping that will occur.

write_to_filebool

When set True data and summaries (as configured) will be written interactively to file during the processing Set during instantiation by the host based on its dump_to_file attrib

dump_file_extstr

Default file extension for any file names that are auto generated

fname_basestr

First part of any auto generated file names. This is usually overridden in the subclass

dump_summarybool

If True a summary is recorded each time a new item is added to the the dump. Default is True

summary_sepstr

delimiter for the summary file. default is a space

data_sepstr

delimiter for the data files (arrays saved to file). default is a space

summary_filestr

File path for summary file. Automatically generated. Can be set specifically

create_dump_dir()[source]

Checks dump directory exists, creates it if not

property level

The level of data dumping that will occur.

SUMMARY

A summary will be recorded

FULL

All possible dumping

CUSTOM

Some customised level of dumping

When first set to CUSTOM this is equivalent to SUMMARY. It is then up to the user to specify what specifically is dumped

class OptimDump(optim, level='SUMMARY')[source]

A container for dumps of optimisation data generated during the pulse optimisation.

Attributes
dump_summarybool

When True summary items are appended to the iter_summary

iter_summarylist of qutip.control.optimizer.OptimIterSummary

Summary at each iteration

dump_fid_errbool

When True values are appended to the fid_err_log

fid_err_loglist of float

Fidelity error at each call of the fid_err_func

dump_grad_normbool

When True values are appended to the fid_err_log

grad_norm_loglist of float

Gradient norm at each call of the grad_norm_log

dump_gradbool

When True values are appended to the grad_log

grad_loglist of ndarray

Gradients at each call of the fid_grad_func

add_iter_summary()[source]

add copy of current optimizer iteration summary

property dump_all

True if everything (ignoring the summary) is to be dumped

property dump_any

True if anything other than the summary is to be dumped

update_fid_err_log(fid_err)[source]

add an entry to the fid_err log

update_grad_log(grad)[source]

add an entry to the grad log

update_grad_norm_log(grad_norm)[source]

add an entry to the grad_norm log

writeout(f=None)[source]

write all the logs and the summary out to file(s)

Parameters
ffilename or filehandle

If specified then all summary and object data will go in one file. If None is specified then type specific files will be generated in the dump_dir If a filehandle is specified then it must be a byte mode file as numpy.savetxt is used, and requires this.

class DynamicsDump(dynamics, level='SUMMARY')[source]

A container for dumps of dynamics data. Mainly time evolution calculations.

Attributes
dump_summarybool

If True a summary is recorded

evo_summarylist of tslotcomp.EvoCompSummary

Summary items are appended if dump_summary is True at each recomputation of the evolution.

dump_ampsbool

If True control amplitudes are dumped

dump_dyn_genbool

If True the dynamics generators (Hamiltonians) are dumped

dump_propbool

If True propagators are dumped

dump_prop_gradbool

If True propagator gradients are dumped

dump_fwd_evobool

If True forward evolution operators are dumped

dump_onwd_evobool

If True onward evolution operators are dumped

dump_onto_evobool

If True onto (or backward) evolution operators are dumped

evo_dumpslist of EvoCompDumpItem

A new dump item is appended at each recomputation of the evolution. That is if any of the calculation objects are to be dumped.

add_evo_comp_summary(dump_item_idx=None)[source]

add copy of current evo comp summary

add_evo_dump()[source]

Add dump of current time evolution generating objects

property dump_all

True if all of the calculation objects are to be dumped

property dump_any

True if any of the calculation objects are to be dumped

writeout(f=None)[source]

Write all the dump items and the summary out to file(s).

Parameters
ffilename or filehandle

If specified then all summary and object data will go in one file. If None is specified then type specific files will be generated in the dump_dir. If a filehandle is specified then it must be a byte mode file as numpy.savetxt is used, and requires this.

class DumpItem[source]

An item in a dump list

class EvoCompDumpItem(dump)[source]

A copy of all objects generated to calculate one time evolution. Note the attributes are only set if the corresponding DynamicsDump dump_* attribute is set.

writeout(f=None)[source]

write all the objects out to files

Parameters
ffilename or filehandle

If specified then all object data will go in one file. If None is specified then type specific files will be generated in the dump_dir If a filehandle is specified then it must be a byte mode file as numpy.savetxt is used, and requires this.

class DumpSummaryItem[source]

A summary of the most recent iteration. Abstract class only.

Attributes
idxint

Index in the summary list in which this is stored