Classes¶
Qobj¶
-
class
Qobj
(inpt=None, dims=[[], []], shape=[], type=None, isherm=None, copy=True, fast=False, superrep=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 shapelist
as arguments.- Parameters
- inptarray_like
Data for vector/matrix representation of the quantum object.
- dimslist
Dimensions of object used for tensor products.
- shapelist
Shape of underlying data structure (matrix shape).
- copybool
Flag specifying whether Qobj should get a copy of the input data, or use the original.
- fastbool
Flag for fast qobj creation when running ode solvers. This parameter is used internally only.
- 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.
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
(self)[source]¶ Check if the quantum object is hermitian.
- Returns
- ishermbool
Returns the new value of isherm property.
-
cosm
(self)[source]¶ Cosine of a quantum operator.
Operator must be square.
- Returns
- oper
qutip.Qobj
Matrix cosine of operator.
- oper
- Raises
- TypeError
Quantum object is not square.
Notes
Uses the Q.expm() method.
-
diag
(self)[source]¶ Diagonal elements of quantum object.
- Returns
- diagsarray
Returns array of
real
values if operators is Hermitian, otherwisecomplex
values are returned.
-
dnorm
(self, B=None)[source]¶ Calculates the diamond norm, or the diamond distance to another operator.
- Parameters
- B
qutip.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.
- B
- Returns
- dfloat
Either the diamond norm of this operator, or the diamond distance from this operator to B.
-
eigenenergies
(self, 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
(self, sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000)[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).
- 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.
-
eliminate_states
(self, states_inds, normalize=False)[source]¶ Creates a new quantum object with states in state_inds eliminated.
- Parameters
- states_indslist of integer
The states that should be removed.
- normalizeTrue / False
Weather or not the new Qobj instance should be normalized (default is False). For Qobjs that represents density matrices or state vectors normalized should probably be set to True, but for Qobjs that represents operators in for example an Hamiltonian, normalize should be False.
- Returns
- q
qutip.Qobj
A new instance of
qutip.Qobj
that contains only the states corresponding to indices that are not in state_inds.
- q
Notes
Experimental.
-
static
evaluate
(qobj_list, t, args)[source]¶ Evaluate a time-dependent quantum object in list format. For example,
qobj_list = [H0, [H1, func_t]]
is evaluated to
Qobj(t) = H0 + H1 * func_t(t, args)
and
qobj_list = [H0, [H1, ‘sin(w * t)’]]
is evaluated to
Qobj(t) = H0 + H1 * sin(args[‘w’] * t)
- Parameters
- qobj_listlist
A nested list of Qobj instances and corresponding time-dependent coefficients.
- tfloat
The time for which to evaluate the time-dependent Qobj instance.
- argsdictionary
A dictionary with parameter values required to evaluate the time-dependent Qobj intance.
- Returns
- output
qutip.Qobj
A Qobj instance that represents the value of qobj_list at time t.
- output
-
expm
(self, method='dense')[source]¶ Matrix exponential of quantum operator.
Input operator must be square.
- Parameters
- methodstr {‘dense’, ‘sparse’}
Use set method to use to calculate the matrix exponentiation. The available choices includes ‘dense’ and ‘sparse’. Since the exponential of a matrix is nearly always dense, method=’dense’ is set as default.s
- Returns
- oper
qutip.Qobj
Exponentiated quantum operator.
- oper
- Raises
- TypeError
Quantum operator is not square.
-
extract_states
(self, states_inds, normalize=False)[source]¶ Qobj with states in state_inds only.
- Parameters
- states_indslist of integer
The states that should be kept.
- normalizeTrue / False
Weather or not the new Qobj instance should be normalized (default is False). For Qobjs that represents density matrices or state vectors normalized should probably be set to True, but for Qobjs that represents operators in for example an Hamiltonian, normalize should be False.
- Returns
- q
qutip.Qobj
A new instance of
qutip.Qobj
that contains only the states corresponding to the indices in state_inds.
- q
Notes
Experimental.
-
full
(self, 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
(self, 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.
- eigvec
qutip.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.
-
matrix_element
(self, bra, ket)[source]¶ Calculates a matrix element.
Gives the matrix element for the quantum object sandwiched between a bra and ket vector.
- Parameters
- bra
qutip.Qobj
Quantum object of type ‘bra’ or ‘ket’
- ket
qutip.Qobj
Quantum object of type ‘ket’.
- bra
- Returns
- elemcomplex
Complex valued matrix element.
-
norm
(self, norm=None, sparse=False, tol=0, maxiter=100000)[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 and argument.
- Parameters
- normstr
Which norm to use for ket/bra vectors: L2 ‘l2’, max norm ‘max’, or for operators: trace ‘tr’, Frobius ‘fro’, one ‘one’, or max ‘max’.
- sparsebool
Use sparse eigenvalue solver for trace norm. Other norms are not affected by this parameter.
- tolfloat
Tolerance for sparse solver (if used) for trace norm. The sparse solver may not converge if the tolerance is set too low.
- maxiterint
Maximum number of iterations performed by sparse solver (if used) for trace norm.
- Returns
- normfloat
The requested norm of the operator or state quantum object.
Notes
The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it.
-
overlap
(self, 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
- other
qutip.Qobj
Quantum object for a state vector of type ‘ket’, ‘bra’ or density matrix.
- other
- Returns
- overlapcomplex
Complex valued overlap.
- Raises
- TypeError
Can only calculate overlap between a bra, ket and density matrix quantum objects.
Notes
Since QuTiP mainly deals with ket vectors, the most efficient inner product call is the ket-ket version that computes the product <self|other> with both vectors expressed as kets.
-
permute
(self, order)[source]¶ Permutes a composite quantum object.
- Parameters
- orderlist/array
List specifying new tensor order.
- Returns
- P
qutip.Qobj
Permuted quantum object.
- P
-
proj
(self)[source]¶ Form the projector from a given ket or bra vector.
- Parameters
- Q
qutip.Qobj
Input bra or ket vector
- Q
- Returns
- P
qutip.Qobj
Projection operator.
- P
-
ptrace
(self, sel)[source]¶ Partial trace of the quantum object.
- Parameters
- selint/list
An
int
orlist
of components to keep after partial trace.
- Returns
- oper
qutip.Qobj
Quantum object representing partial trace with selected components remaining.
- oper
Notes
This function is identical to the
qutip.qobj.ptrace
function that has been deprecated.
-
sinm
(self)[source]¶ Sine of a quantum operator.
Operator must be square.
- Returns
- oper
qutip.Qobj
Matrix sine of operator.
- oper
- Raises
- TypeError
Quantum object is not square.
Notes
Uses the Q.expm() method.
-
sqrtm
(self, 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
- oper
qutip.Qobj
Matrix square root of operator.
- oper
- 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
(self, atol=1e-12)[source]¶ Removes small elements from the quantum object.
- Parameters
- atolfloat
Absolute tolerance used by tidyup. Default is set via qutip global settings parameters.
- Returns
- oper
qutip.Qobj
Quantum object with small elements removed.
- oper
-
tr
(self)[source]¶ Trace of a quantum object.
- Returns
- tracefloat
Returns
real
if operator is Hermitian, returnscomplex
otherwise.
-
trans
(self)[source]¶ Transposed operator.
- Returns
- oper
qutip.Qobj
Transpose of input operator.
- oper
-
transform
(self, inpt, inverse=False, sparse=True)[source]¶ Basis transform defined by input array.
Input array can be a
matrix
defining the transformation, or alist
of kets that defines the new basis.- Parameters
- inptarray_like
A
matrix
orlist
of kets defining the transformation.- inversebool
Whether to return inverse transformation.
- sparsebool
Use sparse matrices when possible. Can be slower.
- Returns
- oper
qutip.Qobj
Operator in new basis.
- oper
Notes
This function is still in development.
-
trunc_neg
(self, 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
- oper
qutip.Qobj
A valid density operator.
- oper
-
unit
(self, inplace=False, norm=None, sparse=False, tol=0, maxiter=100000)[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.
- sparsebool
Use sparse eigensolver for trace norm. Does not affect other norms.
- tolfloat
Tolerance used by sparse eigensolver.
- maxiterint
Number of maximum iterations performed by sparse eigensolver.
- Returns
- oper
qutip.Qobj
Normalized quantum object if not in-place, else None.
- oper
QobjEvo¶
-
class
QobjEvo
(Q_object=[], args={}, tlist=None, copy=True)[source]¶ A class for representing time-dependent quantum objects, such as quantum operators and states.
The QobjEvo class is a representation of time-dependent Qutip quantum objects (Qobj). This class implements math operations :
+,- : QobjEvo, Qobj * : Qobj, C-number / : C-number
and some common linear operator/state operations. The QobjEvo are constructed from a nested list of Qobj with their time-dependent coefficients. The time-dependent coefficients are either a funciton, a string or a numpy array.
For function format, the function signature must be f(t, args). Examples
- def f1_t(t, args):
return np.exp(-1j * t * args[“w1”])
- def f2_t(t, args):
return np.cos(t * args[“w2”])
H = QobjEvo([H0, [H1, f1_t], [H2, f2_t]], args={“w1”:1., “w2”:2.})
For string based coeffients, the string must be a compilable python code resulting in a complex. The following symbols are defined:
sin cos tan asin acos atan pi sinh cosh tanh asinh acosh atanh exp log log10 erf zerf sqrt real imag conj abs norm arg proj numpy as np, and scipy.special as spe.
- Examples
- H = QobjEvo([H0, [H1, ‘exp(-1j*w1*t)’], [H2, ‘cos(w2*t)’]],
args={“w1”:1.,”w2”:2.})
For numpy array format, the array must be an 1d of dtype float or complex. A list of times (float64) at which the coeffients must be given (tlist). The coeffients array must have the same len as the tlist. The time of the tlist do not need to be equidistant, but must be sorted. Examples
tlist = np.logspace(-5,0,100) H = QobjEvo([H0, [H1, np.exp(-1j*tlist)], [H2, np.cos(2.*tlist)]],
tlist=tlist)
args is a dict of (name:object). The name must be a valid variables string. Some solvers support arguments that update at each call: sesolve, mesolve, mcsolve:
- state can be obtained with:
name+”=vec”:Qobj => args[name] == state as 1D np.ndarray name+”=mat”:Qobj => args[name] == state as 2D np.ndarray name+”=Qobj”:Qobj => args[name] == state as Qobj
This Qobj is the initial value.
- expectation values:
name+”=expect”:O (Qobj/QobjEvo) => args[name] == expect(O, state) expect is <phi|O|psi> or tr(state * O) depending on state dimensions
- mcsolve:
- collapse can be obtained with:
name+”=collapse”:list => args[name] == list of collapse each collapse will be appended to the list as (time, which c_ops)
Mixing the formats is possible, but not recommended. Mixing tlist will cause problem.
- Parameters
- QobjEvo(Q_object=[], args={}, tlist=None)
- Q_objectarray_like
Data for vector/matrix representation of the quantum object.
- argsdictionary that contain the arguments for
- tlistarray_like
List of times at which the numpy-array coefficients are applied. Times must be equidistant and start from 0.
- Attributes
- cteQobj
Constant part of the QobjEvo
- opslist
List of Qobj and the coefficients. [(Qobj, coefficient as a function, original coefficient,
type, local arguments ), … ]
- type :
1: function 2: string 3: np.array 4: Cubic_Spline
- argsmap
arguments of the coefficients
- tlistarray_like
List of times at which the numpy-array coefficients are applied.
- compiledint
Has the cython version of the QobjEvo been created
- compiled_qobjevocy_qobj (CQobjCte or CQobjEvoTd)
Cython version of the QobjEvo
- dummy_ctebool
is self.cte a dummy Qobj
- constbool
Indicates if quantum object is Constant
- typeint
- information about the type of coefficient
“string”, “func”, “array”, “spline”, “mixed_callable”, “mixed_compilable”
- num_objint
number of Qobj in the QobjEvo : len(ops) + (1 if not dummy_cte)
Methods
copy() :
Create copy of Qobj
arguments(new_args):
Update the args of the object
Math:
+/- QobjEvo, Qobj, scalar: Addition is possible between QobjEvo and with Qobj or scalar -: Negation operator * Qobj, scalar: Product is possible with Qobj or scalar / scalar: It is possible to divide by scalar only
conj()
Return the conjugate of quantum object.
dag()
Return the adjoint (dagger) of quantum object.
trans()
Return the transpose of quantum object.
norm()
Return self.dag() * self. Only possible if num_obj == 1
permute(order)
Returns composite qobj with indices reordered.
ptrace(sel)
Returns quantum object for selected dimensions after performing partial trace.
apply(f, *args, **kw_args)
Apply the function f to every Qobj. f(Qobj) -> Qobj Return a modified QobjEvo and let the original one untouched
apply_decorator(decorator, *args, str_mod=None,
inplace_np=False, **kw_args): Apply the decorator to each function of the ops. The *args and **kw_args are passed to the decorator. new_coeff_function = decorator(coeff_function, *args, **kw_args) str_mod : list of 2 elements replace the string : str_mod[0] + original_string + str_mod[1] *exemple: str_mod = [“exp(“,”)”] inplace_np: Change the numpy array instead of applying the decorator to the function reading the array. Some decorators create incorrect array. Transformations f’(t) = f(g(t)) create a missmatch between the array and the associated time list.
tidyup(atol=1e-12)
Removes small elements from quantum object.
compress():
Merge ops which are based on the same quantum object and coeff type.
compile(code=False, matched=False, dense=False, omp=0):
Create the associated cython object for faster usage. code: return the code generated for compilation of the strings. matched: the compiled object use sparse matrix with matching indices. (experimental, no real advantage) dense: the compiled object use dense matrix. omp: (int) number of thread: the compiled object use spmvpy_openmp.
__call__(t, data=False, state=None, args={}):
Return the Qobj at time t. *Faster after compilation
mul_mat(t, mat):
Product of this at t time with the dense matrix mat. *Faster after compilation
mul_vec(t, psi):
Apply the quantum object (if operator, no check) to psi. More generaly, return the product of the object at t with psi. *Faster after compilation
expect(t, psi, herm=False):
Calculates the expectation value for the quantum object (if operator, no check) and state psi. Return only the real part if herm. *Faster after compilation
to_list():
Return the time-dependent quantum object as a list
eseries¶
-
class
eseries
(q=None, s=array([], dtype=float64))[source]¶ Class representation of an exponential-series expansion of time-dependent quantum objects.
- Attributes
- amplndarray
Array of amplitudes for exponential series.
- ratesndarray
Array of rates for exponential series.
- dimslist
Dimensions of exponential series components
- shapelist
Shape corresponding to exponential series components
Methods
value(tlist)
Evaluate an exponential series at the times listed in tlist
spec(wlist)
Evaluate the spectrum of an exponential series at frequencies in wlist.
tidyup()
Returns a tidier version of the exponential series
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
- axesinstance {None}
User supplied Matplotlib axes for Bloch sphere animation.
- figinstance {None}
User supplied Matplotlib Figure instance for plotting Bloch sphere.
- font_colorstr {‘black’}
Color of font used for Bloch sphere labels.
- font_sizeint {20}
Size of font used for Bloch sphere labels.
- frame_alphafloat {0.1}
Sets transparency of Bloch sphere frame.
- frame_colorstr {‘gray’}
Color of sphere wireframe.
- frame_widthint {1}
Width of wireframe.
- point_colorlist {[“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 {[“o”,”s”,”d”,”^”]}
List of point marker shapes to cycle through.
- point_sizelist {[25,32,35,45]}
List of point marker sizes. Note, not all point markers look the same size when plotted!
- sphere_alphafloat {0.2}
Transparency of Bloch sphere itself.
- sphere_colorstr {‘#FFDDDD’}
Color of Bloch sphere.
- figsizelist {[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 {5}
Width of displayed vectors.
- vector_stylestr {‘-|>’, ‘simple’, ‘fancy’, ‘’}
Vector arrowhead style (from matplotlib’s arrow style).
- vector_mutationint {20}
Width of vectors arrowhead.
- viewlist {[-60,30]}
Azimuthal and Elevation viewing angles.
- xlabellist {[“$x$”,”“]}
List of strings corresponding to +x and -x axes labels, respectively.
- xlposlist {[1.1,-1.1]}
Positions of +x and -x labels respectively.
- ylabellist {[“$y$”,”“]}
List of strings corresponding to +y and -y axes labels, respectively.
- ylposlist {[1.2,-1.2]}
Positions of +y and -y labels respectively.
- zlabellist {[r’$\left|0\right>$’,r’$\left|1\right>$’]}
List of strings corresponding to +z and -z axes labels, respectively.
- zlposlist {[1.2,-1.2]}
Positions of +z and -z labels respectively.
-
add_annotation
(self, 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/unicode
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_points
(self, points, meth='s')[source]¶ Add a list of data points to bloch sphere.
- Parameters
- pointsarray/list
Collection of data points.
- methstr {‘s’, ‘m’, ‘l’}
Type of points to plot, use ‘m’ for multicolored, ‘l’ for points connected with a line.
-
add_states
(self, state, kind='vector')[source]¶ Add a state vector Qobj to Bloch sphere.
- Parameters
- stateqobj
Input state vector.
- kindstr {‘vector’,’point’}
Type of object to plot.
-
add_vectors
(self, vectors)[source]¶ Add a list of vectors to Bloch sphere.
- Parameters
- vectorsarray_like
Array with vectors of unit length or smaller.
-
render
(self, fig=None, axes=None)[source]¶ Render the Bloch sphere and its data sets in on given figure and axes.
-
save
(self, name=None, format='png', dirc=None)[source]¶ Saves Bloch sphere to file of type
format
in directorydirc
.- 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.
- Returns
- File containing plot of Bloch sphere.
-
set_label_convention
(self, convention)[source]¶ Set x, y and z labels according to one of conventions.
- Parameters
- conventionstring
One of the following:
“original”
“xyz”
“sx sy sz”
“01”
“polarization jones”
“polarization jones letters” see also: http://en.wikipedia.org/wiki/Jones_calculus
“polarization stokes” see also: http://en.wikipedia.org/wiki/Stokes_parameters
-
vector_mutation
= None¶ Sets the width of the vectors arrowhead
-
vector_width
= None¶ Width of Bloch vectors, default = 5
Cubic Spline¶
-
class
Cubic_Spline
(a, b, y, alpha=0, beta=0)[source]¶ Calculates coefficients for a cubic spline interpolation of a given data set.
This function assumes that the data is sampled uniformly over a given interval.
- Parameters
- afloat
Lower bound of the interval.
- bfloat
Upper bound of the interval.
- yndarray
Function values at interval points.
- alphafloat
Second-order derivative at a. Default is 0.
- betafloat
Second-order derivative at b. Default is 0.
Notes
This object can be called like a normal function with a single or array of input points at which to evaluate the interplating function.
Habermann & Kindermann, “Multidimensional Spline Interpolation: Theory and Applications”, Comput Econ 30, 153 (2007).
- Attributes
- afloat
Lower bound of the interval.
- bfloat
Upper bound of the interval.
- coeffsndarray
Array of coeffcients defining cubic spline.
Non-Markovian Solvers¶
-
class
HEOMSolver
[source]¶ This is superclass for all solvers that use the HEOM method for calculating the dynamics evolution. There are many references for this. A good introduction, and perhaps closest to the notation used here is: DOI:10.1103/PhysRevLett.104.250401 A more canonical reference, with full derivation is: DOI: 10.1103/PhysRevA.41.6676 The method can compute open system dynamics without using any Markovian or rotating wave approximation (RWA) for systems where the bath correlations can be approximated to a sum of complex eponentials. The method builds a matrix of linked differential equations, which are then solved used the same ODE solvers as other qutip solvers (e.g. mesolve)
This class should be treated as abstract. Currently the only subclass implemented is that for the Drude-Lorentz spectral density. This covers the majority of the work that has been done using this model, and there are some performance advantages to assuming this model where it is appropriate.
There are opportunities to develop a more general spectral density code.
- Attributes
- H_sysQobj
System Hamiltonian
- coup_opQobj
Operator describing the coupling between system and bath.
- coup_strengthfloat
Coupling strength.
- temperaturefloat
Bath temperature, in units corresponding to planck
- N_cutint
Cutoff parameter for the bath
- N_expint
Number of exponential terms used to approximate the bath correlation functions
- planckfloat
reduced Planck constant
- boltzmannfloat
Boltzmann’s constant
- options
qutip.solver.Options
Generic solver options. If set to None the default options will be used
- progress_bar: BaseProgressBar
Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation.
- stats
qutip.solver.Stats
optional container for holding performance statitics If None is set, then statistics are not collected There may be an overhead in collecting statistics
- exp_coefflist of complex
Coefficients for the exponential series terms
- exp_freqlist of complex
Frequencies for the exponential series terms
-
configure
(self, H_sys, coup_op, coup_strength, temperature, N_cut, N_exp, planck=None, boltzmann=None, renorm=None, bnd_cut_approx=None, options=None, progress_bar=None, stats=None)[source]¶ Configure the solver using the passed parameters The parameters are described in the class attributes, unless there is some specific behaviour
- Parameters
- options
qutip.solver.Options
Generic solver options. If set to None the default options will be used
- progress_bar: BaseProgressBar
Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the simulation. If set to None, then the default progress bar will be used Set to False for no progress bar
- stats: :class:`qutip.solver.Stats`
Optional instance of solver.Stats, or a subclass thereof, for storing performance statistics for the solver If set to True, then the default Stats for this class will be used Set to False for no stats
- options
-
class
HSolverDL
(H_sys, coup_op, coup_strength, temperature, N_cut, N_exp, cut_freq, planck=1.0, boltzmann=1.0, renorm=True, bnd_cut_approx=True, options=None, progress_bar=None, stats=None)[source]¶ HEOM solver based on the Drude-Lorentz model for spectral density. Drude-Lorentz bath the correlation functions can be exactly analytically expressed as an infinite sum of exponentials which depend on the temperature, these are called the Matsubara terms or Matsubara frequencies
For practical computation purposes an approximation must be used based on a small number of Matsubara terms (typically < 4).
- Attributes
- cut_freqfloat
Bath spectral density cutoff frequency.
- renormbool
Apply renormalisation to coupling terms Can be useful if using SI units for planck and boltzmann
- bnd_cut_approxbool
Use boundary cut off approximation Can be
-
configure
(self, H_sys, coup_op, coup_strength, temperature, N_cut, N_exp, cut_freq, planck=None, boltzmann=None, renorm=None, bnd_cut_approx=None, options=None, progress_bar=None, stats=None)[source]¶ Calls configure from
HEOMSolver
and sets any attributes that are specific to this subclass
-
run
(self, rho0, tlist)[source]¶ Function to solve for an open quantum system using the HEOM model.
- Parameters
- rho0Qobj
Initial state (density matrix) of the system.
- tlistlist
Time over which system evolves.
- Returns
- results
qutip.solver.Result
Object storing all results from the simulation.
- results
-
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_S
qutip.Qobj
System Hamiltonian (can also be a Liouvillian)
- L1
qutip.Qobj
/ list ofqutip.Qobj
System operators coupling into the feedback loop. Can be a single operator or a list of operators.
- L2
qutip.Qobj
/ list ofqutip.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_markov
qutip.Qobj
/ list ofqutip.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.
- options
qutip.solver.Options
Generic solver options.
- H_S
-
outfieldcorr
(self, 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
- rho0
qutip.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
- c1
qutip.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)
- c2
qutip.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)
- rho0
- Returns
- : complex
expectation value of field correlation function
-
outfieldpropagator
(self, 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
- c1
qutip.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)
- c2
qutip.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
(self, 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
(self, rho0, t, tau)[source]¶ Compute the reduced system density matrix \(\rho(t)\)
- Parameters
- rho0
qutip.Qobj
initial density matrix or state vector (ket)
- tfloat
current time
- taufloat
time-delay
- rho0
- 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.
- options
qutip.solver.Options
Generic solver options.
- dynmapslist of
Solver Options and Results¶
-
class
Options
(atol=1e-08, rtol=1e-06, method='adams', order=12, nsteps=1000, first_step=0, max_step=0, min_step=0, average_expect=True, average_states=False, tidy=True, num_cpus=0, norm_tol=0.001, norm_t_tol=1e-06, norm_steps=5, rhs_reuse=False, rhs_filename=None, ntraj=500, gui=False, rhs_with_state=False, store_final_state=False, store_states=False, steady_state_average=False, seeds=None, normalize_output=True, use_openmp=None, openmp_threads=None)[source]¶ Class of options for evolution solvers such as
qutip.mesolve
andqutip.mcsolve
. Options can be specified either as arguments to the constructor:opts = Options(order=10, ...)
or by changing the class attributes after creation:
opts = Options() opts.order = 10
Returns options class to be used as options in evolution solvers.
- Attributes
- atolfloat {1e-8}
Absolute tolerance.
- rtolfloat {1e-6}
Relative tolerance.
- methodstr {‘adams’,’bdf’}
Integration method.
- orderint {12}
Order of integrator (<=12 ‘adams’, <=5 ‘bdf’)
- nstepsint {2500}
Max. number of internal steps/call.
- first_stepfloat {0}
Size of initial step (0 = automatic).
- min_stepfloat {0}
Minimum step size (0 = automatic).
- max_stepfloat {0}
Maximum step size (0 = automatic)
- tidybool {True,False}
Tidyup Hamiltonian and initial state by removing small terms.
- num_cpusint
Number of cpus used by mcsolver (default = # of cpus).
- norm_tolfloat
Tolerance used when finding wavefunction norm in mcsolve.
- norm_stepsint
Max. number of steps used to find wavefunction norm to within norm_tol in mcsolve.
- average_statesbool {False}
Average states values over trajectories in stochastic solvers.
- average_expectbool {True}
Average expectation values over trajectories for stochastic solvers.
- mc_corr_epsfloat {1e-10}
Arbitrarily small value for eliminating any divide-by-zero errors in correlation calculations when using mcsolve.
- ntrajint {500}
Number of trajectories in stochastic solvers.
- openmp_threadsint
Number of OPENMP threads to use. Default is number of cpu cores.
- rhs_reusebool {False,True}
Reuse Hamiltonian data.
- rhs_with_statebool {False,True}
Whether or not to include the state in the Hamiltonian function callback signature.
- rhs_filenamestr
Name for compiled Cython file.
- seedsndarray
Array containing random number seeds for mcsolver.
- store_final_statebool {False, True}
Whether or not to store the final state of the evolution in the result class.
- store_statesbool {False, True}
Whether or not to store the state vectors or density matrices in the result class, even if expectation values operators are given. If no expectation are provided, then states are stored by default and this option has no effect.
- use_openmpbool {True, False}
Use OPENMP for sparse matrix vector multiplication. Default None means auto check.
-
class
Result
[source]¶ Class for storing simulation results from any of the dynamics solvers.
- Attributes
- solverstr
Which solver was used [e.g., ‘mesolve’, ‘mcsolve’, ‘brmesolve’, …]
- timeslist/array
Times at which simulation data was collected.
- expectlist/array
Expectation values (if requested) for simulation.
- statesarray
State of the simulation (density matrix or ket) evaluated at
times
.- num_expectint
Number of expectation value operators in simulation.
- num_collapseint
Number of collapse operators in simualation.
- ntrajint/list
Number of trajectories (for stochastic solvers). A list indicates that averaging of expectation values was done over a subset of total number of trajectories.
- col_timeslist
Times at which state collpase occurred. Only for Monte Carlo solver.
- col_whichlist
Which collapse operator was responsible for each collapse in
col_times
. Only for Monte Carlo solver.
-
class
Stats
(section_names=None)[source]¶ Statistical information on the solver performance Statistics can be grouped into sections. If no section names are given in the the contructor, then all statistics will be added to one section ‘main’
- Parameters
- section_nameslist
list of keys that will be used as keys for the sections These keys will also be used as names for the sections The text in the output can be overidden by setting the header property of the section If no names are given then one section called ‘main’ is created
- Attributes
- sectionsOrderedDict of _StatsSection
These are the sections that are created automatically on instantiation or added using add_section
- headerstring
Some text that will be used as the heading in the report By default there is None
- total_timefloat
Time in seconds for the solver to complete processing Can be None, meaning that total timing percentages will be reported
Methods
add_section
(self, name)Add another section with the given name
add_count
(self, key, value[, section])Add value to count.
add_timing
(self, key, value[, section])Add value to timing.
add_message
(self, key, value[, section, sep])Add value to message.
report:
Output the statistics report to console or file.
-
add_count
(self, key, value, section=None)[source]¶ Add value to count. If key does not already exist in section then it is created with this value. If key already exists it is increased by the give value value is expected to be an integer
- Parameters
- keystring
key for the section.counts dictionary reusing a key will result in numerical addition of value
- valueint
Initial value of the count, or added to an existing count
- section: string or `class`_StatsSection
Section which to add the count to. If None given, the default (first) section will be used
-
add_message
(self, key, value, section=None, sep=';')[source]¶ Add value to message. If key does not already exist in section then it is created with this value. If key already exists the value is added to the message The value will be converted to a string
- Parameters
- keystring
key for the section.messages dictionary reusing a key will result in concatenation of value
- valueint
Initial value of the message, or added to an existing message
- sepstring
Message will be prefixed with this string when concatenating
- section: string or `class`_StatsSection
Section which to add the message to. If None given, the default (first) section will be used
-
add_section
(self, name)[source]¶ Add another section with the given name
- Parameters
- namestring
will be used as key for sections dict will also be the header for the section
- Returns
- sectionclass
The new section
-
add_timing
(self, key, value, section=None)[source]¶ Add value to timing. If key does not already exist in section then it is created with this value. If key already exists it is increased by the give value value is expected to be a float, and given in seconds.
- Parameters
- keystring
key for the section.timings dictionary reusing a key will result in numerical addition of value
- valueint
Initial value of the timing, or added to an existing timing
- section: string or `class`_StatsSection
Section which to add the timing to. If None given, the default (first) section will be used
-
report
(self, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]¶ Report the counts, timings and messages from the sections. Sections are reported in the order that the names were supplied in the constructor. The counts, timings and messages are reported in the order that they are added to the sections The output can be written to anything that supports a write method, e.g. a file or the console (default) The output is intended to in markdown format
- Parameters
- outputstream
file or console stream - anything that support write - where the output will be written
-
set_total_time
(self, value, section=None)[source]¶ Sets the total time for the complete solve or for a specific section value is expected to be a float, and given in seconds
- Parameters
- valuefloat
Time in seconds to complete the solver section
- sectionstring or class
Section which to set the total_time for If None given, the total_time for complete solve is set
-
class
StochasticSolverOptions
(me, H=None, c_ops=[], sc_ops=[], state0=None, e_ops=[], m_ops=None, store_all_expect=False, store_measurement=False, dW_factors=None, solver=None, method='homodyne', normalize=None, times=None, nsubsteps=1, ntraj=1, tol=None, generate_noise=None, noise=None, progress_bar=None, map_func=None, map_kwargs=None, args={}, options=None, noiseDepth=20)[source]¶ Class of options for stochastic solvers such as
qutip.stochastic.ssesolve
,qutip.stochastic.smesolve
, etc.The stochastic solvers
qutip.stochastic.general_stochastic
,qutip.stochastic.ssesolve
,qutip.stochastic.smesolve
,qutip.stochastic.photocurrent_sesolve
andqutip.stochastic.photocurrent_mesolve
all take the same keyword arguments as the constructor of these class, and internally they use these arguments to construct an instance of this class, so it is rarely needed to explicitly create an instance of this class.- Attributes
- H
qutip.Qobj
, time-dependent Qobj as a list* System Hamiltonian.
- state0
qutip.Qobj
Initial state vector (ket) or density matrix.
- timeslist / array
List of times for \(t\). Must be uniformly spaced.
- c_opslist of
qutip.Qobj
,qutip.QobjEvo
or [Qobj, coeff*] List of deterministic collapse operators.
- sc_opslist of
qutip.Qobj
,qutip.QobjEvo
or [Qobj, coeff*] List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the equation of motion according to how the d1 and d2 functions are defined.
- e_opslist of
qutip.Qobj
Single operator or list of operators for which to evaluate expectation values.
- m_opslist of
qutip.Qobj
List of operators representing the measurement operators. The expected format is a nested list with one measurement operator for each stochastic increament, for each stochastic collapse operator.
- argsdict
Dictionary of parameters for time dependent systems.
- tolfloat
Tolerance of the solver for implicit methods.
- ntrajint
Number of trajectors.
- nsubstepsint
Number of sub steps between each time-spep given in times.
- dW_factorsarray
Array of length len(sc_ops), containing scaling factors for each measurement operator in m_ops.
- solverstring
Name of the solver method to use for solving the stochastic equations. Valid values are: order 1/2 algorithms: ‘euler-maruyama’, ‘pc-euler’, ‘pc-euler-imp’ order 1 algorithms: ‘milstein’, ‘platen’, ‘milstein-imp’, ‘rouchon’ order 3/2 algorithms: ‘taylor1.5’, ‘taylor1.5-imp’, ‘explicit1.5’ order 2 algorithms: ‘taylor2.0’ call help of
qutip.stochastic.stochastic_solvers
for a description of the solvers. Implicit methods can adjust tolerance via the kw ‘tol’ default is {‘tol’:1e-6}- methodstring (‘homodyne’, ‘heterodyne’)
The name of the type of measurement process that give rise to the stochastic equation to solve.
- store_all_expectbool (default False)
Whether or not to store the e_ops expect values for all paths.
- store_measurementbool (default False)
Whether or not to store the measurement results in the
qutip.solver.Result
instance returned by the solver.- noiseint, array[int, 1d], array[double, 4d]
int : seed of the noise array[int, 1d], length = ntraj, seeds for each trajectories array[double, 4d] (ntraj, len(times), nsubsteps, len(sc_ops)*[1|2])
vector for the noise, the len of the last dimensions is doubled for solvers of order 1.5. The correspond to results.noise
- noiseDepthint
Number of terms kept of the truncated series used to create the noise used by taylor2.0 solver.
- normalizebool
(default True for (photo)ssesolve, False for (photo)smesolve) Whether or not to normalize the wave function during the evolution. Normalizing density matrices introduce numerical errors.
- options
qutip.solver.Options
Generic solver options. Only options.average_states and options.store_states are used.
- map_func: function
A map function or managing the calls to single-trajactory solvers.
- map_kwargs: dictionary
Optional keyword arguments to the map_func function function.
- progress_bar
qutip.ui.BaseProgressBar
Optional progress bar class instance.
- *
- time-dependent Qobj can be used for H, c_ops and sc_ops.
- The format for time-dependent system hamiltonian is:
- H = [Qobj0,[Qobj1,coeff1],[Qobj2,coeff2],…]
= Qobj0 + Qobj1 * coeff1(t) + Qobj2 * coeff2(t)
- coeff function can be:
function: coeff(t, args) -> complex str: “sin(1j*w*t)” np.array[complex, 1d] of length equal to the times array
- The argument args for the function coeff is the args keyword argument of
the stochastic solver.
- Likewisem in str cases, the parameters (‘w’ in this case) are taken from
the args keywords argument.
- *While mixing coeff type does not results in errors, it is not recommended.*
- For the collapse operators (c_ops, sc_ops):
- Each operators can only be composed of 1 Qobj.
- c_ops = [c_op1, c_op2, …]
- where, c_opN = Qobj or [Qobj,coeff]
- The coeff format is the same as for the Hamiltonian.
- H
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.
- hamiltonian
qutip.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
- Attributes
- N: int
The number of two-level systems.
- hamiltonian
qutip.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
(self)[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
(self)[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
(self)[source]¶ Build the Lindbladian superoperator of the dissipative dynamics.
- Returns
- lindbladian
qutip.Qobj
The Lindbladian matrix as a qutip.Qobj.
- lindbladian
-
liouvillian
(self)[source]¶ Build the total Liouvillian using the Dicke basis.
- Returns
- liouv
qutip.Qobj
The Liouvillian matrix for the system.
- liouv
-
pisolve
(self, initial_state, tlist, options=None)[source]¶ Solve for diagonal Hamiltonians and initial states faster.
- Parameters
- initial_state
qutip.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
- options
qutip.solver.Options
The options for the solver.
- initial_state
- 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
(self, 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
(self, 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
(self)[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
(self, 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
(self, rho0, tlist, options=None)[source]¶ Solve the ODE for the evolution of diagonal states and Hamiltonians.
-
tau_valid
(self, 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
(self, 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
(self, 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
(self, 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
TwoModeQuadratureCorrelation
(state=None, theta1=0.0, theta2=0.0, extent=[[-5, 5], [-5, 5]], steps=250)[source]¶ -
update
(self, state)[source]¶ calculate probability distribution for quadrature measurement outcomes given a two-mode wavefunction or density matrix
-
Quantum information processing¶
-
class
Gate
(name, targets=None, controls=None, arg_value=None, arg_label=None)[source]¶ Representation of a quantum gate, with its required parametrs, and target and control qubits.
- Parameters
- namestring
Gate name.
- targetslist or int
Gate targets.
- controlslist or int
Gate controls.
- arg_valuefloat
Argument value(phi).
- arg_labelstring
Label for gate representation.
-
class
QubitCircuit
(N, input_states=None, output_states=None, reverse_states=True, user_gates=None)[source]¶ Representation of a quantum program/algorithm, maintaining a sequence of gates.
- Parameters
- Nint
Number of qubits in the system.
- user_gatesdict
Define a dictionary of the custom gates. See examples for detail.
- input_stateslist
A list of string such as 0,’+’, “A”, “Y”. Only used for latex.
Examples
>>> def user_gate(): ... mat = np.array([[1., 0], ... [0., 1.j]]) ... return Qobj(mat, dims=[[2], [2]]) >>> qc.QubitCircuit(2, user_gates={"T":user_gate}) >>> qc.add_gate("T", targets=[0])
-
add_1q_gate
(self, name, start=0, end=None, qubits=None, arg_value=None, arg_label=None)[source]¶ Adds a single qubit gate with specified parameters on a variable number of qubits in the circuit. By default, it applies the given gate to all the qubits in the register.
- Parameters
- namestring
Gate name.
- startint
Starting location of qubits.
- endint
Last qubit for the gate.
- qubitslist
Specific qubits for applying gates.
- arg_valuefloat
Argument value(phi).
- arg_labelstring
Label for gate representation.
-
add_circuit
(self, qc, start=0)[source]¶ Adds a block of a qubit circuit to the main circuit. Globalphase gates are not added.
- Parameters
- qcQubitCircuit
The circuit block to be added to the main circuit.
- startint
The qubit on which the first gate is applied.
-
add_gate
(self, gate, targets=None, controls=None, arg_value=None, arg_label=None, index=None)[source]¶ Adds a gate with specified parameters to the circuit.
- Parameters
- gate: string or `Gate`
Gate name. If gate is an instance of Gate, parameters are unpacked and added.
- targets: list
Gate targets.
- controls: list
Gate controls.
- arg_value: float
Argument value(phi).
- arg_label: string
Label for gate representation.
- indexlist
Positions to add the gate.
-
add_state
(self, state, targets=None, state_type='input')[source]¶ Add an input or ouput state to the circuit. By default all the input and output states will be initialized to None. A particular state can be added by specifying the state and the qubit where it has to be added along with the type as input or output.
- Parameters
- state: str
The state that has to be added. It can be any string such as 0, ‘+’, “A”, “Y”
- targets: list
A list of qubit positions where the given state has to be added.
- state_type: str
One of either “input” or “output”. This specifies whether the state to be added is an input or output. default: “input”
-
adjacent_gates
(self)[source]¶ Method to resolve two qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions.
- Returns
- qcQubitCircuit
Return QubitCircuit of the gates for the qubit circuit with the resolved non-adjacent gates.
-
propagators
(self)[source]¶ Propagator matrix calculator for N qubits returning the individual steps as unitary matrices operating from left to right.
- Returns
- U_listlist
Return list of unitary matrices for the qubit circuit.
-
remove_gate
(self, index=None, end=None, name=None, remove='first')[source]¶ Remove a gate from a specific index or between two indexes or the first, last or all instances of a particular gate.
- Parameters
- indexint
Location of gate to be removed.
- namestring
Gate name to be removed.
- removestring
If first or all gate are to be removed.
-
resolve_gates
(self, basis=['CNOT', 'RX', 'RY', 'RZ'])[source]¶ Unitary matrix calculator for N qubits returning the individual steps as unitary matrices operating from left to right in the specified basis.
- Parameters
- basislist.
Basis of the resolved circuit.
- Returns
- qcQubitCircuit
Return QubitCircuit of resolved gates for the qubit circuit in the desired basis.
-
class
CircuitProcessor
(N, correct_global_phase)[source]¶ Base class for representation of the physical implementation of a quantum program/algorithm on a specified qubit system.
-
adjacent_gates
(self, qc, setup)[source]¶ Function to take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.
- Parameters
- qc: QubitCircuit
Takes the quantum circuit to be implemented.
- setup: String
Takes the nature of the spin chain; linear or circular.
- Returns
- qc: QubitCircuit
The resolved circuit representation.
-
get_ops_and_u
(self)[source]¶ Returns the Hamiltonian operators and corresponding values by stacking them together.
-
get_ops_labels
(self)[source]¶ Returns the Hamiltonian operators and corresponding labels by stacking them together.
-
load_circuit
(self, qc)[source]¶ Translates an abstract quantum circuit to its corresponding Hamiltonian for a specific model.
- Parameters
- qc: QubitCircuit
Takes the quantum circuit to be implemented.
-
optimize_circuit
(self, qc)[source]¶ Function to take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.
- Parameters
- qc: QubitCircuit
Takes the quantum circuit to be implemented.
- Returns
- qc: QubitCircuit
The optimal circuit representation.
-
plot_pulses
(self)[source]¶ Maps the physical interaction between the circuit components for the desired physical system.
- Returns
- fig, ax: Figure
Maps the physical interaction between the circuit components.
-
pulse_matrix
(self)[source]¶ Generates the pulse matrix for the desired physical system.
- Returns
- t, u, labels:
Returns the total time and label for every operation.
-
run
(self, qc=None)[source]¶ Generates the propagator matrix by running the Hamiltonian for the appropriate time duration for the desired physical system.
- Parameters
- qc: QubitCircuit
Takes the quantum circuit to be implemented.
- Returns
- U_list: list
The propagator matrix obtained from the physical implementation.
-
run_state
(self, qc=None, states=None)[source]¶ Generates the propagator matrix by running the Hamiltonian for the appropriate time duration for the desired physical system with the given initial state of the qubit register.
- Parameters
- qc: QubitCircuit
Takes the quantum circuit to be implemented.
- states: Qobj
Initial state of the qubits in the register.
- Returns
- U_list: list
The propagator matrix obtained from the physical implementation.
-
-
class
SpinChain
(N, correct_global_phase=True, sx=None, sz=None, sxsy=None)[source]¶ Representation of the physical implementation of a quantum program/algorithm on a spin chain qubit system.
-
adjacent_gates
(self, qc, setup='linear')[source]¶ Method to resolve 2 qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions for linear/circular spin chain system.
- Parameters
- qc: QubitCircuit
The circular spin chain circuit to be resolved
- setup: Boolean
Linear of Circular spin chain setup
- Returns
- qc: QubitCircuit
Returns QubitCircuit of resolved gates for the qubit circuit in the desired basis.
-
get_ops_and_u
(self)[source]¶ Returns the Hamiltonian operators and corresponding values by stacking them together.
-
-
class
LinearSpinChain
(N, correct_global_phase=True, sx=None, sz=None, sxsy=None)[source]¶ Representation of the physical implementation of a quantum program/algorithm on a spin chain qubit system arranged in a linear formation. It is a sub-class of SpinChain.
-
adjacent_gates
(self, qc)[source]¶ Method to resolve 2 qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions for linear/circular spin chain system.
- Parameters
- qc: QubitCircuit
The circular spin chain circuit to be resolved
- setup: Boolean
Linear of Circular spin chain setup
- Returns
- qc: QubitCircuit
Returns QubitCircuit of resolved gates for the qubit circuit in the desired basis.
-
-
class
CircularSpinChain
(N, correct_global_phase=True, sx=None, sz=None, sxsy=None)[source]¶ Representation of the physical implementation of a quantum program/algorithm on a spin chain qubit system arranged in a circular formation. It is a sub-class of SpinChain.
-
adjacent_gates
(self, qc)[source]¶ Method to resolve 2 qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions for linear/circular spin chain system.
- Parameters
- qc: QubitCircuit
The circular spin chain circuit to be resolved
- setup: Boolean
Linear of Circular spin chain setup
- Returns
- qc: QubitCircuit
Returns QubitCircuit of resolved gates for the qubit circuit in the desired basis.
-
-
class
DispersivecQED
(N, correct_global_phase=True, Nres=None, deltamax=None, epsmax=None, w0=None, wq=None, eps=None, delta=None, g=None)[source]¶ Representation of the physical implementation of a quantum program/algorithm on a dispersive cavity-QED system.
-
dispersive_gate_correction
(self, qc1, rwa=True)[source]¶ Method to resolve ISWAP and SQRTISWAP gates in a cQED system by adding single qubit gates to get the correct output matrix.
- Parameters
- qc: Qobj
The circular spin chain circuit to be resolved
- rwa: Boolean
Specify if RWA is used or not.
- Returns
- qc: QubitCircuit
Returns QubitCircuit of resolved gates for the qubit circuit in the desired basis.
-
get_ops_and_u
(self)[source]¶ Returns the Hamiltonian operators and corresponding values by stacking them together.
-
get_ops_labels
(self)[source]¶ Returns the Hamiltonian operators and corresponding labels by stacking them together.
-
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 that is GRAPE or CRAB
- 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
- dump
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.
dumping
stringThe 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.
- 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_summary
OptimIterSummary
Summary of the most recent iteration. Note this is only set if dummping is on
-
apply_method_params
(self, 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
(self, 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
(self, *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
(self, *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
(self, 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
(self, *args)[source]¶ Check the elapsed wall time for the optimisation run so far. Terminate if this has exceeded the maximum allowed time
-
run_optimization
(self, 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
(self, 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
(self, 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
(self, 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
-
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.
Notes
- [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
(self, 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, or (in theory) any other representaion that supports typical matrix methods (e.g. dot) ndarray performs best for smaller quantum systems. 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_ctrls
integercalculate 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_gen
List of QobjList of combined dynamics generators (Qobj) for each timeslot
prop
list of QobjList of propagators (Qobj) for each timeslot
prop_grad
array[num_tslots, num_ctrls] of QobjArray of propagator gradients (Qobj) for each timeslot, control
fwd_evo
List of QobjList of evolution operators (Qobj) from the initial to the given
onwd_evo
List of QobjList of evolution operators (Qobj) from the initial to the given
onto_evo
List of QobjList 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
- dump
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
dumping
stringThe 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
(self, 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
(self, k)[source]¶ Computes the dynamics generator for a given timeslot The is the combined Hamiltion for unitary systems
-
compute_evolution
(self)[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
-
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
(self, j)[source]¶ Get the dynamics generator for the control Not implemented in the base class. Choose a subclass
-
get_drift_dim
(self)[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
(self, k)[source]¶ Get the combined dynamics generator for the timeslot Not implemented in the base class. Choose a subclass
-
get_num_ctrls
(self)[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
(self)[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
(self, 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
-
save_amps
(self, 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
-
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
(self)[source]¶ Checks whether all propagators are unitary For propagators found not to be unitary, the potential underlying causes are investigated.
-
initialize_controls
(self, 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
(self, 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.
-
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.
-
class
PropCompDiag
(dynamics, params=None)[source]¶ Coumputes the propagator exponentiation using diagonalisation of of the dynamics generator
-
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
-
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
(self, 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.
-
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
-
compute_fid_grad
(self)[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
-
get_fid_err_gradient
(self)[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
(self)[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
(self)[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_normalization
(self)[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
(self, grad)[source]¶ Normalise the gradient matrix passed as grad This PSU version is independent of global phase
-
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
(self)[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_gradient
(self)[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)
-
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
-
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
(self, 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.
-
class
TSlotCompUpdateAll
(dynamics, params=None)[source]¶ Timeslot Computer - Update All Updates all dynamics generators, propagators and evolutions when ctrl amplitudes are updated
-
compare_amps
(self, 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
-
-
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
(self, 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
-
class
PulseGenRandom
(dyn=None, params=None)[source]¶ Generates random pulses as simply random values for each timeslot
-
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
(self, 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
-
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
(self, 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
-
class
PulseGenSine
(dyn=None, params=None)[source]¶ Generates sine wave pulses
-
gen_pulse
(self, 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
PulseGenGaussian
(dyn=None, params=None)[source]¶ Generates pulses with a Gaussian profile
-
gen_pulse
(self, 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.
-
-
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
-
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
(self, 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
(self)[source]¶ Get the parameter values to be optimised :returns: :rtype: list (or 1d array) of floats
-
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
(self, 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.
-
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
-
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
level
stringThe 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.
- 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
-
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
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
-
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
-
writeout
(self, 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 :class:`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.
-
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
(self, f=None)[source]¶ write all the dump items and the summary out to file(s) :param f: 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
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
(self, 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.
-