# Classes

## Qobj

class Qobj(inpt=None, dims=None, shape=None, type=None, isherm=None, copy=True, fast=False, superrep=None, isunitary=None)

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

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

  Parameters:
    inpt array_like

      Data for vector/matrix representation of the quantum object.

    dims list

      Dimensions of object used for tensor products.

    shape list

      Shape of underlying data structure (matrix shape).

    copy bool

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

    fast bool

      Flag for fast qobj creation when running ode solvers. This parameter is used internally only.

  Attributes:
    data array_like

      Sparse matrix characterizing the quantum object.

    dims list

      List of dimensions keeping track of the tensor structure.

    shape list

      Shape of the underlying data array.

    type str

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

    superrep str

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

    isherm bool

      Indicates if quantum object represents Hermitian operator.

    isunitary bool

      Indictaes if quantum object represents unitary operator.

    iscp bool

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

    ishp bool

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

    istp bool

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

    iscptp bool

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

    isket bool

      Indicates if the quantum object represents a ket.

    isbra bool

      Indicates if the quantum object represents a bra.

    isoper bool

      Indicates if the quantum object represents an operator.

    issuper bool

      Indicates if the quantum object represents a superoperator.

    isoperket bool

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

    isoperbra bool

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

  Methods

  copy() | Create copy of Qobj
  conj() | Conjugate of quantum object.
  cosm() | Cosine of quantum object.
  dag() | Adjoint (dagger) of quantum object.
  dnorm() | Diamond norm of quantum operator.
  dual_chan() | Dual channel of quantum object representing a CP map.
  eigenenergies(sparse=False, sort=’low’, eigvals=0, tol=0, maxiter=100000) | Returns eigenenergies (eigenvalues) of a quantum object.
  eigenstates(sparse=False, sort=’low’, eigvals=0, tol=0, maxiter=100000) | Returns eigenenergies and eigenstates of quantum object.
  expm() | Matrix exponential of quantum object.
  full(order=’C’) | Returns dense array of quantum object data attribute.
  groundstate(sparse=False, tol=0, maxiter=100000) | Returns eigenvalue and eigenket for the groundstate of a quantum object.
  inv() | Return a Qobj corresponding to the matrix inverse of the operator.
  matrix_element(bra, ket) | Returns the matrix element of operator between bra and ket vectors.
  norm(norm=’tr’, sparse=False, tol=0, maxiter=100000) | Returns norm of a ket or an operator.
  permute(order) | Returns composite qobj with indices reordered.
  proj() | Computes the projector for a ket or bra vector.
  ptrace(sel) | Returns quantum object for selected dimensions after performing partial trace.
  sinm() | Sine of quantum object.
  sqrtm() | Matrix square root of quantum object.
  tidyup(atol=1e-12) | Removes small elements from quantum object.
  tr() | Trace of quantum object.
  trans() | Transpose of quantum object.
  transform(inpt, inverse=False) | Performs a basis transformation defined by inpt matrix.
  trunc_neg(method=’clip’) | Removes negative eigenvalues and returns a new Qobj that is a valid density operator.
  unit(norm=’tr’, sparse=False, tol=0, maxiter=100000) | Returns normalized quantum object.

  check_herm()

    Check if the quantum object is hermitian.

    Returns:
      isherm bool

        Returns the new value of isherm property.

  check_isunitary()

    Checks whether qobj is a unitary matrix

  conj()

    Conjugate operator of quantum object.

  copy()

    Create identical copy

  cosm()

    Cosine of a quantum operator.

    Operator must be square.

    Returns:
      oper `qutip.Qobj`

        Matrix cosine of operator.

    Raises:
      TypeError

        Quantum object is not square.

    Notes

    Uses the Q.expm() method.

  dag()

    Adjoint operator of quantum object.

  diag()

    Diagonal elements of quantum object.

    Returns:
      diags array

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

  dnorm(B=None)

    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.

    Returns:
      d float

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

  dual_chan()

    Dual channel of quantum object representing a completely positive map.

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

    Eigenenergies of a quantum object.

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

    Parameters:
      sparse bool

        Use sparse Eigensolver

      sort str

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

      eigvals int

        Number of requested eigenvalues. Default is all eigenvalues.

      tol float

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

      maxiter int

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

    Returns:
      eigvals array

        Array of eigenvalues for operator.

    Notes

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

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

    Eigenstates and eigenenergies.

    Eigenstates and eigenenergies are defined for operators and superoperators only.

    Parameters:
      sparse bool

        Use sparse Eigensolver

      sort str

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

      eigvals int

        Number of requested eigenvalues. Default is all eigenvalues.

      tol float

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

      maxiter int

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

      phase_fix int, None

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

    Returns:
      eigvals array

        Array of eigenvalues for operator.

      eigvecs array

        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(states_inds, normalize=False)

    Creates a new quantum object with states in state_inds eliminated.

    Parameters:
      states_inds list of integer

        The states that should be removed.

      normalize True / 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.

    Notes

    Experimental.

  static evaluate(qobj_list, t, args)

    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_list list

        A nested list of Qobj instances and corresponding time-dependent coefficients.

      t float

        The time for which to evaluate the time-dependent Qobj instance.

      args dictionary

        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.

  expm(method='dense')

    Matrix exponential of quantum operator.

    Input operator must be square.

    Parameters:
      method str {‘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.

    Raises:
      TypeError

        Quantum operator is not square.

  extract_states(states_inds, normalize=False)

    Qobj with states in state_inds only.

    Parameters:
      states_inds list of integer

        The states that should be kept.

      normalize True / 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.

    Notes

    Experimental.

  full(order='C', squeeze=False)

    Dense array from quantum object.

    Parameters:
      order str {‘C’, ‘F’}

        Return array in C (default) or Fortran ordering.

      squeeze bool {False, True}

        Squeeze output array.

    Returns:
      data array

        Array of complex data from quantum objects data attribute.

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

    Ground state Eigenvalue and Eigenvector.

    Defined for quantum operators or superoperators only.

    Parameters:
      sparse bool

        Use sparse Eigensolver

      tol float

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

      maxiter int

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

      safe bool (default=True)

        Check for degenerate ground state

    Returns:
      eigval float

        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.

  inv(sparse=False)

    Matrix inverse of a quantum operator

    Operator must be square.

    Returns:
      oper `qutip.Qobj`

        Matrix inverse of operator.

    Raises:
      TypeError

        Quantum object is not square.

  matrix_element(bra, ket)

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

    Returns:
      elem complex

        Complex valued matrix element.

    Notes

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

  norm(norm=None, sparse=False, tol=0, maxiter=100000)

    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:
      norm str

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

      sparse bool

        Use sparse eigenvalue solver for trace norm. Other norms are not affected by this parameter.

      tol float

        Tolerance for sparse solver (if used) for trace norm. The sparse solver may not converge if the tolerance is set too low.

      maxiter int

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

    Returns:
      norm float

        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(other)

    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.

    Returns:
      overlap complex

        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(order)

    Permutes a composite quantum object.

    Parameters:
      order list/array

        List specifying new tensor order.

    Returns:
      P `qutip.Qobj`

        Permuted quantum object.

  proj()

    Form the projector from a given ket or bra vector.

    Parameters:
      Q `qutip.Qobj`

        Input bra or ket vector

    Returns:
      P `qutip.Qobj`

        Projection operator.

  ptrace(sel, sparse=None)

    Partial trace of the quantum object.

    Parameters:
      sel int/list

        An `int` or `list` of components to keep after partial trace. The order is unimportant; no transposition will be done and the spaces will remain in the same order in the output.

    Returns:
      oper `qutip.Qobj`

        Quantum object representing partial trace with selected components remaining.

    Notes

    This function is identical to the `qutip.qobj.ptrace` function that has been deprecated.

  purity()

    Calculate purity of a quantum object.

    Returns:
      state_purity float

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

  sinm()

    Sine of a quantum operator.

    Operator must be square.

    Returns:
      oper `qutip.Qobj`

        Matrix sine of operator.

    Raises:
      TypeError

        Quantum object is not square.

    Notes

    Uses the Q.expm() method.

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

    Sqrt of a quantum operator.

    Operator must be square.

    Parameters:
      sparse bool

        Use sparse eigenvalue/vector solver.

      tol float

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

      maxiter int

        Maximum number of iterations used by sparse solver.

    Returns:
      oper `qutip.Qobj`

        Matrix square root of operator.

    Raises:
      TypeError

        Quantum object is not square.

    Notes

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

  tidyup(atol=None)

    Removes small elements from the quantum object.

    Parameters:
      atol float

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

    Returns:
      oper `qutip.Qobj`

        Quantum object with small elements removed.

  tr()

    Trace of a quantum object.

    Returns:
      trace float

        Returns the trace of the quantum object.

  trans()

    Transposed operator.

    Returns:
      oper `qutip.Qobj`

        Transpose of input operator.

  transform(inpt, inverse=False, sparse=True)

    Basis transform defined by input array.

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

    Parameters:
      inpt array_like

        A `matrix` or `list` of kets defining the transformation.

      inverse bool

        Whether to return inverse transformation.

      sparse bool

        Use sparse matrices when possible. Can be slower.

    Returns:
      oper `qutip.Qobj`

        Operator in new basis.

    Notes

    This function is still in development.

  trunc_neg(method='clip')

    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:
      method str

        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.

  unit(inplace=False, norm=None, sparse=False, tol=0, maxiter=100000)

    Operator or state normalized to unity.

    Uses norm from Qobj.norm().

    Parameters:
      inplace bool

        Do an in-place normalization

      norm str

        Requested norm for states / operators.

      sparse bool

        Use sparse eigensolver for trace norm. Does not affect other norms.

      tol float

        Tolerance used by sparse eigensolver.

      maxiter int

        Number of maximum iterations performed by sparse eigensolver.

    Returns:
      oper `qutip.Qobj`

        Normalized quantum object if not in-place, else None.

## QobjEvo

class QobjEvo(Q_object=[], args={}, copy=True, tlist=None, state0=None, e_ops=[])

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

  Basic math operations are defined:

  - `+`, `-` : `QobjEvo`, `Qobj`, scalars.

  - `*`: `Qobj`, C number

  - `/` : C number

  This object is constructed by passing a list of `Qobj` instances, each of which may have an associated scalar time dependence. The list is summed to produce the final result. In other words, if an instance of this class is \(Q(t)\), then it is constructed from a set of constant:obj:~qutip.Qobj \(\{Q_k\}\) and time-dependent scalars \(f_k(t)\) by

  \[Q(t) = \sum_k f_k(t) Q_k\]

  If a scalar \(f_k(t)\) is not passed with a given `Qobj`, then that term is assumed to be constant. The next section contains more detail on the allowed forms of the constants, and gives several examples for how to build instances of this class.

  Time-dependence formats

  There are three major formats for specifying a time-dependent scalar:

  - Python function

  - string

  - array

  For function format, the function signature must be `f(t: float, args: dict) -> complex`, for example

      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:

      pi   exp   log   log10
      erf  zerf  norm  proj
      real imag conj abs arg
      sin  sinh  asin  asinh
      cos  cosh  acos  acosh
      tan  tanh  atan  atanh
      numpy as np
      scipy.special as spe

  A couple more simple 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 `np.float64` or `np.complex128`. A list of times (`np.float64`) at which the coeffients must be given as `tlist`. The coeffients array must have the same length as the tlist. The times of the tlist do not need to be equidistant, but must be sorted. By default, a cubic spline interpolation will be used for the coefficient at time t. If the coefficients are to be treated as step functions, use the arguments `args = {"_step_func_coeff": True}`. Examples of array-format usage are:

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

  Mixing time formats is allowed. It is not possible to create a single `QobjEvo` that contains different `tlist` values, however.

  Passing arguments

  `args` is a dict of (name: object). The name must be a valid Python identifier string, and in general the object can be any type that is supported by the code to be compiled in the string.

  There are some “magic” names that can be specified, whose objects will be overwritten when used within `sesolve`, `mesolve` and `mcsolve`. This allows access to the solvers’ internal states, and they are updated at every call. The initial values of these dictionary elements is unimportant. The magic names available are:

  - `"state"`: the current state as a `Qobj`

  - `"state_vec"`: the current state as a column-stacked 1D `np.ndarray`

  - `"state_mat"`: the current state as a 2D `np.ndarray`

  - `"expect_op_<n>"`: the current expectation value of the element `e_ops[n]`, which is an argument to the solvers. Replace `<n>` with an integer literal, e.g. `"expect_op_0"`. This will be either real- or complex-valued, depending on whether the state and operator are both Hermitian or not.

  - `"collapse"`: (`mcsolve` only) a list of the collapses that have occurred during the evolution. Each element of the list is a 2-tuple `(time: float, which: int)`, where `time` is the time this collapse happened, and `which` is an integer indexing the `c_ops` argument to `mcsolve`.

  Parameters:
    Q_object list, `Qobj` or `QobjEvo`

      The time-dependent description of the quantum object. This is of the same format as the first parameter to the general ODE solvers; in general, it is a list of `[Qobj, time_dependence]` pairs that are summed to make the whole object. The `time_dependence` can be any of the formats discussed in the previous section. If a particular term has no time-dependence, then you should just give the `Qobj` instead of the 2-element list.

    args dict, optional

      Mapping of `{str: object}`, discussed in greater detail above. The strings can be any valid Python identifier, and the objects are of the consumable types. See the previous section for details on the “magic” names used to access solver internals.

    tlist array_like, optional

      List of the times any numpy-array coefficients describe. This is used only in at least one of the time dependences in `Q_object` is given in Numpy-array format. The times must be sorted, but need not be equidistant. Values inbetween will be interpolated.

  Attributes:
    cte `Qobj`

      Constant part of the QobjEvo.

    ops list of `EvoElement`

      Internal representation of the time-dependence structure of the elements.

    args dict

      The current value of the `args` dictionary passed into the constructor.

    dynamics_args list

      Names of the dynamic arguments that the solvers will generate. These are the magic names that were found in the `args` parameter.

    tlist array_like

      List of times at which the numpy-array coefficients are applied.

    compiled str

      A string representing the properties of the low-level Cython class backing this object (may be empty).

    compiled_qobjevo `CQobjCte` or `CQobjEvoTd`

      Cython version of the QobjEvo.

    coeff_get callable

      Object called to obtain a list of all the coefficients at a particular time.

    coeff_files list

      Runtime created files to delete with the instance.

    dummy_cte bool

      Is self.cte an empty Qobj

    const bool

      Indicates if quantum object is constant

    type{“cte”, “string”, “func”, “array”, “spline”, “mixed_callable”, “mixed_compilable”}

      Information about the type of coefficients used in the entire object.

    num_obj int

      Number of `Qobj` in the QobjEvo.

    use_cython bool

      Flag to compile string to Cython or Python

    safePickle bool

      Flag to not share pointers between thread.

  apply(function, *args, **kw_args)

    Apply the linear function `function` to every `Qobj` included in this time-dependent object, and return a new `QobjEvo` with the result.

    Any additional arguments or keyword arguments will be appended to every function call.

  apply_decorator(function, *args, str_mod=None, inplace_np=False, **kw_args)

    Apply the given function to every time-dependent coefficient in the quantum object, and return a new object with the result.

    Any additional arguments and keyword arguments will be appended to the function calls.

    Parameters:
      function callable

        `(time_dependence, *args, **kwargs) -> time_dependence`. Called on each time-dependent coefficient to produce a new coefficient. The additional arguments and keyword arguments are the ones given to this function.

      str_mod list

        A 2-element list of strings, that will additionally wrap any string time-dependences. An existing time-dependence string `x` will become `str_mod[0] + x + str_mod[1]`.

      inplace_np bool, default False

        Whether this function should modify Numpy arrays inplace, or be used like a regular decorator. Some decorators create incorrect arrays as some transformations `f'(t) = f(g(t))` create a mismatch between the array and the associated time list.

  arguments(new_args)

    Update the scoped variables that were passed as `args` to new values.

  compile(code=False, matched=False, dense=False, omp=0)

    Create an associated Cython object for faster usage. This function is called automatically by the solvers.

    Parameters:
      code bool, default False

        Return the code string generated by compilation of any strings.

      matched bool, default False

        If True, the underlying sparse matrices used to represent each element of the type will have their structures unified. This may include adding explicit zeros to sparse matrices, but can be faster in some cases due to not having to deal with repeated structural mismatches.

      dense bool, default False

        Whether to swap to using dense matrices to back the data.

      omp int, optional

        The number of OpenMP threads to use when doing matrix multiplications, if QuTiP was compiled with OpenMP.

    Returns:
      compiled_str str

        (Only if code was set to True). The code-generated string of compiled calling code.

  compress()

    Merge together elements that share the same time-dependence, to reduce the number of matrix multiplications and additions that need to be done to evaluate this object.

    Modifies the object inplace.

  conj()

    Return the matrix elementwise conjugation.

  copy()

    Return a copy of this object.

  dag()

    Return the matrix conjugate-transpose (dagger).

  expect(t, state, herm=False)

    Calculate the expectation value of this operator on the given (time-independent) state at a particular time.

    This is more efficient than `expect(QobjEvo(t), state)`.

    Parameters:
      t float

        The time to evaluate this operator at.

      state Qobj or np.ndarray

        The state to take the expectation value around.

      herm bool, default False

        Whether this operator and the state are both Hermitian. If True, only the real part of the result will be returned.

    See also

    `expect`

      General-purpose expectation values.

  mul_mat(t, mat)

    Multiply this object evaluated at time t by a matrix (from the right).

    Parameters:
      t float

        The time to evaluate this object at.

      mat Qobj or np.ndarray

        The matrix that is multiplied by this object.

    Returns:
      mat: Qobj or np.ndarray

        The matrix result in the same type as the input.

  mul_vec(t, vec)

    Multiply this object evaluated at time t by a vector.

    Parameters:
      t float

        The time to evaluate this object at.

      vec Qobj or np.ndarray

        The state-vector to multiply this object by.

    Returns:
      vec: Qobj or np.ndarray

        The vector result in the same type as the input.

  permute(order)

    Permute the tensor structure of the underlying matrices into a new format.

    See also

    `Qobj.permute`

      the same operation on constant quantum objects.

  tidyup(atol=None)

    Removes small elements from this quantum object inplace.

  to_list()

    Return this operator in the list-like form used to initialised it, like can be passed to `mesolve`.

  trans()

    Return the matrix transpose.

## eseries

class eseries(q=None, s=array([], dtype=float64))

  Class representation of an exponential-series expansion of time-dependent quantum objects.

  Deprecated since version 4.6.0: `eseries` will be removed in QuTiP 5. Please use `QobjEvo` for general time-dependence.

  Attributes:
    ampl ndarray

      Array of amplitudes for exponential series.

    rates ndarray

      Array of rates for exponential series.

    dims list

      Dimensions of exponential series components

    shape list

      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

  spec(wlist)

    Evaluate the spectrum of an exponential series at frequencies in `wlist`.

    Parameters:
      wlist array_like

        Array/list of frequenies.

    Returns:
      val_list ndarray

        Values of exponential series at frequencies in `wlist`.

  tidyup(*args)

    Returns a tidier version of exponential series.

  value(tlist)

    Evaluates an exponential series at the times listed in `tlist`.

    Parameters:
      tlist ndarray

        Times at which to evaluate exponential series.

    Returns:
      val_list ndarray

        Values of exponential at times in `tlist`.

## Bloch sphere

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

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

  Attributes:
    axes matplotlib.axes.Axes

      User supplied Matplotlib axes for Bloch sphere animation.

    fig matplotlib.figure.Figure

      User supplied Matplotlib Figure instance for plotting Bloch sphere.

    font_color str, default ‘black’

      Color of font used for Bloch sphere labels.

    font_size int, default 20

      Size of font used for Bloch sphere labels.

    frame_alpha float, default 0.1

      Sets transparency of Bloch sphere frame.

    frame_color str, default ‘gray’

      Color of sphere wireframe.

    frame_width int, default 1

      Width of wireframe.

    point_color list, default [“b”, “r”, “g”, “#CC6600”]

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

    point_marker list, default [“o”, “s”, “d”, “^”]

      List of point marker shapes to cycle through.

    point_size list, default [25, 32, 35, 45]

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

    sphere_alpha float, default 0.2

      Transparency of Bloch sphere itself.

    sphere_color str, default ‘#FFDDDD’

      Color of Bloch sphere.

    figsize list, default [7, 7]

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

    vector_color list, [“g”, “#CC6600”, “b”, “r”]

      List of vector colors to cycle through.

    vector_width int, default 5

      Width of displayed vectors.

    vector_style str, default ‘-|>’

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

    vector_mutation int, default 20

      Width of vectors arrowhead.

    view list, default [-60, 30]

      Azimuthal and Elevation viewing angles.

    xlabel list, default [“$x$”, “”]

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

    xlpos list, default [1.1, -1.1]

      Positions of +x and -x labels respectively.

    ylabel list, default [“$y$”, “”]

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

    ylpos list, default [1.2, -1.2]

      Positions of +y and -y labels respectively.

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

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

    zlpos list, default [1.2, -1.2]

      Positions of +z and -z labels respectively.

  add_annotation(state_or_vector, text, **kwargs)

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

    Parameters:
      state_or_vector Qobj/array/list/tuple

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

      text str

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

      kwargs

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

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

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

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

    Parameters:
      start Qobj or array-like

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

      end Qobj or array-like

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

      fmt str, default: “b”

        A matplotlib format string for rendering the arc.

      steps int, default: None

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

      **kwargs dict

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

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

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

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

    Parameters:
      start Qobj or array-like

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

      end Qobj or array-like

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

      fmt str, default: “k”

        A matplotlib format string for rendering the line.

      **kwargs dict

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

  add_points(points, meth='s', alpha=1.0)

    Add a list of data points to bloch sphere.

    Parameters:
      points array_like

        Collection of data points.

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

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

      alpha float, default=1.

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

      .. note::

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

  add_states(state, kind='vector', alpha=1.0)

    Add a state vector Qobj to Bloch sphere.

    Parameters:
      state Qobj

        Input state vector.

      kind{‘vector’, ‘point’}

        Type of object to plot.

      alpha float, default=1.

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

  add_vectors(vectors, alpha=1.0)

    Add a list of vectors to Bloch sphere.

    Parameters:
      vectors array_like

        Array with vectors of unit length or smaller.

      alpha float, default=1.

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

  clear()

    Resets Bloch sphere data sets to empty.

  make_sphere()

    Plots Bloch sphere and data sets.

  render()

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

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

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

    Parameters:
      name str

        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.

      format str

        Format of output image.

      dirc str

        Directory for output images. Defaults to current working directory.

      dpin int

        Resolution in dots per inch.

    Returns:
      File containing plot of Bloch sphere.
  set_label_convention(convention)

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

    Parameters:
      convention string

        One of the following:

        - “original”

        - “xyz”

        - “sx sy sz”

        - “01”

        - “polarization jones”

        - “polarization jones letters” see also: https://en.wikipedia.org/wiki/Jones_calculus

        - “polarization stokes” see also: https://en.wikipedia.org/wiki/Stokes_parameters

  show()

    Display Bloch sphere and corresponding data sets.

    Notes

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

  vector_mutation

    Sets the width of the vectors arrowhead

  vector_style

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

  vector_width

    Width of Bloch vectors, default = 5

class Bloch3d(fig=None)

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

  Notes

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

  Attributes:
    fig instance {None}

      User supplied Matplotlib Figure instance for plotting Bloch sphere.

    font_color str {‘black’}

      Color of font used for Bloch sphere labels.

    font_scale float {0.08}

      Scale for font used for Bloch sphere labels.

    frame bool {True}

      Draw frame for Bloch sphere

    frame_alpha float {0.05}

      Sets transparency of Bloch sphere frame.

    frame_color str {‘gray’}

      Color of sphere wireframe.

    frame_num int {8}

      Number of frame elements to draw.

    frame_radius floats {0.005}

      Width of wireframe.

    point_color list {[‘r’, ‘g’, ‘b’, ‘y’]}

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

    point_mode string {‘sphere’,’cone’,’cube’,’cylinder’,’point’}

      Point marker shapes.

    point_size float {0.075}

      Size of points on Bloch sphere.

    sphere_alpha float {0.1}

      Transparency of Bloch sphere itself.

    sphere_color str {‘#808080’}

      Color of Bloch sphere.

    size list {[500,500]}

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

    vector_color list {[‘r’, ‘g’, ‘b’, ‘y’]}

      List of vector colors to cycle through.

    vector_width int {3}

      Width of displayed vectors.

    view list {[45,65]}

      Azimuthal and Elevation viewing angles.

    xlabel list {`['|x>', '']`}

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

    xlpos list {[1.07,-1.07]}

      Positions of +x and -x labels respectively.

    ylabel list {`['|y>', '']`}

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

    ylpos list {[1.07,-1.07]}

      Positions of +y and -y labels respectively.

    zlabel list {`['|0>', '|1>']`}

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

    zlpos list {[1.07,-1.07]}

      Positions of +z and -z labels respectively.

  add_points(points, meth='s', alpha=1.0)

    Add a list of data points to bloch sphere.

    Parameters:
      points array/list

        Collection of data points.

      meth str {‘s’,’m’}

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

      alpha float, default=1.

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

  add_states(state, kind='vector', alpha=1.0)

    Add a state vector Qobj to Bloch sphere.

    Parameters:
      state qobj

        Input state vector.

      kind str {‘vector’,’point’}

        Type of object to plot.

      alpha float, default=1.

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

  add_vectors(vectors, alpha=1.0)

    Add a list of vectors to Bloch sphere.

    Parameters:
      vectors array/list

        Array with vectors of unit length or smaller.

      alpha float, default=1.

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

  clear()

    Resets the Bloch sphere data sets to empty.

  make_sphere()

    Plots Bloch sphere and data sets.

  plot_points()

    Plots points on the Bloch sphere.

  plot_vectors()

    Plots vectors on the Bloch sphere.

  save(name=None, format='png', dirc=None)

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

    Parameters:
      name str

        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.

      format str

        Format of output image. Default is ‘png’.

      dirc str

        Directory for output images. Defaults to current working directory.

    Returns:
      File containing plot of Bloch sphere.
  show()

    Display the Bloch sphere and corresponding data sets.

## Distributions

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

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

  Parameters:
    xvec, yvec array_like

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

    g float, default sqrt(2)

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

    memory real, default 1024

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

  See also

  `qfunc`

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

  Examples

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

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

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

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

## Cubic Spline

class Cubic_Spline(a, b, y, alpha=0, beta=0)

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

      Lower bound of the interval.

    b float

      Upper bound of the interval.

    y ndarray

      Function values at interval points.

    alpha float

      Second-order derivative at a. Default is 0.

    beta float

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

      Lower bound of the interval.

    b float

      Upper bound of the interval.

    coeffs ndarray

      Array of coeffcients defining cubic spline.

## Non-Markovian Solvers

class HEOMSolver(H_sys, bath, max_depth, options=None, progress_bar=None)

  HEOM solver that supports multiple baths.

  The baths must be all either bosonic or fermionic baths.

  Parameters:
    H_sys QObj, QobjEvo or a list

      The system Hamiltonian or Liouvillian specified as either a `Qobj`, a `QobjEvo`, or a list of elements that may be converted to a `QobjEvo`.

    bath Bath or list of Bath

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

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

    max_depth int

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

    options `qutip.solver.Options`

      Generic solver options. If set to None the default options will be used.

    progress_bar None, True or `BaseProgressBar`

      Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the solver. If True, an instance of `TextProgressBar` is used instead.

  Attributes:
    ados `HierarchyADOs`

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

  run(rho0, tlist, e_ops=None, ado_init=False, ado_return=False)

    Solve for the time evolution of the system.

    Parameters:
      rho0 Qobj or HierarchyADOsState or numpy.array

        Initial state (`Qobj` density matrix) of the system if `ado_init` is `False`.

        If `ado_init` is `True`, then `rho0` should be an instance of `HierarchyADOsState` or a numpy array giving the initial state of all ADOs. Usually the state of the ADOs would be determine from a previous call to `.run(..., ado_return=True)`. For example, `result = solver.run(..., ado_return=True)` could be followed by `solver.run(result.ado_states[-1], tlist, ado_init=True)`.

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

      tlist list

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

      e_ops Qobj / callable / list / dict / None, optional

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

      ado_init: bool, default False

        Indicates if initial condition is just the system state, or a numpy array including all ADOs.

      ado_return: bool, default True

        Whether to also return as output the full state of all ADOs.

    Returns:
      `qutip.solver.Result`

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

        - `times`: the times `t` (i.e. the `tlist`).

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

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

        - `expect`: the value of each `e_ops` at time `t` (only available if `e_ops` were given). If `e_ops` was passed as a dictionary, then `expect` will be a dictionary with the same keys as `e_ops` and values giving the list of outcomes for the corresponding key.

  steady_state(use_mkl=True, mkl_max_iter_refine=100, mkl_weighted_matching=False)

    Compute the steady state of the system.

    Parameters:
      use_mkl bool, default=False

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

      mkl_max_iter_refine int

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

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

      mkl_weighted_matching bool

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

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

    Returns:
      steady_state Qobj

        The steady state density matrix of the system.

      steady_ados `HierarchyADOsState`

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

class HSolverDL(H_sys, coup_op, coup_strength, temperature, N_cut, N_exp, cut_freq, bnd_cut_approx=False, options=None, progress_bar=None, combine=True)

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

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

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

  Note

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

  Note

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

  Note

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

  Parameters:
    H_sys Qobj or QobjEvo or list

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

    coup_op Qobj

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

    coup_strength float

      Coupling strength. Referred to as `lam` in `DrudeLorentzBath`.

    temperature float

      Bath temperature. Referred to as `T` in `DrudeLorentzBath`.

    N_cut int

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

    N_exp int

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

    cut_freq float

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

    bnd_cut_approx bool

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

    options `qutip.solver.Options`

      Generic solver options. If set to None the default options will be used.

    progress_bar None, True or `BaseProgressBar`

      Optional instance of BaseProgressBar, or a subclass thereof, for showing the progress of the solver. If True, an instance of `TextProgressBar` is used instead.

    combine bool, default True

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

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

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

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

      The type of bath exponent.

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

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

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

    dim int or None

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

    Q Qobj

      The coupling operator for this excitation mode.

    vk complex

      The frequency of the exponent of the excitation term.

    ck complex

      The coefficient of the excitation term.

    ck2 optional, complex

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

    sigma_bar_k_offset optional, int

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

    tag optional, str, tuple or any other object

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

  Attributes:
    All of the parameters are available as attributes.
  types

    alias of `ExponentType`

class Bath(exponents)

  Represents a list of bath expansion exponents.

  Parameters:
    exponents list of BathExponent

      The exponents of the correlation function describing the bath.

  Attributes:
    All of the parameters are available as attributes.

class BosonicBath(Q, ck_real, vk_real, ck_imag, vk_imag, combine=True, tag=None)

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

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

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

  then:

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

  Defines the coefficients `ck` and the frequencies `vk`.

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

  Parameters:
    Q Qobj

      The coupling operator for the bath.

    ck_real list of complex

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

    vk_real list of complex

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

    ck_imag list of complex

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

    vk_imag list of complex

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

    combine bool, default True

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

    tag optional, str, tuple or any other object

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

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

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

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

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

    Parameters:
      exponents list of BathExponent

        The list of exponents to combine.

      rtol float, default 1e-5

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

      atol float, default 1e-7

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

    Returns:
      list of BathExponent

        The new reduced list of exponents.

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

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

  Parameters:
    Q Qobj

      Operator describing the coupling between system and bath.

    lam float

      Coupling strength.

    gamma float

      Bath spectral density cutoff frequency.

    T float

      Bath temperature.

    Nk int

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

    combine bool, default True

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

    tag optional, str, tuple or any other object

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

  terminator()

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

    Returns:
      delta: float

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

      terminator Qobj

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

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

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

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

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

  The implementation here follows the approach in the paper.

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

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

  Parameters:
    Q Qobj

      Operator describing the coupling between system and bath.

    lam float

      Coupling strength.

    gamma float

      Bath spectral density cutoff frequency.

    T float

      Bath temperature.

    Nk int

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

    combine bool, default True

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

    tag optional, str, tuple or any other object

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

  terminator()

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

    Returns:
      delta: float

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

      terminator Qobj

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

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

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

  Parameters:
    Q Qobj

      Operator describing the coupling between system and bath.

    lam float

      Coupling strength.

    gamma float

      Bath spectral density cutoff frequency.

    w0 float

      Bath spectral density resonance frequency.

    T float

      Bath temperature.

    Nk int

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

    combine bool, default True

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

    tag optional, str, tuple or any other object

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

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

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

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

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

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

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

  Parameters:
    Q Qobj

      The coupling operator for the bath.

    ck_plus list of complex

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

    vk_plus list of complex

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

    ck_minus list of complex

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

    vk_minus list of complex

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

    tag optional, str, tuple or any other object

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

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

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

  Note

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

  Parameters:
    Q Qobj

      Operator describing the coupling between system and bath.

    gamma float

      The coupling strength between the system and the bath.

    w float

      The width of the environment.

    mu float

      The chemical potential of the bath.

    T float

      Bath temperature.

    Nk int

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

    tag optional, str, tuple or any other object

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

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

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

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

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

  The implementation here follows the approach in the paper.

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

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

  Parameters:
    Q Qobj

      Operator describing the coupling between system and bath.

    gamma float

      The coupling strength between the system and the bath.

    w float

      The width of the environment.

    mu float

      The chemical potential of the bath.

    T float

      Bath temperature.

    Nk int

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

    tag optional, str, tuple or any other object

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

class HierarchyADOs(exponents, max_depth)

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

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

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

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

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

  Parameters:
    exponents list of BathExponent

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

    max_depth int

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

  Attributes:
    exponents list of BathExponent

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

    max_depth int

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

    dims list of int

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

    vk list of complex

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

    ck list of complex

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

    ck2: list of complex

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

    sigma_bar_k_offset: list of int

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

    labels: list of tuples

      A list of the ADO labels within the hierarchy.

  exps(label)

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

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

    Parameters:
      label tuple

        The ADO label to convert to a list of exponents.

    Returns:
      tuple of BathExponent

        A tuple of BathExponents.

    Examples

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

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

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

  filter(level=None, tags=None, dims=None, types=None)

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

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

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

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

    Parameters:
      level int

        The hierarchy depth to return ADOs from.

      tags list of object or None

        Filter parameter that matches the `.tag` attribute of exponents.

      dims list of int

        Filter parameter that matches the `.dim` attribute of exponents.

      types list of BathExponent types or list of str

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

    Returns:
      list of tuple

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

  idx(label)

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

    Parameters:
      label tuple

        The label to look up.

    Returns:
      int

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

  next(label, k)

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

    Parameters:
      label tuple

        The ADO label to add an excitation to.

      k int

        The exponent to add the excitation to.

    Returns:
      tuple or None

        The next label.

  prev(label, k)

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

    Parameters:
      label tuple

        The ADO label to remove the excitation from.

      k int

        The exponent to remove the excitation from.

    Returns:
      tuple or None

        The previous label.

class HierarchyADOsState(rho, ados, ado_state)

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

  Parameters:
    rho `Qobj`

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

    ados `HierarchyADOs`

      The description of the hierarchy.

    ado_state numpy.array

      The full state of the hierarchy.

  Attributes:
    rho Qobj

      The system state.

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

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

    Parameters:
      idx int or label

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

    Returns:
      Qobj

        A `Qobj` representing the state of the specified ADO.

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

  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_freq float

      Bath spectral density cutoff frequency.

    renorm bool

      Apply renormalisation to coupling terms Can be useful if using SI units for planck and boltzmann

    bnd_cut_approx bool

      Use boundary cut off approximation Can be

  configure(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)

    Calls configure from `HEOMSolver` and sets any attributes that are specific to this subclass

  reset()

    Reset any attributes to default values

  run(rho0, tlist)

    Function to solve for an open quantum system using the HEOM model.

    Parameters:
      rho0 Qobj

        Initial state (density matrix) of the system.

      tlist list

        Time over which system evolves.

    Returns:
      results `qutip.solver.Result`

        Object storing all results from the simulation.

class HEOMSolver

  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_sys Qobj

      System Hamiltonian

    coup_op Qobj

      Operator describing the coupling between system and bath.

    coup_strength float

      Coupling strength.

    temperature float

      Bath temperature, in units corresponding to planck

    N_cut int

      Cutoff parameter for the bath

    N_exp int

      Number of exponential terms used to approximate the bath correlation functions

    planck float

      reduced Planck constant

    boltzmann float

      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_coeff list of complex

      Coefficients for the exponential series terms

    exp_freq list of complex

      Frequencies for the exponential series terms

  configure(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)

    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

  create_new_stats()

    Creates a new stats object suitable for use with this solver Note: this solver expects the stats object to have sections

    - config

    - integrate

  reset()

    Reset any attributes to default values

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

  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 of `qutip.Qobj`

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

    L2 `qutip.Qobj` / list of `qutip.Qobj`

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

    S_matrix: *array*

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

    c_ops_markov `qutip.Qobj` / list of `qutip.Qobj`

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

    integrator str {‘propagator’, ‘mesolve’}

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

    parallel bool

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

    options `qutip.solver.Options`

      Generic solver options.

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

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

      blist array_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

      tlist array_like

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

      tau float

        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)

    Returns:
      : complex

        expectation value of field correlation function

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

    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:
      blist array_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

      tlist array_like

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

      tau float

        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)

      notrace bool {False}

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

    Returns:
      : `qutip.Qobj`

        time-propagator for computing field correlation function

  propagator(t, tau, notrace=False)

    Compute propagator for time t and time-delay tau

    Parameters:
      t float

        current time

      tau float

        time-delay

      notrace bool {False}

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

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

        time-propagator for reduced system dynamics

  rhot(rho0, t, tau)

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

    Parameters:
      rho0 `qutip.Qobj`

        initial density matrix or state vector (ket)

      t float

        current time

      tau float

        time-delay

    Returns:
      : `qutip.Qobj`

        density matrix at time \(t\)

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

  Class of options for the Transfer Tensor Method solver.

  Attributes:
    dynmaps list of `qutip.Qobj`

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

    times array_like

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

    learningtimes array_like

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

    thres float

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

    options `qutip.solver.Options`

      Generic solver options.

## Solver Options and Results

class ExpectOps(e_ops=[], super_=False)

  Contain and compute expectation values

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)

  Class of options for evolution solvers such as `qutip.mesolve` and `qutip.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:
    atol float {1e-8}

      Absolute tolerance.

    rtol float {1e-6}

      Relative tolerance.

    method str {‘adams’,’bdf’}

      Integration method.

    order int {12}

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

    nsteps int {2500}

      Max. number of internal steps/call.

    first_step float {0}

      Size of initial step (0 = automatic).

    min_step float {0}

      Minimum step size (0 = automatic).

    max_step float {0}

      Maximum step size (0 = automatic)

    tidy bool {True,False}

      Tidyup Hamiltonian and initial state by removing small terms.

    num_cpus int

      Number of cpus used by mcsolver (default = # of cpus).

    norm_tol float

      Tolerance used when finding wavefunction norm in mcsolve.

    norm_steps int

      Max. number of steps used to find wavefunction norm to within norm_tol in mcsolve.

    average_states bool {False}

      Average states values over trajectories in stochastic solvers.

    average_expect bool {True}

      Average expectation values over trajectories for stochastic solvers.

    mc_corr_eps float {1e-10}

      Arbitrarily small value for eliminating any divide-by-zero errors in correlation calculations when using mcsolve.

    ntraj int {500}

      Number of trajectories in stochastic solvers.

    openmp_threads int

      Number of OPENMP threads to use. Default is number of cpu cores.

    rhs_reuse bool {False,True}

      Reuse Hamiltonian data.

    rhs_with_state bool {False,True}

      Whether or not to include the state in the Hamiltonian function callback signature.

    rhs_filename str

      Name for compiled Cython file.

    seeds ndarray

      Array containing random number seeds for mcsolver.

    store_final_state bool {False, True}

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

    store_states bool {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_openmp bool {True, False}

      Use OPENMP for sparse matrix vector multiplication. Default None means auto check.

class Result

  Class for storing simulation results from any of the dynamics solvers.

  Attributes:
    solver str

      Which solver was used [e.g., ‘mesolve’, ‘mcsolve’, ‘brmesolve’, …]

    times list/array

      Times at which simulation data was collected.

    expect list/array

      Expectation values (if requested) for simulation.

    states array

      State of the simulation (density matrix or ket) evaluated at `times`.

    num_expect int

      Number of expectation value operators in simulation.

    num_collapse int

      Number of collapse operators in simualation.

    ntraj int/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_times list

      Times at which state collpase occurred. Only for Monte Carlo solver.

    col_which list

      Which collapse operator was responsible for each collapse in `col_times`. Only for Monte Carlo solver.

class SolverConfiguration

class Stats(section_names=None)

  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_names list

      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:
    sections OrderedDict of _StatsSection

      These are the sections that are created automatically on instantiation or added using add_section

    header string

      Some text that will be used as the heading in the report By default there is None

    total_time float

      Time in seconds for the solver to complete processing Can be None, meaning that total timing percentages will be reported

  add_count(key, value, section=None)

    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:
      key string

        key for the section.counts dictionary reusing a key will result in numerical addition of value

      value int

        Initial value of the count, or added to an existing count

      section string or `_StatsSection`

        Section which to add the count to. If None given, the default (first) section will be used

  add_message(key, value, section=None, sep=';')

    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:
      key string

        key for the section.messages dictionary reusing a key will result in concatenation of value

      value int

        Initial value of the message, or added to an existing message

      sep string

        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(name)

    Add another section with the given name

    Parameters:
      name string

        will be used as key for sections dict will also be the header for the section

    Returns:
      section`_StatsSection`

        The new section

  add_timing(key, value, section=None)

    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:
      key string

        key for the section.timings dictionary reusing a key will result in numerical addition of value

      value int

        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

  clear()

    Clear counts, timings and messages from all sections

  report(output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

    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:
      output stream

        file or console stream - anything that support write - where the output will be written

  set_total_time(value, section=None)

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

        Time in seconds to complete the solver section

      section string or class_StatsSection

        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)

  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` and `qutip.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.

  Within the attribute list, a `time_dependent_object` is either

  - `Qobj`: a constant term

  - 2-element list of `[Qobj, time_dependence]`: a time-dependent term where the `Qobj` will be multiplied by the time-dependent scalar.

  For more details on all allowed time-dependent objects, see the documentation for `QobjEvo`.

  Attributes:
    H time_dependent_object or list of time_dependent_object

      System Hamiltonian in standard time-dependent list format. This is the same as the argument that (e.g.) `mesolve` takes. If this is a list of elements, they are summed.

    state0 `qutip.Qobj`

      Initial state vector (ket) or density matrix.

    times array_like of float

      List of times for \(t\). Must be uniformly spaced.

    c_ops list of time_dependent_object

      List of deterministic collapse operators. Each element of the list is a separate operator; unlike the Hamiltonian, there is no implicit summation over the terms.

    sc_ops list of time_dependent_object

      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. Each element of the list is a separate operator, like `c_ops`.

    e_ops list of `qutip.Qobj`

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

    m_ops list 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.

    args dict

      Dictionary of parameters for time dependent systems.

    tol float

      Tolerance of the solver for implicit methods.

    ntraj int

      Number of trajectors.

    nsubsteps int

      Number of sub steps between each time-spep given in times.

    dW_factors array

      Array of length len(sc_ops), containing scaling factors for each measurement operator in m_ops.

    solver string

      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’

      See the documentation of `stochastic_solvers` for a description of the solvers. Implicit methods can adjust tolerance via the kw ‘tol’. Default is {‘tol’: 1e-6}

    method string (‘homodyne’, ‘heterodyne’)

      The name of the type of measurement process that give rise to the stochastic equation to solve.

    store_all_expect bool (default False)

      Whether or not to store the e_ops expect values for all paths.

    store_measurement bool (default False)

      Whether or not to store the measurement results in the `qutip.solver.Result` instance returned by the solver.

    noise int, or 1D array of int, or 4D array of float

      - int : seed of the noise

      - 1D array : length = ntraj, seeds for each trajectories.

      - 4D array : `(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. This corresponds to results.noise.

    noiseDepth int

      Number of terms kept of the truncated series used to create the noise used by taylor2.0 solver.

    normalize bool

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

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

  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

  Examples

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

  Attributes:
    N: int

      The number of two-level systems.

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

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

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

    Build the Lindbladian superoperator of the dissipative dynamics.

    Returns:
      lindbladian `qutip.Qobj`

        The Lindbladian matrix as a qutip.Qobj.

  liouvillian()

    Build the total Liouvillian using the Dicke basis.

    Returns:
      liouv `qutip.Qobj`

        The Liouvillian matrix for the system.

  pisolve(initial_state, tlist, options=None)

    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.

    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)

  The Permutation Invariant Matrix class.

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

  > dp/dt = Mp

  Parameters:
    N: int

      The number of two-level systems.

    emission: float

      Incoherent emission coefficient (also nonradiative emission). default: 0.0

    dephasing: float

      Local dephasing coefficient. default: 0.0

    pumping: float

      Incoherent pumping coefficient. default: 0.0

    collective_emission: float

      Collective (superradiant) emmission coefficient. default: 0.0

    collective_pumping: float

      Collective pumping coefficient. default: 0.0

    collective_dephasing: float

      Collective dephasing coefficient. default: 0.0

  Attributes:
    N: int

      The number of two-level systems.

    emission: float

      Incoherent emission coefficient (also nonradiative emission). default: 0.0

    dephasing: float

      Local dephasing coefficient. default: 0.0

    pumping: float

      Incoherent pumping coefficient. default: 0.0

    collective_emission: float

      Collective (superradiant) emmission coefficient. default: 0.0

    collective_dephasing: float

      Collective dephasing coefficient. default: 0.0

    collective_pumping: float

      Collective pumping coefficient. default: 0.0

    M: dict

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

  calculate_j_m(dicke_row, dicke_col)

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

    Parameters:
      dicke_row, dicke_col: int

        The row and column from the Dicke space matrix

    Returns:
      j, m: float

        The j and m values.

  calculate_k(dicke_row, dicke_col)

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

    Generate the matrix M governing the dynamics for diagonal cases.

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

  isdicke(dicke_row, dicke_col)

    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_col int

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

  solve(rho0, tlist, options=None)

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

  tau1(j, m)

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

  tau2(j, m)

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

  tau3(j, m)

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

  tau4(j, m)

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

  tau5(j, m)

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

  tau6(j, m)

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

  tau7(j, m)

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

  tau8(j, m)

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

  tau9(j, m)

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

  tau_valid(dicke_row, dicke_col)

    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_col int

        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.

## One-Dimensional Lattice

class Lattice1d(num_cell=10, boundary='periodic', cell_num_site=1, cell_site_dof=[1], Hamiltonian_of_cell=None, inter_hop=None)

  A class for representing a 1d crystal.

  The Lattice1d class can be defined with any specific unit cells and a specified number of unit cells in the crystal. It can return dispersion relationship, position operators, Hamiltonian in the position represention etc.

  Parameters:
    num_cell int

      The number of cells in the crystal.

    boundary str

      Specification of the type of boundary the crystal is defined with.

    cell_num_site int

      The number of sites in the unit cell.

    cell_site_dof list of int/ int

      The tensor structure of the degrees of freedom at each site of a unit cell.

    Hamiltonian_of_cell qutip.Qobj

      The Hamiltonian of the unit cell.

    inter_hop qutip.Qobj / list of Qobj

      The coupling between the unit cell at i and at (i+unit vector)

  Attributes:
    num_cell int

      The number of unit cells in the crystal.

    cell_num_site int

      The nuber of sites in a unit cell.

    length_for_site int

      The length of the dimension per site of a unit cell.

    cell_tensor_config list of int

      The tensor structure of the cell in the form [cell_num_site,cell_site_dof[:][0] ]

    lattice_tensor_config list of int

      The tensor structure of the crystal in the form [num_cell,cell_num_site,cell_site_dof[:][0]]

    length_of_unit_cell int

      The length of the dimension for a unit cell.

    period_bnd_cond_x int

      1 indicates “periodic” and 0 indicates “hardwall” boundary condition

    inter_vec_list list of list

      The list of list of coefficients of inter unitcell vectors’ components along Cartesian uit vectors.

    lattice_vectors_list list of list

      The list of list of coefficients of lattice basis vectors’ components along Cartesian unit vectors.

    H_intra qutip.Qobj

      The Qobj storing the Hamiltonian of the unnit cell.

    H_inter_list list of Qobj/ qutip.Qobj

      The list of coupling terms between unit cells of the lattice.

    is_real bool

      Indicates if the Hamiltonian is real or not.

  Hamiltonian()

    Returns the lattice Hamiltonian for the instance of Lattice1d.

    Returns:
      Qobj(Hamil)qutip.Qobj

        oper type Quantum object representing the lattice Hamiltonian.

  basis(cell, site, dof_ind)

    Returns a single particle wavefunction ket with the particle localized at a specified dof at a specified site of a specified cell.

    Parameters:

      - cell (int) – The cell at which the particle is to be localized.

      - site (int) – The site of the cell at which the particle is to be localized.

      - dof_ind (int/ list of int) – The index of the degrees of freedom with which the sigle particle is to be localized.

    Returns:
      vec_i qutip.Qobj

        ket type Quantum object representing the localized particle.

  bloch_wave_functions()

    Returns eigenvectors ($psi_n(k)$) of the Hamiltonian in a numpy.ndarray for translationally symmetric lattices with periodic boundary condition.

    \begin{eqnarray} |\psi_n(k) \rangle = |k \rangle \otimes | u_{n}(k) \rangle \\ | u_{n}(k) \rangle = a_n(k)|a\rangle + b_n(k)|b\rangle \\ \end{eqnarray}

    Please see section 1.2 of Asbóth, J. K., Oroszlány, L., & Pályi, A. (2016). A short course on topological insulators. Lecture notes in physics, 919 for a review.

    Returns:
      eigenstates ordered np.array

        eigenstates[j][0] is the jth eigenvalue. eigenstates[j][1] is the corresponding eigenvector.

  bulk_Hamiltonians()

    Returns the bulk momentum space Hamiltonian ($H(k)$) for the lattice at the good quantum numbers of k in a numpy ndarray of Qobj’s.

    Please see section 1.2 of Asbóth, J. K., Oroszlány, L., & Pályi, A. (2016). A short course on topological insulators. Lecture notes in physics, 919 for a review.

    Returns:
      knxa np.array

        knxA[j][0] is the jth good Quantum number k.

      qH_ks np.ndarray of Qobj’s

        qH_ks[j] is the Oobj of type oper that holds a bulk Hamiltonian for a good quantum number k.

  cell_periodic_parts()

    Returns eigenvectors of the bulk Hamiltonian, i.e. the cell periodic part($u_n(k)$) of the Bloch wavefunctios in a numpy.ndarray for translationally symmetric lattices with periodic boundary condition.

    \begin{eqnarray} |\psi_n(k) \rangle = |k \rangle \otimes | u_{n}(k) \rangle \\ | u_{n}(k) \rangle = a_n(k)|a\rangle + b_n(k)|b\rangle \\ \end{eqnarray}

    Please see section 1.2 of Asbóth, J. K., Oroszlány, L., & Pályi, A. (2016). A short course on topological insulators. Lecture notes in physics, 919 for a review.

    Returns:
      knxa np.array

        knxA[j][0] is the jth good Quantum number k.

      vec_kns np.ndarray of Qobj’s

        vec_kns[j] is the Oobj of type ket that holds an eigenvector of the bulk Hamiltonian of the lattice.

  display_lattice()

    Produces a graphic portraying the lattice symbolically with a unit cell marked in it.

    Returns:
      inter_T Qobj

        The coefficient of $psi_{i,N}^{dagger}psi_{0,i+1}$, i.e. the coupling between the two boundary sites of the two unit cells i and i+1.

  display_unit_cell(label_on=False)

    Produces a graphic displaying the unit cell features with labels on if defined by user. Also returns a dict of Qobj’s corresponding to the labeled elements on the display.

    Returns:
      Hcell dict

        Hcell[i][j] is the Hamiltonian segment for $H_{i,j}$ labeled on the graphic.

  distribute_operator(op)

    A function that returns an operator matrix that applies op to all the cells in the 1d lattice

    Parameters:

      op (qutip.Qobj) – Qobj representing the operator to be applied at all cells.

    Returns:
      op_H qutip.Qobj

        Quantum object representing the operator with op applied at all cells.

  get_dispersion(knpoints=0)

    Returns dispersion relationship for the lattice with the specified number of unit cells with a k array and a band energy array.

    Returns:
      knxa np.array

        knxA[j][0] is the jth good Quantum number k.

      val_kns np.array

        val_kns[j][:] is the array of band energies of the jth band good at all the good Quantum numbers of k.

  k()

    Returns the crystal momentum operator. All degrees of freedom has the cell number at their correspondig entry in the position operator.

    Returns:
      Qobj(ks)qutip.Qobj

        The crystal momentum operator in units of 1/a. L is the number of unit cells, a is the length of a unit cell which is always taken to be 1.

  operator_at_cells(op, cells)

    A function that returns an operator matrix that applies op to specific cells specified in the cells list

    Parameters:
      op qutip.Qobj

        Qobj representing the operator to be applied at certain cells.

      cells: list of int

        The cells at which the operator op is to be applied.

    Returns:
      Qobj(op_H)Qobj

        Quantum object representing the operator with op applied at the specified cells.

  operator_between_cells(op, row_cell, col_cell)

    A function that returns an operator matrix that applies op to specific cells specified in the cells list

    Parameters:
      op qutip.Qobj

        Qobj representing the operator to be put between cells row_cell and col_cell.

      row_cell: int

        The row index for cell for the operator op to be applied.

      col_cell: int

        The column index for cell for the operator op to be applied.

    Returns:
      oper_bet_cell Qobj

        Quantum object representing the operator with op applied between the specified cells.

  plot_dispersion()

    Plots the dispersion relationship for the lattice with the specified number of unit cells. The dispersion of the infinte crystal is also plotted if num_cell is smaller than MAXc.

  winding_number()

    Returns the winding number for a lattice that has chiral symmetry and also plots the trajectory of (dx,dy)(dx,dy are the coefficients of sigmax and sigmay in the Hamiltonian respectively) on a plane.

    Returns:
      winding_number int or str

        knxA[j][0] is the jth good Quantum number k.

  x()

    Returns the position operator. All degrees of freedom has the cell number at their correspondig entry in the position operator.

    Returns:
      Qobj(xs)qutip.Qobj

        The position operator.

## Distribution functions

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

  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:
    data array_like

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

    xvecs list

      List of arrays that spans the space for each coordinate.

    xlabels list

      List of labels for each coordinate.

  marginal(dim=0)

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

    Parameters:
      dim int

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

    Returns:
      d Distributions

        A new instances of Distribution that describes the marginal distribution.

  project(dim=0)

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

    Parameters:
      dim int

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

    Returns:
      d Distributions

        A new instances of Distribution that describes the projection.

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

    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, ax tuple

        A tuple of matplotlib figure and axes instances.

class WignerDistribution(rho=None, extent=[[-5, 5], [-5, 5]], steps=250)

class QDistribution(rho=None, extent=[[-5, 5], [-5, 5]], steps=250)

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

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

  update_psi(psi)

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

  update_rho(rho)

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

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

    Calculate the wavefunction for the given state of an harmonic oscillator

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

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

## Quantum information processing

class Gate(*args, **kwargs)

  Representation of a quantum gate, with its required parameters, and target and control qubits.

  Parameters:
    name string

      Gate name.

    targets list or int

      Gate targets.

    controls list or int

      Gate controls.

    arg_value float

      Argument value(phi).

    arg_label string

      Label for gate representation.

    classical_controls int or list of int, optional

      indices of classical bits to control gate on.

    control_value int, optional

      value of classical bits to control on, the classical controls are interpreted as an integer with lowest bit being the first one. If not specified, then the value is interpreted to be 2 ** len(classical_controls) - 1 (i.e. all classical controls are 1).

class Measurement(name, targets=None, index=None, classical_store=None)

  Representation of a quantum measurement, with its required parameters, and target qubits.

  Parameters:
    name string

      Measurement name.

    targets list or int

      Gate targets.

    classical_store int

      Result of the measurment is stored in this classical register of the circuit.

  measurement_comp_basis(state)

    Measures a particular qubit (determined by the target) whose ket vector/ density matrix is specified in the computational basis and returns collapsed_states and probabilities (retains full dimension).

    Parameters:
      state ket or oper

        state to be measured on specified by ket vector or density matrix

    Returns:
      collapsed_states List of Qobjs

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

      probabilities List of floats

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

class QubitCircuit(N, input_states=None, output_states=None, reverse_states=True, user_gates=None, dims=None, num_cbits=0)

  Representation of a quantum program/algorithm, maintaining a sequence of gates.

  Parameters:
    N int

      Number of qubits in the system.

    user_gates dict

      Define a dictionary of the custom gates. See examples for detail.

    input_states list

      A list of string such as 0,’+’, “A”, “Y”. Only used for latex.

    dims list

      A list of integer for the dimension of each composite system. e.g [2,2,2,2,2] for 5 qubits system. If None, qubits system will be the default option.

    num_cbits int

      Number of classical bits in the system.

  Examples

      >>> def user_gate():
      ...     mat = np.array([[1.,   0],
      ...                     [0., 1.j]])
      ...     return Qobj(mat, dims=[[2], [2]])
      >>> qubit_circuit = QubitCircuit(2, user_gates={"T":user_gate})
      >>> qubit_circuit.add_gate("T", targets=[0])

  add_1q_gate(name, start=0, end=None, qubits=None, arg_value=None, arg_label=None, classical_controls=None, control_value=None)

    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:
      name string

        Gate name.

      start int

        Starting location of qubits.

      end int

        Last qubit for the gate.

      qubits list

        Specific qubits for applying gates.

      arg_value float

        Argument value(phi).

      arg_label string

        Label for gate representation.

  add_circuit(qc, start=0, overwrite_user_gates=False)

    Adds a block of a qubit circuit to the main circuit. Globalphase gates are not added.

    Parameters:
      qc `QubitCircuit`

        The circuit block to be added to the main circuit.

      start int

        The qubit on which the first gate is applied.

  add_gate(gate, targets=None, controls=None, arg_value=None, arg_label=None, index=None, classical_controls=None, control_value=None)

    Adds a gate with specified parameters to the circuit.

    Parameters:
      gate: string or :class:`.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.

      index list

        Positions to add the gate. Each index in the supplied list refers to a position in the original list of gates.

      classical_controls int or list of int, optional

        indices of classical bits to control gate on.

      control_value int, optional

        value of classical bits to control on, the classical controls are interpreted as an integer with lowest bit being the first one. If not specified, then the value is interpreted to be 2 ** len(classical_controls) - 1 (i.e. all classical controls are 1).

  add_measurement(measurement, targets=None, index=None, classical_store=None)

    Adds a measurement with specified parameters to the circuit.

    Parameters:
      measurement: string

        Measurement name. If name is an instance of Measuremnent, parameters are unpacked and added.

      targets: list

        Gate targets

      index list

        Positions to add the gate.

      classical_store int

        Classical register where result of measurement is stored.

  add_state(state, targets=None, state_type='input')

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

    Method to resolve two qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions.

    Returns:
      qubit_circuit: `QubitCircuit`

        Return `QubitCircuit` of the gates for the qubit circuit with the resolved non-adjacent gates.

  propagators(expand=True)

    Propagator matrix calculator for N qubits returning the individual steps as unitary matrices operating from left to right. :returns: U_list – Return list of unitary matrices for the qubit circuit. :rtype: list

  propagators_no_expand()

    Propagator matrix calculator for N qubits returning the individual steps as unitary matrices operating from left to right.

    Returns:
      U_list list

        Return list of unitary matrices for the qubit circuit.

  remove_gate_or_measurement(index=None, end=None, name=None, remove='first')

    Remove a gate from a specific index or between two indexes or the first, last or all instances of a particular gate.

    Parameters:
      index int

        Location of gate or measurement to be removed.

      name string

        Gate or Measurement name to be removed.

      remove string

        If first or all gates/measurements are to be removed.

  resolve_gates(basis=['CNOT', 'RX', 'RY', 'RZ'])

    Unitary matrix calculator for N qubits returning the individual steps as unitary matrices operating from left to right in the specified basis. Calls ‘_resolve_to_universal’ for each gate, this function maps each ‘GATENAME’ with its corresponding ‘_gate_basis_2q’ Subsequently calls _resolve_2q_basis for each basis, this function maps each ‘2QGATENAME’ with its corresponding ‘_basis_’

    Parameters:
      basis list.

        Basis of the resolved circuit.

    Returns:
      qc `QubitCircuit`

        Return `QubitCircuit` of resolved gates for the qubit circuit in the desired basis.

  reverse_circuit()

    Reverse an entire circuit of unitary gates.

    Returns:
      qubit_circuit `QubitCircuit`

        Return `QubitCircuit` of resolved gates for the qubit circuit in the reverse order.

  run(state, cbits=None, U_list=None, measure_results=None, precompute_unitary=False)

    Calculate the result of one instance of circuit run.

    Parameters:
      state ket or oper

        state vector or density matrix input.

      cbits List of ints, optional

        initialization of the classical bits.

      U_list: list of Qobj, optional

        list of predefined unitaries corresponding to circuit.

      measure_results tuple of ints, optional

        optional specification of each measurement result to enable post-selection. If specified, the measurement results are set to the tuple of bits (sequentially) instead of being chosen at random.

      precompute_unitary: Boolean, optional

        Specify if computation is done by pre-computing and aggregating gate unitaries. Possibly a faster method in the case of large number of repeat runs with different state inputs.

    Returns:
      final_state Qobj

        output state of the circuit run.

  run_statistics(state, U_list=None, cbits=None, precompute_unitary=False)

    Calculate all the possible outputs of a circuit (varied by measurement gates).

    Parameters:
      state ket or oper

        state vector or density matrix input.

      cbits List of ints, optional

        initialization of the classical bits.

      U_list: list of Qobj, optional

        list of predefined unitaries corresponding to circuit.

      measure_results tuple of ints, optional

        optional specification of each measurement result to enable post-selection. If specified, the measurement results are set to the tuple of bits (sequentially) instead of being chosen at random.

      precompute_unitary: Boolean, optional

        Specify if computation is done by pre-computing and aggregating gate unitaries. Possibly a faster method in the case of large number of repeat runs with different state inputs.

    Returns:
      result: CircuitResult

        Return a CircuitResult object containing output states and and their probabilities.

class CircuitResult(final_states, probabilities, cbits=None)
  get_cbits(index=None)

    Return list of classical bit outputs corresponding to the results.

    Parameters:
      index: int

        Indicates i-th output, probability pair to be returned.

    Returns:
      cbits: list of int or list of list of int

        list of classical bit outputs

  get_final_states(index=None)

    Return list of output states.

    Parameters:
      index: int

        Indicates i-th state to be returned.

    Returns:
      final_states: Qobj or list of Qobj.

        List of output kets or density matrices.

  get_probabilities(index=None)

    Return list of probabilities corresponding to the output states.

    Parameters:
      index: int

        Indicates i-th probability to be returned.

    Returns:
      probabilities: float or list of float

        Probabilities associated with each output state.

class CircuitSimulator(qc, state=None, cbits=None, U_list=None, measure_results=None, mode='state_vector_simulator', precompute_unitary=False)
  initialize(state=None, cbits=None, measure_results=None)

    Reset Simulator state variables to start a new run.

    Parameters:
      state: ket or oper

        ket or density matrix

      cbits: list of int, optional

        initial value of classical bits

      U_list: list of Qobj, optional

        list of predefined unitaries corresponding to circuit.

      measure_results tuple of ints, optional

        optional specification of each measurement result to enable post-selection. If specified, the measurement results are set to the tuple of bits (sequentially) instead of being chosen at random.

  run(state, cbits=None, measure_results=None)

    Calculate the result of one instance of circuit run.

    Parameters:
      state ket or oper

        state vector or density matrix input.

      cbits List of ints, optional

        initialization of the classical bits.

      measure_results tuple of ints, optional

        optional specification of each measurement result to enable post-selection. If specified, the measurement results are set to the tuple of bits (sequentially) instead of being chosen at random.

    Returns:
      result: CircuitResult

        Return a CircuitResult object containing output state and probability.

  run_statistics(state, cbits=None)

    Calculate all the possible outputs of a circuit (varied by measurement gates).

    Parameters:
      state ket

        state to be observed on specified by density matrix.

      cbits List of ints, optional

        initialization of the classical bits.

    Returns:
      result: CircuitResult

        Return a CircuitResult object containing output states and and their probabilities.

  step()

    Return state after one step of circuit evolution (gate or measurement).

    Returns:
      state ket or oper

        state after one evolution step.

class Processor(N, t1=None, t2=None, dims=None, spline_kind='step_func')

  A simulator of a quantum device based on the QuTiP solver `qutip.mesolve`. It is defined by the available driving Hamiltonian and the decoherence time for each component systems. The processor can simulate the evolution under the given control pulses. Noisy evolution is supported by `Noise` and can be added to the processor.

  Parameters:
    N: int

      The number of component systems.

    t1: list or float, optional

      Characterize the decoherence of amplitude damping for each qubit. A list of size N or a float for all qubits.

    t2: list of float, optional

      Characterize the decoherence of dephasing for each qubit. A list of size N or a float for all qubits.

    dims: list, optional

      The dimension of each component system. Default value is a qubit system of `dim=[2,2,2,...,2]`

    spline_kind: str, optional

      Type of the coefficient interpolation. Default is “step_func” Note that they have different requirement for the length of `coeff`.

      - “step_func”: The coefficient will be treated as a step function. E.g. `tlist=[0,1,2]` and `coeff=[3,2]`, means that the coefficient is 3 in t=[0,1) and 2 in t=[2,3). It requires `len(coeff)=len(tlist)-1` or `len(coeff)=len(tlist)`, but in the second case the last element of coeff has no effect.

      - “cubic”: Use cubic interpolation for the coefficient. It requires `len(coeff)=len(tlist)`

  Attributes:
    N: int

      The number of component systems.

    pulses: list of :class:`.Pulse`

      A list of control pulses of this device

    t1: float or list

      Characterize the decoherence of amplitude damping of each qubit.

    t2: float or list

      Characterize the decoherence of dephasing for each qubit.

    noise: :class:`.Noise`, optional

      A list of noise objects. They will be processed when creating the noisy `qutip.QobjEvo` from the processor or run the simulation.

    drift: :class:`qutip.qip.pulse.Drift`

      A Drift object representing the drift Hamiltonians.

    dims: list

      The dimension of each component system. Default value is a qubit system of `dim=[2,2,2,...,2]`

    spline_kind: str

      Type of the coefficient interpolation. See parameters of `Processor` for details.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc)

    Translate an `QubitCircuit` to its corresponding Hamiltonians. (Defined in subclasses)

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, states=None, noisy=True, solver='mesolve', **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments.

    If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices. Noise will be neglected in this option.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: bool

        If True, calculate the evolution with matrices exponentiation.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      solver: str

        “mesolve” or “mcsolve”

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

class OptPulseProcessor(N, drift=None, t1=None, t2=None, dims=None)

  A processor, which takes the Hamiltonian available as dynamic generators, calls the qutip.control.optimize_pulse_unitary function to find an optimized pulse sequence for the desired quantum circuit. The processor can simulate the evolution under the given control pulses using `qutip.mesolve`. (For attributes documentation, please refer to the parent class `Processor`)

  Parameters:
    N: int

      The number of component systems.

    drift: `:class:`qutip.Qobj`

      The drift Hamiltonian. The size must match the whole quantum system.

    t1: list or float

      Characterize the decoherence of amplitude damping for each qubit. A list of size N or a float for all qubits.

    t2: list of float

      Characterize the decoherence of dephasing for each qubit. A list of size N or a float for all qubits.

    dims: list

      The dimension of each component system. Default value is a qubit system of `dim=[2,2,2,...,2]`

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc, min_fid_err=inf, merge_gates=True, setting_args=None, verbose=False, **kwargs)

    Find the pulses realizing a given `QubitCircuit` using qutip.control.optimize_pulse_unitary. Further parameter for for qutip.control.optimize_pulse_unitary needs to be given as keyword arguments. By default, it first merge all the gates into one unitary and then find the control pulses for it. It can be turned off and one can set different parameters for different gates. See examples for details.

    Parameters:
      qc: :class:`.QubitCircuit` or list of Qobj

        The quantum circuit to be translated.

      min_fid_err: float, optional

        The minimal fidelity tolerance, if the fidelity error of any gate decomposition is higher, a warning will be given. Default is infinite.

      merge_gates: boolean, optimal

        If True, merge all gate/Qobj into one Qobj and then find the optimal pulses for this unitary matrix. If False, find the optimal pulses for each gate/Qobj.

      setting_args: dict, optional

        Only considered if merge_gates is False. It is a dictionary containing keyword arguments for different gates.

        E.g.:

            setting_args = {"SNOT": {"num_tslots": 10, "evo_time": 1},
                            "SWAP": {"num_tslots": 30, "evo_time": 3},
                            "CNOT": {"num_tslots": 30, "evo_time": 3}}

      verbose: boolean, optional

        If true, the information for each decomposed gate will be shown. Default is False.

      **kwargs

        keyword arguments for qutip.control.optimize_pulse_unitary

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape (len(ctrls), len(tlist)-1). Each row corresponds to the control pulse sequence for one Hamiltonian.

    Notes

    `len(tlist) - 1 = coeffs.shape[1]` since tlist gives the beginning and the end of the pulses.

    Examples

    Same parameter for all the gates:

        qc = QubitCircuit(N=1)
        qc.add_gate("SNOT", 0)
        num_tslots = 10
        evo_time = 10
        processor = OptPulseProcessor(N=1, drift=sigmaz(),
                                      ctrls=[sigmax()])
        # num_tslots and evo_time are two keyword arguments
        tlist, coeffs = processor.load_circuit(
            qc, num_tslots=num_tslots, evo_time=evo_time)

    Different parameters for different gates:

        qc = QubitCircuit(N=2)
        qc.add_gate("SNOT", 0)
        qc.add_gate("SWAP", targets=[0, 1])
        qc.add_gate('CNOT', controls=1, targets=[0])

        processor = OptPulseProcessor(N=2, drift=tensor([sigmaz()]*2))
        processor.add_control(sigmax(), cyclic_permutation=True)
        processor.add_control(sigmay(), cyclic_permutation=True)
        processor.add_control(tensor([sigmay(), sigmay()]))
        setting_args = {"SNOT": {"num_tslots": 10, "evo_time": 1},
                        "SWAP": {"num_tslots": 30, "evo_time": 3},
                        "CNOT": {"num_tslots": 30, "evo_time": 3}}
        tlist, coeffs = processor.load_circuit(qc,
                                               setting_args=setting_args,
                                               merge_gates=False)

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, states=None, noisy=True, solver='mesolve', **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments.

    If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices. Noise will be neglected in this option.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: bool

        If True, calculate the evolution with matrices exponentiation.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      solver: str

        “mesolve” or “mcsolve”

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

class ModelProcessor(N, correct_global_phase=True, t1=None, t2=None)

  The base class for a circuit processor simulating a physical device, e.g cavityQED, spinchain. The available Hamiltonian of the system is predefined. The processor can simulate the evolution under the given control pulses either numerically or analytically. It cannot be used alone, please refer to the sub-classes. (Only additional attributes are documented here, for others please refer to the parent class `Processor`)

  Parameters:
    N: int

      The number of component systems.

    correct_global_phase: boolean, optional

      If true, the analytical solution will track the global phase. It has no effect on the numerical solution.

    t1: list or float

      Characterize the decoherence of amplitude damping for each qubit. A list of size N or a float for all qubits.

    t2: list of float

      Characterize the decoherence of dephasing for each qubit. A list of size N or a float for all qubits.

  Attributes:
    params: dict

      A Python dictionary contains the name and the value of the parameters in the physical realization, such as laser frequency, detuning etc.

    correct_global_phase: float

      Save the global phase, the analytical solution will track the global phase. It has no effect on the numerical solution.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_ops_and_u()

    Get the labels for each Hamiltonian.

    Returns:
      ctrls: list

        The list of Hamiltonians

      coeffs: array_like

        The transposed pulse matrix

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc)

    Translate an `QubitCircuit` to its corresponding Hamiltonians. (Defined in subclasses)

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  pulse_matrix(dt=0.01)

    Generates the pulse matrix for the desired physical system.

    Returns:
      t, u, labels:

        Returns the total time and label for every operation.

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, qc=None, states=None, **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments. If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: boolean

        If True, calculate the evolution with matrices exponentiation.

      qc: :class:`.QubitCircuit`, optional

        A quantum circuit. If given, it first calls the `load_circuit` and then calculate the evolution.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

  set_up_params()

    Save the parameters in the attribute params and check the validity. (Defined in subclasses)

    Notes

    All parameters will be multiplied by 2*pi for simplicity

  to_array(params, N)

    Transfer a parameter to an array.

class SpinChain(N, correct_global_phase, sx, sz, sxsy, t1, t2)

  The processor based on the physical implementation of a spin chain qubits system. The available Hamiltonian of the system is predefined. The processor can simulate the evolution under the given control pulses either numerically or analytically. It is a base class and should not be used directly, please refer the the subclasses `qutip.qip.device.LinearSpinChain` and `qutip.qip.device.CircularSpinChain`. (Only additional attributes are documented here, for others please refer to the parent class `ModelProcessor`)

  Parameters:
    N: int

      The number of qubits in the system.

    correct_global_phase: float

      Save the global phase, the analytical solution will track the global phase. It has no effect on the numerical solution.

    sx: int or list

      The delta for each of the qubits in the system.

    sz: int or list

      The epsilon for each of the qubits in the system.

    sxsy: int or list

      The interaction strength for each of the qubit pair in the system.

    t1: list or float

      Characterize the decoherence of amplitude damping for each qubit. A list of size N or a float for all qubits.

    t2: list of float

      Characterize the decoherence of dephasing for each qubit. A list of size N or a float for all qubits.

  Attributes:
    sx: list

      The delta for each of the qubits in the system.

    sz: list

      The epsilon for each of the qubits in the system.

    sxsy: list

      The interaction strength for each of the qubit pair in the system.

    sx_ops: list

      A list of sigmax Hamiltonians for each qubit.

    sz_ops: list

      A list of sigmaz Hamiltonians for each qubit.

    sxsy_ops: list

      A list of tensor(sigmax, sigmay) interacting Hamiltonians for each qubit.

    sx_u: array_like

      Pulse matrix for sigmax Hamiltonians.

    sz_u: array_like

      Pulse matrix for sigmaz Hamiltonians.

    sxsy_u: array_like

      Pulse matrix for tensor(sigmax, sigmay) interacting Hamiltonians.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  adjacent_gates(qc, setup='linear')

    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: :class:`.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.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_ops_and_u()

    Get the labels for each Hamiltonian.

    Returns:
      ctrls: list

        The list of Hamiltonians

      coeffs: array_like

        The transposed pulse matrix

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc, setup, schedule_mode='ASAP', compiler=None)

    Decompose a `QubitCircuit` in to the control amplitude generating the corresponding evolution.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

      setup: string

        “linear” or “circular” for two sub-classes.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each row corresponds to the control pulse sequence for one Hamiltonian.

  optimize_circuit(qc)

    Take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

    Returns:
      qc: `QubitCircuit`

        The circuit representation with elementary gates that can be implemented in this model.

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  pulse_matrix(dt=0.01)

    Generates the pulse matrix for the desired physical system.

    Returns:
      t, u, labels:

        Returns the total time and label for every operation.

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, qc=None, states=None, **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments. If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: boolean

        If True, calculate the evolution with matrices exponentiation.

      qc: :class:`.QubitCircuit`, optional

        A quantum circuit. If given, it first calls the `load_circuit` and then calculate the evolution.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

  set_up_ops(N)

    Generate the Hamiltonians for the spinchain model and save them in the attribute ctrls.

    Parameters:
      N: int

        The number of qubits in the system.

  set_up_params(sx, sz)

    Save the parameters in the attribute params and check the validity. The keys of params including “sx”, “sz”, and “sxsy”, each mapped to a list for parameters corresponding to each qubits. For coupling strength “sxsy”, list element i is the interaction between qubits i and i+1.

    Parameters:
      sx: float or list

        The coefficient of sigmax in the model

      sz: flaot or list

        The coefficient of sigmaz in the model

    Notes

    The coefficient of sxsy is defined in the submethods. All parameters will be multiplied by 2*pi for simplicity

  to_array(params, N)

    Transfer a parameter to an array.

class LinearSpinChain(N, correct_global_phase=True, sx=0.25, sz=1.0, sxsy=0.1, t1=None, t2=None)

  A processor based on the physical implementation of a linear spin chain qubits system. The available Hamiltonian of the system is predefined. The processor can simulate the evolution under the given control pulses either numerically or analytically.

  Parameters:
    N: int

      The number of qubits in the system.

    correct_global_phase: float

      Save the global phase, the analytical solution will track the global phase. It has no effect on the numerical solution.

    sx: int or list

      The delta for each of the qubits in the system.

    sz: int or list

      The epsilon for each of the qubits in the system.

    sxsy: int or list

      The interaction strength for each of the qubit pair in the system.

    t1: list or float, optional

      Characterize the decoherence of amplitude damping for each qubit.

    t2: list of float, optional

      Characterize the decoherence of dephasing for each qubit.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  adjacent_gates(qc)

    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: :class:`.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.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_ops_and_u()

    Get the labels for each Hamiltonian.

    Returns:
      ctrls: list

        The list of Hamiltonians

      coeffs: array_like

        The transposed pulse matrix

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc, schedule_mode='ASAP', compiler=None)

    Decompose a `QubitCircuit` in to the control amplitude generating the corresponding evolution.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

      setup: string

        “linear” or “circular” for two sub-classes.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each row corresponds to the control pulse sequence for one Hamiltonian.

  optimize_circuit(qc)

    Take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

    Returns:
      qc: `QubitCircuit`

        The circuit representation with elementary gates that can be implemented in this model.

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  pulse_matrix(dt=0.01)

    Generates the pulse matrix for the desired physical system.

    Returns:
      t, u, labels:

        Returns the total time and label for every operation.

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, qc=None, states=None, **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments. If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: boolean

        If True, calculate the evolution with matrices exponentiation.

      qc: :class:`.QubitCircuit`, optional

        A quantum circuit. If given, it first calls the `load_circuit` and then calculate the evolution.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

  set_up_ops(N)

    Generate the Hamiltonians for the spinchain model and save them in the attribute ctrls.

    Parameters:
      N: int

        The number of qubits in the system.

  set_up_params(sx, sz, sxsy)

    Save the parameters in the attribute params and check the validity. The keys of params including “sx”, “sz”, and “sxsy”, each mapped to a list for parameters corresponding to each qubits. For coupling strength “sxsy”, list element i is the interaction between qubits i and i+1.

    Parameters:
      sx: float or list

        The coefficient of sigmax in the model

      sz: flaot or list

        The coefficient of sigmaz in the model

    Notes

    The coefficient of sxsy is defined in the submethods. All parameters will be multiplied by 2*pi for simplicity

  to_array(params, N)

    Transfer a parameter to an array.

class CircularSpinChain(N, correct_global_phase=True, sx=0.25, sz=1.0, sxsy=0.1, t1=None, t2=None)

  A processor based on the physical implementation of a circular spin chain qubits system. The available Hamiltonian of the system is predefined. The processor can simulate the evolution under the given control pulses either numerically or analytically.

  Parameters:
    N: int

      The number of qubits in the system.

    correct_global_phase: float

      Save the global phase, the analytical solution will track the global phase. It has no effect on the numerical solution.

    sx: int or list

      The delta for each of the qubits in the system.

    sz: int or list

      The epsilon for each of the qubits in the system.

    sxsy: int or list

      The interaction strength for each of the qubit pair in the system.

    t1: list or float, optional

      Characterize the decoherence of amplitude damping for each qubit.

    t2: list of float, optional

      Characterize the decoherence of dephasing for each qubit.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  adjacent_gates(qc)

    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: :class:`.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.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed. (Defined in subclasses)

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_ops_and_u()

    Get the labels for each Hamiltonian.

    Returns:
      ctrls: list

        The list of Hamiltonians

      coeffs: array_like

        The transposed pulse matrix

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc, schedule_mode='ASAP', compiler=None)

    Decompose a `QubitCircuit` in to the control amplitude generating the corresponding evolution.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

      setup: string

        “linear” or “circular” for two sub-classes.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each row corresponds to the control pulse sequence for one Hamiltonian.

  optimize_circuit(qc)

    Take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

    Returns:
      qc: `QubitCircuit`

        The circuit representation with elementary gates that can be implemented in this model.

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  pulse_matrix(dt=0.01)

    Generates the pulse matrix for the desired physical system.

    Returns:
      t, u, labels:

        Returns the total time and label for every operation.

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, qc=None, states=None, **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments. If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: boolean

        If True, calculate the evolution with matrices exponentiation.

      qc: :class:`.QubitCircuit`, optional

        A quantum circuit. If given, it first calls the `load_circuit` and then calculate the evolution.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

  set_up_ops(N)

    Generate the Hamiltonians for the spinchain model and save them in the attribute ctrls.

    Parameters:
      N: int

        The number of qubits in the system.

  set_up_params(sx, sz, sxsy)

    Save the parameters in the attribute params and check the validity. The keys of params including “sx”, “sz”, and “sxsy”, each mapped to a list for parameters corresponding to each qubits. For coupling strength “sxsy”, list element i is the interaction between qubits i and i+1.

    Parameters:
      sx: float or list

        The coefficient of sigmax in the model

      sz: flaot or list

        The coefficient of sigmaz in the model

    Notes

    The coefficient of sxsy is defined in the submethods. All parameters will be multiplied by 2*pi for simplicity

  to_array(params, N)

    Transfer a parameter to an array.

class DispersiveCavityQED(N, correct_global_phase=True, num_levels=10, deltamax=1.0, epsmax=9.5, w0=10.0, wq=None, eps=9.5, delta=0.0, g=0.01, t1=None, t2=None)

  The processor based on the physical implementation of a dispersive cavity QED system. The available Hamiltonian of the system is predefined. For a given pulse amplitude matrix, the processor can calculate the state evolution under the given control pulse, either analytically or numerically. (Only additional attributes are documented here, for others please refer to the parent class `ModelProcessor`)

  Parameters:
    N: int

      The number of qubits in the system.

    correct_global_phase: float, optional

      Save the global phase, the analytical solution will track the global phase. It has no effect on the numerical solution.

    num_levels: int, optional

      The number of energy levels in the resonator.

    deltamax: int or list, optional

      The coefficients of sigma-x for each of the qubits in the system.

    epsmax: int or list, optional

      The coefficients of sigma-z for each of the qubits in the system.

    w0: int, optional

      The base frequency of the resonator.

    eps: int or list, optional

      The epsilon for each of the qubits in the system.

    delta: int or list, optional

      The epsilon for each of the qubits in the system.

    g: int or list, optional

      The interaction strength for each of the qubit with the resonator.

    t1: list or float

      Characterize the decoherence of amplitude damping for each qubit. A list of size N or a float for all qubits.

    t2: list of float

      Characterize the decoherence of dephasing for each qubit. A list of size N or a float for all qubits.

  Attributes:
    sx_ops: list

      A list of sigmax Hamiltonians for each qubit.

    sz_ops: list

      A list of sigmaz Hamiltonians for each qubit.

    cavityqubit_ops: list

      A list of interacting Hamiltonians between cavity and each qubit.

    sx_u: array_like

      Pulse matrix for sigmax Hamiltonians.

    sz_u: array_like

      Pulse matrix for sigmaz Hamiltonians.

    g_u: array_like

      Pulse matrix for interacting Hamiltonians between cavity and each qubit.

    wq: list of float

      The frequency of the qubits calculated from eps and delta for each qubit.

    Delta: list of float

      The detuning with respect to w0 calculated from wq and w0 for each qubit.

  add_control(qobj, targets=None, cyclic_permutation=False, label=None)

    Add a control Hamiltonian to the processor. It creates a new `Pulse` object for the device that is turned off (`tlist = None`, `coeff = None`). To activate the pulse, one can set its tlist and coeff.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The Hamiltonian for the control pulse..

      targets: list, optional

        The indices of the target qubits (or subquantum system of other dimensions).

      cyclic_permutation: bool, optional

        If true, the Hamiltonian will be expanded for all cyclic permutation of the target qubits.

      label: str, optional

        The label (name) of the pulse

  add_drift(qobj, targets, cyclic_permutation=False)

    Add a drift Hamiltonians. The drift Hamiltonians are intrinsic of the quantum system and cannot be controlled by external field.

    Parameters:
      qobj: :class:`qutip.Qobj`

        The drift Hamiltonian.

      targets: list

        The indices of the target qubits (or subquantum system of other dimensions).

  add_noise(noise)

    Add a noise object to the processor

    Parameters:
      noise: :class:`.Noise`

        The noise object defined outside the processor

  add_pulse(pulse)

    Add a new pulse to the device.

    Parameters:
      pulse: :class:`.Pulse`

        Pulse object to be added.

  property coeffs

    A list of the coefficients for all control pulses.

  property ctrls

    A list of Hamiltonians of all pulses.

  eliminate_auxillary_modes(U)

    Eliminate the auxillary modes like the cavity modes in cqed.

  get_full_coeffs(full_tlist=None)

    Return the full coefficients in a 2d matrix form. Each row corresponds to one pulse. If the tlist are different for different pulses, the length of each row will be same as the full_tlist (see method get_full_tlist). Interpolation is used for adding the missing coefficient according to spline_kind.

    Returns:
      coeffs: array-like 2d

        The coefficients for all ideal pulses.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the ideal pulses. If different pulses have different time steps, it will collect all the time steps in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the ideal evolution.

  get_noisy_pulses(device_noise=False, drift=False)

    It takes the pulses defined in the Processor and adds noise according to Processor.noise. It does not modify the pulses saved in Processor.pulses but returns a new list. The length of the new list of noisy pulses might be longer because of drift Hamiltonian and device noise. They will be added to the end of the pulses list.

    Parameters:
      device_noise: bool, optional

        If true, include pulse independent noise such as single qubit Relaxation. Default is False.

      drift: bool, optional

        If true, include drift Hamiltonians. Default is False.

    Returns:
      noisy_pulses: list of `Pulse`

        A list of noisy pulses.

  get_operators_labels()

    Get the labels for each Hamiltonian. It is used in the method``plot_pulses``. It is a 2-d nested list, in the plot, a different color will be used for each sublist.

  get_ops_and_u()

    Get the labels for each Hamiltonian.

    Returns:
      ctrls: list

        The list of Hamiltonians

      coeffs: array_like

        The transposed pulse matrix

  get_qobjevo(args=None, noisy=False)

    Create a `qutip.QobjEvo` representation of the evolution. It calls the method get_noisy_pulses and create the QobjEvo from it.

    Parameters:
      args: dict, optional

        Arguments for `qutip.QobjEvo`

      noisy: bool, optional

        If noise are included. Default is False.

    Returns:
      qobjevo: `qutip.QobjEvo`

        The `qutip.QobjEvo` representation of the unitary evolution.

      c_ops: list of `qutip.QobjEvo`

        A list of lindblad operators is also returned. if `noisy==Flase`, it is always an empty list.

  load_circuit(qc, schedule_mode='ASAP', compiler=None)

    Decompose a `QubitCircuit` in to the control amplitude generating the corresponding evolution.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each row corresponds to the control pulse sequence for one Hamiltonian.

  optimize_circuit(qc)

    Take a quantum circuit/algorithm and convert it into the optimal form/basis for the desired physical system.

    Parameters:
      qc: :class:`.QubitCircuit`

        Takes the quantum circuit to be implemented.

    Returns:
      qc: `QubitCircuit`

        The circuit representation with elementary gates that can be implemented in this model.

  plot_pulses(title=None, figsize=(12, 6), dpi=None, show_axis=False, rescale_pulse_coeffs=True, num_steps=1000)

    Plot the ideal pulse coefficients.

    Parameters:
      title: str, optional

        Title for the plot.

      figsize: tuple, optional

        The size of the figure.

      dpi: int, optional

        The dpi of the figure.

      show_axis: bool, optional

        If the axis are shown.

      rescale_pulse_coeffs: bool, optional

        Rescale the hight of each pulses.

      num_steps: int, optional

        Number of time steps in the plot.

    Returns:
      fig: matplotlib.figure.Figure

        The Figure object for the plot.

      ax: matplotlib.axes._subplots.AxesSubplot

        The axes for the plot.

    Notes

    `plot_pulses` only works for array_like coefficients

  pulse_matrix(dt=0.01)

    Generates the pulse matrix for the desired physical system.

    Returns:
      t, u, labels:

        Returns the total time and label for every operation.

  read_coeff(file_name, inctime=True)

    Read the control amplitudes matrix and time list saved in the file by save_amp.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list in included in the first column.

    Returns:
      tlist: array_like

        The time list read from the file.

      coeffs: array_like

        The pulse matrix read from the file.

  remove_pulse(indices=None, label=None)

    Remove the control pulse with given indices.

    Parameters:
      indices: int or list of int

        The indices of the control Hamiltonians to be removed.

      label: str

        The label of the pulse

  run(qc=None)

    Calculate the propagator of the evolution by matrix exponentiation. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by load_circuit.

    Returns:
      U_list: list

        The propagator matrix obtained from the physical implementation.

  run_analytically(init_state=None, qc=None)

    Simulate the state evolution under the given qutip.QubitCircuit with matrice exponentiation. It will calculate the propagator with matrix exponentiation and return a list of `qutip.Qobj`. This method won’t include noise or collpase.

    Parameters:
      qc: :class:`.QubitCircuit`, optional

        Takes the quantum circuit to be implemented. If not given, use the quantum circuit saved in the processor by `load_circuit`.

      init_state: :class:`qutip.Qobj`, optional

        The initial state of the qubits in the register.

    Returns:
      U_list: list

        A list of propagators obtained for the physical implementation.

  run_state(init_state=None, analytical=False, qc=None, states=None, **kwargs)

    If analytical is False, use `qutip.mesolve` to calculate the time of the state evolution and return the result. Other arguments of mesolve can be given as keyword arguments. If analytical is True, calculate the propagator with matrix exponentiation and return a list of matrices.

    Parameters:
      init_state: Qobj

        Initial density matrix or state vector (ket).

      analytical: boolean

        If True, calculate the evolution with matrices exponentiation.

      qc: :class:`.QubitCircuit`, optional

        A quantum circuit. If given, it first calls the `load_circuit` and then calculate the evolution.

      states: :class:`qutip.Qobj`, optional

        Old API, same as init_state.

      **kwargs

        Keyword arguments for the qutip solver.

    Returns:
      evo_result: `qutip.solver.Result`

        If `analytical` is False, an instance of the class `qutip.solver.Result` will be returned.

        If `analytical` is True, a list of matrices representation is returned.

  save_coeff(file_name, inctime=True)

    Save a file with the control amplitudes in each timeslot.

    Parameters:
      file_name: string

        Name of the file.

      inctime: bool, optional

        True if the time list should be included in the first column.

  set_all_tlist(tlist)

    Set the same tlist for all the pulses.

    Parameters:
      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

  set_up_ops(N)

    Generate the Hamiltonians for the spinchain model and save them in the attribute ctrls.

    Parameters:
      N: int

        The number of qubits in the system.

  set_up_params(N, num_levels, deltamax, epsmax, w0, wq, eps, delta, g)

    Save the parameters in the attribute params and check the validity. The keys of params including “sx”, “sz”, “w0”, “eps”, “delta” and “g”, each mapped to a list for parameters corresponding to each qubits. For coupling strength “g”, list element i is the interaction between qubits i and i+1.

    Parameters:
      N: int

        The number of qubits in the system.

      num_levels: int

        The number of energy levels in the resonator.

      deltamax: list

        The coefficients of sigma-x for each of the qubits in the system.

      epsmax: list

        The coefficients of sigma-z for each of the qubits in the system.

      wo: int

        The base frequency of the resonator.

      wq: list

        The frequency of the qubits.

      eps: list

        The epsilon for each of the qubits in the system.

      delta: list

        The delta for each of the qubits in the system.

      g: list

        The interaction strength for each of the qubit with the resonator.

    Notes

    All parameters will be multiplied by 2*pi for simplicity

  to_array(params, N)

    Transfer a parameter to an array.

class Noise

  The base class representing noise in a processor. The noise object can be added to `Processor` and contributes to evolution.

  get_noisy_dynamics(dims, pulses, systematic_noise)

    Return a pulses list added with noise and the pulse independent noise in a dummy Pulse object.

    Parameters:
      dims: list, optional

        The dimension of the components system, the default value is [2,2…,2] for qubits system.

      pulses: list of :class:`.Pulse`

        The input pulses, on which the noise object is to be applied.

      systematic_noise: :class:`.Pulse`

        The dummy pulse with no ideal control element.

    Returns:
      noisy_pulses: list of `Pulse`

        Noisy pulses.

      systematic_noise: `Pulse`

        The dummy pulse representing pulse independent noise.

class DecoherenceNoise(c_ops, targets=None, coeff=None, tlist=None, all_qubits=False)

  The decoherence noise in a processor. It generates lindblad noise according to the given collapse operator c_ops.

  Parameters:
    c_ops: :class:`qutip.Qobj` or list

      The Hamiltonian representing the dynamics of the noise.

    targets: int or list, optional

      The indices of qubits that are acted on. Default is on all qubits

    coeff: list, optional

      A list of the coefficients for the control Hamiltonians.

    tlist: array_like, optional

      A NumPy array specifies the time of each coefficient.

    all_qubits: bool, optional

      If c_ops contains only single qubits collapse operator, `all_qubits=True` will allow it to be applied to all qubits.

  Attributes:
    c_ops: :class:`qutip.Qobj` or list

      The Hamiltonian representing the dynamics of the noise.

    targets: int or list

      The indices of qubits that are acted on.

    coeff: list

      A list of the coefficients for the control Hamiltonians.

    tlist: array_like

      A NumPy array specifies the time of each coefficient.

    all_qubits: bool

      If c_ops contains only single qubits collapse operator, `all_qubits=True` will allow it to be applied to all qubits.

  get_noisy_dynamics(dims=None, pulses=None, systematic_noise=None)

    Return a pulses list added with noise and the pulse independent noise in a dummy Pulse object.

    Parameters:
      dims: list, optional

        The dimension of the components system, the default value is [2,2…,2] for qubits system.

      pulses: list of :class:`.Pulse`

        The input pulses, on which the noise object is to be applied.

      systematic_noise: :class:`.Pulse`

        The dummy pulse with no ideal control element.

    Returns:
      noisy_pulses: list of `Pulse`

        Noisy pulses.

      systematic_noise: `Pulse`

        The dummy pulse representing pulse independent noise.

class RelaxationNoise(t1=None, t2=None, targets=None)

  The decoherence on each qubit characterized by two time scales t1 and t2.

  Parameters:
    t1: float or list, optional

      Characterize the decoherence of amplitude damping for each qubit.

    t2: float or list, optional

      Characterize the decoherence of dephasing for each qubit.

    targets: int or list, optional

      The indices of qubits that are acted on. Default is on all qubits

  Attributes:
    t1: float or list

      Characterize the decoherence of amplitude damping for each qubit.

    t2: float or list

      Characterize the decoherence of dephasing for each qubit.

    targets: int or list

      The indices of qubits that are acted on.

  get_noisy_dynamics(dims=None, pulses=None, systematic_noise=None)

    Return a pulses list added with noise and the pulse independent noise in a dummy Pulse object.

    Parameters:
      dims: list, optional

        The dimension of the components system, the default value is [2,2…,2] for qubits system.

      pulses: list of :class:`.Pulse`

        The input pulses, on which the noise object is to be applied.

      systematic_noise: :class:`.Pulse`

        The dummy pulse with no ideal control element.

    Returns:
      noisy_pulses: list of `Pulse`

        Noisy pulses.

      systematic_noise: `Pulse`

        The dummy pulse representing pulse independent noise.

class ControlAmpNoise(coeff, tlist=None, indices=None)

  The noise in the amplitude of the control pulse.

  Parameters:
    coeff: list

      A list of the coefficients for the control Hamiltonians. For available choices, see `qutip.QobjEvo`.

    tlist: array_like, optional

      A NumPy array specifies the time of each coefficient.

    indices: list of int, optional

      The indices of target pulse in the list of pulses.

    Attributes
    ———-
    coeff: list

      A list of the coefficients for the control Hamiltonians. For available choices, see `qutip.QobjEvo`.

    tlist: array_like

      A NumPy array specifies the time of each coefficient.

    indices: list of int

      The indices of target pulse in the list of pulses.

  get_noisy_dynamics(dims=None, pulses=None, systematic_noise=None)

    Return a pulses list added with noise and the pulse independent noise in a dummy Pulse object.

    Parameters:
      dims: list, optional

        The dimension of the components system, the default value is [2,2…,2] for qubits system.

      pulses: list of :class:`.Pulse`

        The input pulses, on which the noise object is to be applied.

      systematic_noise: :class:`.Pulse`

        The dummy pulse with no ideal control element.

    Returns:
      noisy_pulses: list of `Pulse`

        Noisy pulses.

      systematic_noise: `Pulse`

        The dummy pulse representing pulse independent noise.

class RandomNoise(dt, rand_gen, indices=None, **kwargs)

  Random noise in the amplitude of the control pulse. The arguments for the random generator need to be given as key word arguments.

  Parameters:
    dt: float, optional

      The time interval between two random amplitude. The coefficients of the noise are the same within this time range.

    rand_gen: numpy.random, optional

      A random generator in numpy.random, it has to take a `size` parameter as the size of random numbers in the output array.

    indices: list of int, optional

      The indices of target pulse in the list of pulses.

    **kwargs:

      Key word arguments for the random number generator.

  Examples

      >>> gaussnoise = RandomNoise(             dt=0.1, rand_gen=np.random.normal, loc=mean, scale=std)

  Attributes:
    dt: float, optional

      The time interval between two random amplitude. The coefficients of the noise are the same within this time range.

    rand_gen: numpy.random, optional

      A random generator in numpy.random, it has to take a `size` parameter.

    indices: list of int

      The indices of target pulse in the list of pulses.

    **kwargs:

      Key word arguments for the random number generator.

  get_noisy_dynamics(dims=None, pulses=None, systematic_noise=None)

    Return a pulses list added with noise and the pulse independent noise in a dummy Pulse object.

    Parameters:
      dims: list, optional

        The dimension of the components system, the default value is [2,2…,2] for qubits system.

      pulses: list of :class:`.Pulse`

        The input pulses, on which the noise object is to be applied.

      systematic_noise: :class:`.Pulse`

        The dummy pulse with no ideal control element.

    Returns:
      noisy_pulses: list of `Pulse`

        Noisy pulses.

      systematic_noise: `Pulse`

        The dummy pulse representing pulse independent noise.

class Pulse(qobj, targets, tlist=None, coeff=None, spline_kind=None, label='')

  Representation of a control pulse and the pulse dependent noise. The pulse is characterized by the ideal control pulse, the coherent noise and the lindblad noise. The later two are lists of noisy evolution dynamics. Each dynamic element is characterized by four variables: qobj, targets, tlist and coeff.

  See examples for different construction behavior.

  Parameters:
    qobj: :class:’qutip.Qobj’

      The Hamiltonian of the ideal pulse.

    targets: list

      target qubits of the ideal pulse (or subquantum system of other dimensions).

    tlist: array-like, optional

      tlist of the ideal pulse. A list of time at which the time-dependent coefficients are applied. tlist does not have to be equidistant, but must have the same length or one element shorter compared to coeff. See documentation for the parameter spline_kind.

    coeff: array-like or bool, optional

      Time-dependent coefficients of the ideal control pulse. If an array, the length must be the same or one element longer compared to tlist. See documentation for the parameter spline_kind. If a bool, the coefficient is a constant 1 or 0.

    spline_kind: str, optional

      Type of the coefficient interpolation: “step_func” or “cubic”.

      -“step_func”: The coefficient will be treated as a step function. E.g. `tlist=[0,1,2]` and `coeff=[3,2]`, means that the coefficient is 3 in t=[0,1) and 2 in t=[2,3). It requires `len(coeff)=len(tlist)-1` or `len(coeff)=len(tlist)`, but in the second case the last element of coeff has no effect.

      -“cubic”: Use cubic interpolation for the coefficient. It requires `len(coeff)=len(tlist)`

    label: str

      The label (name) of the pulse.

  Examples

  Create a pulse that is turned off

      >>> Pulse(sigmaz(), 0)
      >>> Pulse(sigmaz(), 0, None, None)

  Create a time dependent pulse

      >>> tlist = np.array([0., 1., 2., 4.])
      >>> coeff = np.array([0.5, 1.2, 0.8])
      >>> spline_kind = "step_func"
      >>> Pulse(sigmaz(), 0, tlist=tlist, coeff=coeff, spline_kind="step_func")

  Create a time independent pulse

      >>> Pulse(sigmaz(), 0, coeff=True)

  Create a constant pulse with time range

      >>> Pulse(sigmaz(), 0, tlist=tlist, coeff=True)

  Create an dummy Pulse (H=0)

      >>> Pulse(None, None)

  Attributes:
    ideal_pulse: :class:`._EvoElement`

      The ideal dynamic of the control pulse.

    coherent_noise: list of :class:`._EvoElement`

      The coherent noise caused by the control pulse. Each dynamic element is still characterized by a time-dependent Hamiltonian.

    lindblad_noise: list of :class:`._EvoElement`

      The dissipative noise of the control pulse. Each dynamic element will be treated as a (time-dependent) lindblad operator in the master equation.

    spline_kind: str

      See parameter spline_kind.

    label: str

      See parameter label.

  add_coherent_noise(qobj, targets, tlist=None, coeff=None)

    Add a new (time-dependent) Hamiltonian to the coherent noise.

    Parameters:
      qobj: :class:’qutip.Qobj’

        The Hamiltonian of the pulse.

      targets: list

        target qubits of the pulse (or subquantum system of other dimensions).

      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. tlist does not have to be equidistant, but must have the same length or one element shorter compared to coeff. See documentation for the parameter spline_kind of `Pulse`.

      coeff: array-like or bool, optional

        Time-dependent coefficients of the pulse noise. If an array, the length must be the same or one element longer compared to tlist. See documentation for the parameter spline_kind of `Pulse`. If a bool, the coefficient is a constant 1 or 0.

  add_lindblad_noise(qobj, targets, tlist=None, coeff=None)

    Add a new (time-dependent) lindblad noise to the coherent noise.

    Parameters:
      qobj: :class:’qutip.Qobj’

        The collapse operator of the lindblad noise.

      targets: list

        target qubits of the collapse operator (or subquantum system of other dimensions).

      tlist: array-like, optional

        A list of time at which the time-dependent coefficients are applied. tlist does not have to be equidistant, but must have the same length or one element shorter compared to coeff. See documentation for the parameter spline_kind of `Pulse`.

      coeff: array-like or bool, optional

        Time-dependent coefficients of the pulse noise. If an array, the length must be the same or one element longer compared to tlist. See documentation for the parameter spline_kind of `Pulse`. If a bool, the coefficient is a constant 1 or 0.

  property coeff

    See parameter coeff.

  get_full_tlist(tol=1e-10)

    Return the full tlist of the pulses and noise. It means that if different `tlist` are present, they will be merged to one with all time points stored in a sorted array.

    Returns:
      full_tlist: array-like 1d

        The full time sequence for the noisy evolution.

  get_ideal_qobj(dims)

    Get the Hamiltonian of the ideal pulse.

    Parameters:
      dims: int or list

        Dimension of the system. If int, we assume it is the number of qubits in the system. If list, it is the dimension of the component systems.

    Returns:
      qobj: `qutip.Qobj`

        The Hamiltonian of the ideal pulse.

  get_ideal_qobjevo(dims)

    Get a QobjEvo representation of the ideal evolution.

    Parameters:
      dims: int or list

        Dimension of the system. If int, we assume it is the number of qubits in the system. If list, it is the dimension of the component systems.

    Returns:
      ideal_evo: `qutip.QobjEvo`

        A QobjEvo representing the ideal evolution.

  get_noisy_qobjevo(dims)

    Get the `QobjEvo` representation of the noisy evolution. The result can be used directly as input for the qutip solvers.

    Parameters:
      dims: int or list

        Dimension of the system. If int, we assume it is the number of qubits in the system. If list, it is the dimension of the component systems.

    Returns:
      noisy_evo: `qutip.QobjEvo`

        A `QobjEvo` representing the ideal evolution and coherent noise.

      c_ops: list of `qutip.QobjEvo`

        A list of (time-dependent) lindbald operators.

  print_info()

    Print the information of the pulse, including the ideal dynamics, the coherent noise and the lindblad noise.

  property qobj

    See parameter qobj.

  property targets

    See parameter targets.

  property tlist

    See parameter tlist

class GateCompiler(N, params=None, pulse_dict=None)

  Base class. It compiles a `QubitCircuit` into the pulse sequence for the processor. The core member function compile calls compiling method from the sub-class and concatenate the compiled pulses.

  Parameters:
    N: int

      The number of the component systems.

    params: dict, optional

      A Python dictionary contains the name and the value of the parameters, such as laser frequency, detuning etc. It will be saved in the class attributes and can be used to calculate the control pulses.

    pulse_dict: dict, optional

      A map between the pulse label and its index in the pulse list. If given, the compiled pulse can be identified with `(pulse_label, coeff)`, instead of `(pulse_index, coeff)`. The number of key-value pairs should match the number of pulses in the processor. If it is empty, an integer `pulse_index` needs to be used in the compiling routine saved under the attributes `gate_compiler`.

  Attributes:
    gate_compiler: dict

      The Python dictionary in the form of {gate_name: compiler_function}. It saves the compiling routine for each gate. See sub-classes for implementation. Note that for continuous pulse, the first coeff should always be 0.

    args: dict

      Arguments for individual compiling routines. It adds more flexibility in customizing compiler.

  compile(circuit, schedule_mode=None, args=None)

    Compile the the native gates into control pulse sequence. It calls each compiling method and concatenates the compiled pulses.

    Parameters:
      circuit: :class:`.QubitCircuit` or list of

        `Gate` A list of elementary gates that can be implemented in the corresponding hardware. The gate names have to be in gate_compiler.

      schedule_mode: str, optional

        `"ASAP"` for “as soon as possible” or `"ALAP"` for “as late as possible” or `False` or `None` for no schedule. Default is None.

      args: dict, optional

        A dictionary of arguments used in a specific gate compiler function.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape `(len(ctrls), len(tlist))`. Each row corresponds to the control pulse sequence for one Hamiltonian.

  globalphase_compiler(gate, args)

    Compiler for the GLOBALPHASE gate

class CavityQEDCompiler(N, params, pulse_dict, global_phase=0.0)

  Decompose a `QubitCircuit` into the pulse sequence for the processor.

  Parameters:
    N: int

      The number of qubits in the system.

    params: dict

      A Python dictionary contains the name and the value of the parameters. See `DispersiveCavityQED.set_up_params` for the definition.

    global_phase: float, optional

      Record of the global phase change and will be returned.

    pulse_dict: dict, optional

      A map between the pulse label and its index in the pulse list. If given, the compiled pulse can be identified with `(pulse_label, coeff)`, instead of `(pulse_index, coeff)`. The number of key-value pairs should match the number of pulses in the processor. If it is empty, an integer `pulse_index` needs to be used in the compiling routine saved under the attributes `gate_compiler`.

  Attributes:
    N: int

      The number of the component systems.

    params: dict

      A Python dictionary contains the name and the value of the parameters, such as laser frequency, detuning etc.

    pulse_dict: dict

      A map between the pulse label and its index in the pulse list.

    gate_compiler: dict

      The Python dictionary in the form of {gate_name: decompose_function}. It saves the decomposition scheme for each gate.

  compile(circuit, schedule_mode=None, args=None)

    Compile the the native gates into control pulse sequence. It calls each compiling method and concatenates the compiled pulses.

    Parameters:
      circuit: :class:`.QubitCircuit` or list of

        `Gate` A list of elementary gates that can be implemented in the corresponding hardware. The gate names have to be in gate_compiler.

      schedule_mode: str, optional

        `"ASAP"` for “as soon as possible” or `"ALAP"` for “as late as possible” or `False` or `None` for no schedule. Default is None.

      args: dict, optional

        A dictionary of arguments used in a specific gate compiler function.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape `(len(ctrls), len(tlist))`. Each row corresponds to the control pulse sequence for one Hamiltonian.

  globalphase_compiler(gate, args)

    Compiler for the GLOBALPHASE gate

  iswap_compiler(gate, args)

    Compiler for the ISWAP gate

  rx_compiler(gate, args)

    Compiler for the RX gate

  rz_compiler(gate, args)

    Compiler for the RZ gate

  sqrtiswap_compiler(gate, args)

    Compiler for the SQRTISWAP gate

    Notes

    This version of sqrtiswap_compiler has very low fidelity, please use iswap

class SpinChainCompiler(N, params, pulse_dict, setup='linear', global_phase=0.0)

  Compile a `QubitCircuit` into the pulse sequence for the processor.

  Parameters:
    N: int

      The number of qubits in the system.

    params: dict

      A Python dictionary contains the name and the value of the parameters. See `SpinChain.set_up_params` for the definition.

    setup: string

      “linear” or “circular” for two sub-classes.

    global_phase: bool

      Record of the global phase change and will be returned.

    pulse_dict: dict, optional

      A map between the pulse label and its index in the pulse list. If given, the compiled pulse can be identified with `(pulse_label, coeff)`, instead of `(pulse_index, coeff)`. The number of key-value pairs should match the number of pulses in the processor. If it is empty, an integer `pulse_index` needs to be used in the compiling routine saved under the attributes `gate_compiler`.

  Attributes:
    N: int

      The number of the component systems.

    params: dict

      A Python dictionary contains the name and the value of the parameters, such as laser frequency, detuning etc.

    pulse_dict: dict

      A map between the pulse label and its index in the pulse list.

    gate_compiler: dict

      The Python dictionary in the form of {gate_name: decompose_function}. It saves the decomposition scheme for each gate.

    setup: string

      “linear” or “circular” for two sub-classes.

    global_phase: bool

      Record of the global phase change and will be returned.

  compile(circuit, schedule_mode=None, args=None)

    Compile the the native gates into control pulse sequence. It calls each compiling method and concatenates the compiled pulses.

    Parameters:
      circuit: :class:`.QubitCircuit` or list of

        `Gate` A list of elementary gates that can be implemented in the corresponding hardware. The gate names have to be in gate_compiler.

      schedule_mode: str, optional

        `"ASAP"` for “as soon as possible” or `"ALAP"` for “as late as possible” or `False` or `None` for no schedule. Default is None.

      args: dict, optional

        A dictionary of arguments used in a specific gate compiler function.

    Returns:
      tlist: array_like

        A NumPy array specifies the time of each coefficient

      coeffs: array_like

        A 2d NumPy array of the shape `(len(ctrls), len(tlist))`. Each row corresponds to the control pulse sequence for one Hamiltonian.

  globalphase_compiler(gate, args)

    Compiler for the GLOBALPHASE gate

  iswap_compiler(gate, args)

    Compiler for the ISWAP gate

  rx_compiler(gate, args)

    Compiler for the RX gate

  rz_compiler(gate, args)

    Compiler for the RZ gate

  sqrtiswap_compiler(gate, args)

    Compiler for the SQRTISWAP gate

class Scheduler(method='ALAP', constraint_functions=None)

  A gate (pulse) scheduler for quantum circuits (instructions). It schedules a given circuit or instructions to reduce the total execution time by parallelization. It uses heuristic methods mainly from in https://doi.org/10.1117/12.666419.

  The scheduler includes two methods, “ASAP”, as soon as possible, and “ALAP”, as late as possible. The later is commonly used in quantum computation because of the finite lifetime of qubits.

  The scheduler aims at pulse schedule and therefore does not consider merging gates to reduce the gates number. It assumes that the input circuit is optimized at the gate level and matches the hardware topology.

  Parameters:
    method: str

      “ASAP” for as soon as possible. “ALAP” for as late as possible.

    constraint_functions: list, optional

      A list of hardware constraint functions. Default includes a function qubit_contraint, i.e. one qubit cannot be used by two gates at the same time.

  apply_constraint(ind1, ind2, instructions)

    Apply hardware constraint to check if two instructions can be executed in parallel.

    Parameters:
      ind1, ind2: int

        indices of the two instructions

      instructions: list

        The instruction list

  commutation_rules(ind1, ind2, instructions)

    Determine if two gates commute, given that their used qubits overlap. Since usually the input gates are already in a universal gate sets, it uses an oversimplified condition:

    If the two gates do not have the same name, they are considered as not commuting. If they are the same gate and have the same controls or targets, they are considered as commuting. E.g. CNOT 0, 1 commute with CNOT 0, 2.

  schedule(circuit, gates_schedule=False, return_cycles_list=False, random_shuffle=False, repeat_num=0)

    Schedule a QubitCircuit, a list of Gates or a list of Instruction. For pulse schedule, the execution time for each Instruction is given in its duration attributes.

    The scheduler first generates a quantum gates dependency graph, containing information about which gates have to be executed before some other gates. The graph preserves the mobility of the gates, i.e. commuting gates are not dependent on each other, even if they use the same qubits. Next, it computes the longest distance of each node to the start and end nodes. The distance for each dependency arrow is defined by the execution time of the instruction (By default, it is 1 for all gates). This is used as a priority measure in the next step. The gate with a longer distance to the end node and a shorter distance to the start node has higher priority. In the last step, it uses a list-schedule algorithm with hardware constraint and priority and returns a list of cycles for gates/instructions.

    For pulse schedule, an additional step is required to compute the start time of each instruction. It adds the additional dependency caused by hardware constraint to the graph and recomputes the distance of each node to the start and end node. This distance is then converted to the start time of each instruction.

    Parameters:
      circuit: QubitCircuit or list

        For gate schedule, it should be a QubitCircuit or a list of Gate objects. For pulse schedule, it should be a list of Instruction objects, each with an attribute duration that indicates the execution time of this instruction.

      gates_schedule: bool, optional

        True, if only gates schedule is needed. This saves some computation that is only useful to pulse schedule. If the input circuit is a QubitCircuit, it will be assigned to True automatically. Otherwise, the default is False.

      return_cycles_list: bool, optional

        If True, the method returns the cycles_list, e.g. [{0, 2}, {1, 3}], which means that the first cycle contains gates0 and gates2 while the second cycle contains gates1 and gates3. It is only usefull for gates schedule.

      random_shuffle: bool, optional

        If the commuting gates are randomly scuffled to explore larger search space.

      repeat_num: int, optional

        Repeat the scheduling several times and use the best result. Used together with `random_shuffle=Ture`.

    Returns:
      gate_cycle_indices or instruction_start_time: list

        The cycle indices for each gate or the start time for each instruction.

    Examples

        >>> from qutip.qip.circuit import QubitCircuit
        >>> from qutip.qip.scheduler import Scheduler
        >>> circuit = QubitCircuit(7)
        >>> circuit.add_gate("SNOT", 3)  # gate0
        >>> circuit.add_gate("CZ", 5, 3)  # gate1
        >>> circuit.add_gate("CZ", 4, 3)  # gate2
        >>> circuit.add_gate("CZ", 2, 3)  # gate3
        >>> circuit.add_gate("CZ", 6, 5)  # gate4
        >>> circuit.add_gate("CZ", 2, 6)  # gate5
        >>> circuit.add_gate("SWAP", [0, 2])  # gate6
        >>>
        >>> scheduler = Scheduler("ASAP")
        >>> scheduler.schedule(circuit, gates_schedule=True)
        [0, 1, 3, 2, 2, 3, 4]

    The result list is the cycle indices for each gate. It means that the circuit can be executed in 5 gate cycles: `[gate0, gate1, (gate3, gate4), (gate2, gate5), gate6]` Notice that gate3 and gate4 commute with gate2, therefore, the order is changed to reduce the number of cycles.

class Instruction(gate, tlist=None, pulse_info=(), duration=1)

  The instruction that implements a quantum gate. It contains the control pulse required to implement the gate on a particular hardware model.

  Parameters:
    gate: :class:`.Gate`

      The quantum gate.

    duration: list, optional

      The execution time needed for the instruction.

    tlist: array_like, optional

      A list of time at which the time-dependent coefficients are applied. See `Pulse` for detailed information`

    pulse_info: list, optional

      A list of tuples, each tuple corresponding to a pair of pulse label and pulse coefficient, in the format (str, array_like). This pulses will implement the desired gate.

  Attributes:
    targets: list, optional

      The target qubits.

    controls: list, optional

      The control qubits.

    used_qubits: set

      Union of the control and target qubits.

## Optimal control

class Optimizer(config, dyn, params=None)

  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_level integer

      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.

    alg string

      Algorithm to use in pulse optimisation. Options are:

      - ‘GRAPE’ (default) - GRadient Ascent Pulse Engineering

      - ‘CRAB’ - Chopped RAndom Basis

    alg_params Dictionary

      Options that are specific to the pulse optim algorithm `alg`.

    disp_conv_msg bool

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

    optim_method string

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

    method_params Dictionary

      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_grad bool

      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_lbound float 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_ubound float 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

    bounds List 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

    dynamics Dynamics (subclass instance)

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

    config OptimConfig instance

      various configuration options (see OptimConfig for details)

    termination_conditions TerminationCondition instance

      attributes determine when the optimisation will end

    pulse_generator PulseGen (subclass instance)

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

    stats Stats

      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 `qutip.control.dump.OptimDump`

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

    `dumping` string

      The level of data dumping that will occur during the optimisation

    dump_to_file bool

      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_dir string

      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(params=None)

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

  apply_params(params=None)

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

  property dumping

    The level of data dumping that will occur during the optimisation

    - NONE : No processing data dumped (Default)

    - SUMMARY : A summary at each iteration will be recorded

    - FULL : All logs will be generated and dumped

    - CUSTOM : Some customised level of dumping

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

  fid_err_func_wrapper(*args)

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

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

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

  fid_err_grad_wrapper(*args)

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

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

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

  init_optim(term_conds)

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

  iter_step_callback_func(*args)

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

  run_optimization(term_conds=None)

    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)

  Implements the run_optimization method using the BFGS algorithm

  run_optimization(term_conds=None)

    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)

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

  Attributes:
    max_metric_corr integer

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

  init_optim(term_conds)

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

  run_optimization(term_conds=None)

    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)

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

  AJGP ToDo: Add citation here

  init_optim(term_conds)

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

class OptimizerCrabFmin(config, dyn, params=None)

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

  References

  [1]

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

  [2]

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

  run_optimization(term_conds=None)

    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

  A summary of the most recent iteration of the pulse optimisation

  Attributes:
    iter_num int

      Iteration number of the pulse optimisation

    fid_func_call_num int

      Fidelity function call number of the pulse optimisation

    grad_func_call_num int

      Gradient function call number of the pulse optimisation

    fid_err float

      Fidelity error

    grad_norm float

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

    wall_time float

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

class TerminationConditions

  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_targ float

      Target fidelity error

    fid_goal float

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

    max_wall_time float

      # maximum time for optimisation (seconds)

    min_gradient_norm float

      Minimum normalised gradient after which optimisation will terminate

    max_iterations integer

      Maximum iterations of the optimisation algorithm

    max_fid_func_calls integer

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

    accuracy_factor float

      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

  Attributes give the result of the pulse optimisation attempt

  Attributes:
    termination_reason string

      Description of the reason for terminating the optimisation

    fidelity float

      final (normalised) fidelity that was achieved

    initial_fid_err float

      fidelity error before optimisation starting

    fid_err float

      final fidelity error that was achieved

    goal_achieved boolean

      True is the fidely error achieved was below the target

    grad_norm_final float

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

    grad_norm_min_reached float

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

    num_iter integer

      Number of iterations of the optimisation algorithm completed

    max_iter_exceeded boolean

      True if the iteration limit was reached

    max_fid_func_exceeded boolean

      True if the fidelity function call limit was reached

    wall_time float

      time elapsed during the optimisation

    wall_time_limit_exceeded boolean

      True if the wall time limit was reached

    time array[num_tslots+1] of float

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

    initial_amps array[num_tslots, n_ctrls]

      The amplitudes at the start of the optimisation

    final_amps array[num_tslots, n_ctrls]

      The amplitudes at the end of the optimisation

    evo_full_final Qobj

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

    evo_full_initial Qobj

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

    stats Stats

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

    optimizer Optimizer

      Instance of the Optimizer used to generate the result

class Dynamics(optimconfig, params=None)

  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_level integer

      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.

    stats Stats

      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_computer TimeslotComputer (subclass instance)

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

    prop_computer PropagatorComputer (subclass instance)

      Used to compute the propagators and their gradients

    fid_computer FidelityComputer (subclass instance)

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

    memory_optimization int

      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_dtype type

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

    cache_phased_dyn_gen bool

      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_grad bool

      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_tslots integer

      Number of timeslots (aka timeslices)

    `num_ctrls` integer

      calculate the of controls from the length of the control list

    evo_time float

      Total time for the evolution

    tau array[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

    time array[num_tslots+1] of float

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

    drift_dyn_gen Qobj 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_gen List of Qobj

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

    initial Qobj

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

    target Qobj

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

    ctrl_amps array[num_tslots, num_ctrls] of float

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

    initial_ctrl_scaling float

      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_offset float

      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 Qobj

      List of combined dynamics generators (Qobj) for each timeslot

    `prop` list of Qobj

      List of propagators (Qobj) for each timeslot

    `prop_grad` array[num_tslots, num_ctrls] of Qobj

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

    `fwd_evo` List of Qobj

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

    `onwd_evo` List of Qobj

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

    `onto_evo` List of Qobj

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

    evo_current Boolean

      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_prec float

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

    def_amps_fname string

      Default name for the output used when save_amps is called

    unitarity_check_level int

      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 `qutip.control.dump.DynamicsDump`

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

    `dumping` string

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

    dump_to_file bool

      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_dir string

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

  apply_params(params=None)

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

  combine_dyn_gen(k)

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

  compute_evolution()

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

  property dumping

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

    - NONE : No processing data dumped (Default)

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

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

    - CUSTOM : Some customised level of dumping

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

  property dyn_gen

    List of combined dynamics generators (Qobj) for each timeslot

  property dyn_gen_phase

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

  flag_system_changed()

    Flag evolution, fidelity and gradients as needing recalculation

  property full_evo

    Full evolution - time evolution at final time slot

  property fwd_evo

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

  get_ctrl_dyn_gen(j)

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

  get_drift_dim()

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

  get_dyn_gen(k)

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

  get_num_ctrls()

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

  init_timeslots()

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

  initialize_controls(amps, init_tslots=True)

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

  property num_ctrls

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

  property onto_evo

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

  property onwd_evo

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

  property phase_application

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

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

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

    - ‘custom’ : Customised phase application

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

    Type:

      phase_application

  property prop

    List of propagators (Qobj) for each timeslot

  property prop_grad

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

  refresh_drift_attribs()

    Reset the dyn_shape, dyn_dims and time_depend_drift attribs

  save_amps(file_name=None, times=None, amps=None, verbose=False)

    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_name string

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

      times List 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

      amps Array[num_tslots, num_ctrls]

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

      verbose Boolean

        If True then an info message will be logged

  unitarity_check()

    Checks whether all propagators are unitary

  update_ctrl_amps(new_amps)

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

class DynamicsGenMat(optimconfig, params=None)

  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)

  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_ham Qobj

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

    ctrl_ham List of Qobj

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

    H List 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()

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

  initialize_controls(amplitudes, init_tslots=True)

    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)

  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:
    omega array[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)

  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_level integer

      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_exact boolean

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

  apply_params(params=None)

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

  reset()

    reset any configuration data

class PropCompApproxGrad(dynamics, params=None)

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

  reset()

    reset any configuration data

class PropCompDiag(dynamics, params=None)

  Coumputes the propagator exponentiation using diagonalisation of of the dynamics generator

  reset()

    reset any configuration data

class PropCompFrechet(dynamics, params=None)

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

  reset()

    reset any configuration data

class FidelityComputer(dynamics, params=None)

  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_level integer

      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_norm float

      Normalisation constant

    fid_norm_func function

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

    grad_norm_func function

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

    uses_onwd_evo boolean

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

    uses_onto_evo boolean
      flag to specify whether the onto_evo evolution operator

        (see Dynamics) is used by the FidelityComputer

    fid_err float

      Last computed value of the fidelity error

    fidelity float

      Last computed value of the normalised fidelity

    fidelity_current boolean

      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_norm float

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

    fid_err_grad_current boolean

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

  apply_params(params=None)

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

  clear()

    clear any temporarily held status data

  flag_system_changed()

    Flag fidelity and gradients as needing recalculation

  get_fid_err()

    returns the absolute distance from the maximum achievable fidelity

  get_fid_err_gradient()

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

  init_comp()

    initialises the computer based on the configuration of the Dynamics

  reset()

    reset any configuration data and clear any temporarily held status data

class FidCompUnitary(dynamics, params=None)

  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_option string
      determines how global phase is treated in fidelity calculations:

        PSU - global phase ignored SU - global phase included

    fidelity_prenorm complex

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

    fidelity_prenorm_current boolean

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

  clear()

    clear any temporarily held status data

  compute_fid_grad()

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

  flag_system_changed()

    Flag fidelity and gradients as needing recalculation

  get_fid_err()

    Gets the absolute error in the fidelity

  get_fid_err_gradient()

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

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

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

  init_comp()

    Check configuration and initialise the normalisation

  init_normalization()

    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_PSU(A)
  normalize_SU(A)
  normalize_gradient_PSU(grad)

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

  normalize_gradient_SU(grad)

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

  reset()

    reset any configuration data and clear any temporarily held status data

  set_phase_option(phase_option=None)

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

class FidCompTraceDiff(dynamics, params=None)

  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_factor float

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

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

    Gets the absolute error in the fidelity

  get_fid_err_gradient()

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

  init_comp()

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

  reset()

    reset any configuration data and clear any temporarily held status data

class FidCompTraceDiffApprox(dynamics, params=None)

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

  Attributes:
    epsilon float

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

  compute_fid_err_grad()

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

  reset()

    reset any configuration data and clear any temporarily held status data

class TimeslotComputer(dynamics, params=None)

  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_level integer

      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_summary EvoCompSummary

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

  apply_params(params=None)

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

  dump_current()

    Store a copy of the current time evolution

class TSlotCompUpdateAll(dynamics, params=None)

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

  compare_amps(new_amps)

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

  get_timeslot_for_fidelity_calc()

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

  recompute_evolution()

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

class PulseGen(dyn=None, params=None)

  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_tslots integer

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

    pulse_time float

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

    scaling float

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

    offset float

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

    tau array[num_tslots] of float

      Duration of each timeslot (copied from Dynamics if given)

    lbound float

      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

    ubound float

      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

    periodic boolean

      True if the pulse generator produces periodic pulses

    random boolean

      True if the pulse generator produces random pulses

    log_level integer

      level of messaging output from the logger. Options are attributes of qutip.logging_utils, in decreasing levels of messaging, are: DEBUG_INTENSE, DEBUG_VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL Anything WARN or above is effectively ‘quiet’ execution, assuming everything runs as expected. The default NOTSET implies that the level will be taken from the QuTiP settings file, which by default is WARN

  apply_params(params=None)

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

  gen_pulse()

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

  init_pulse()

    Initialise the pulse parameters

  reset()

    reset attributes to default values

class PulseGenRandom(dyn=None, params=None)

  Generates random pulses as simply random values for each timeslot

  gen_pulse()

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

  reset()

    reset attributes to default values

class PulseGenZero(dyn=None, params=None)

  Generates a flat pulse

  gen_pulse()

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

class PulseGenLinear(dyn=None, params=None)

  Generates linear pulses

  Attributes:
    gradient float

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

    start_val float

      Start point of the line. That is the starting amplitude

    end_val float

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

  gen_pulse(gradient=None, start_val=None, end_val=None)

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

  init_pulse(gradient=None, start_val=None, end_val=None)

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

  reset()

    reset attributes to default values

class PulseGenPeriodic(dyn=None, params=None)

  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_waves float

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

    wavelen float

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

    freq float

      Frequency of the pulse

    start_phase float

      Phase of the pulse signal when t=0

  init_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)

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

  reset()

    reset attributes to default values

class PulseGenSine(dyn=None, params=None)

  Generates sine wave pulses

  gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)

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

class PulseGenSquare(dyn=None, params=None)

  Generates square wave pulses

  gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)

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

class PulseGenSaw(dyn=None, params=None)

  Generates saw tooth wave pulses

  gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)

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

class PulseGenTriangle(dyn=None, params=None)

  Generates triangular wave pulses

  gen_pulse(num_waves=None, wavelen=None, freq=None, start_phase=None)

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

class PulseGenGaussian(dyn=None, params=None)

  Generates pulses with a Gaussian profile

  gen_pulse(mean=None, variance=None)

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

  reset()

    reset attributes to default values

class PulseGenGaussianEdge(dyn=None, params=None)

  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_time float

      Determines the ramping rate. It is approximately the time required to bring the pulse to full amplitude It is set to 1/10 of the pulse time by default

  gen_pulse(decay_time=None)

    Generate a pulse that starts and ends at zero and 1.0 in between then apply scaling and offset The tailing in and out is an inverted Gaussian shape

  reset()

    reset attributes to default values

class PulseGenCrab(dyn=None, num_coeffs=None, params=None)

  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_coeffs integer

      Number of coefficients used for each basis function

    num_basis_funcs integer

      Number of basis functions In this case set at 2 and should not be changed

    coeffs float array[num_coeffs, num_basis_funcs]

      The basis coefficient values

    randomize_coeffs bool

      If True (default) then the coefficients are set to some random values when initialised, otherwise they will all be equal to self.scaling

  estimate_num_coeffs(dim)

    Estimate the number coefficients based on the dimensionality of the system. :returns: num_coeffs – estimated number of coefficients :rtype: int

  get_optim_var_vals()

    Get the parameter values to be optimised :rtype: list (or 1d array) of floats

  init_coeffs(num_coeffs=None)

    Generate the initial ceofficent values.

    Parameters:
      num_coeffs integer

        Number of coefficients used for each basis function If given this overides the default and sets the attribute of the same name.

  init_pulse(num_coeffs=None)

    Set the initial freq and coefficient values

  reset()

    reset attributes to default values

  set_optim_var_vals(param_vals)

    Set the values of the any of the pulse generation parameters based on new values from the optimisation method Typically this will be the basis coefficients

class PulseGenCrabFourier(dyn=None, num_coeffs=None, params=None)

  Generates a pulse using the Fourier basis functions, i.e. sin and cos

  Attributes:
    freqs float array[num_coeffs]

      Frequencies for the basis functions

    randomize_freqs bool

      If True (default) the some random offset is applied to the frequencies

  gen_pulse(coeffs=None)

    Generate a pulse using the Fourier basis with the freqs and coeffs attributes.

    Parameters:
      coeffs float array[num_coeffs, num_basis_funcs]

        The basis coefficient values If given this overides the default and sets the attribute of the same name.

  init_freqs()

    Generate the frequencies These are the Fourier harmonics with a uniformly distributed random offset

  init_pulse(num_coeffs=None)

    Set the initial freq and coefficient values

  reset()

    reset attributes to default values

class Stats

  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_name string

      Text used in some report functions. Makes sense to set it to ‘Hamiltonian’ when using unitary dynamics Default is simply ‘dynamics generator’

    num_iter integer

      Number of iterations of the optimisation algorithm

    wall_time_optim_start float

      Start time for the optimisation

    wall_time_optim_end float

      End time for the optimisation

    wall_time_optim float

      Time elasped during the optimisation

    wall_time_dyn_gen_compute float

      Total wall (elasped) time computing combined dynamics generator (for example combining drift and control Hamiltonians)

    wall_time_prop_compute float

      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_compute float

      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_compute float

      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_compute float

      Total wall (elasped) time computing the fidelity error gradient. Excludes calculating the propagator gradients (in exact gradient methods)

    num_fidelity_func_calls integer

      Number of calls to fidelity function by the optimisation algorithm

    num_grad_func_calls integer

      Number of calls to gradient function by the optimisation algorithm

    num_tslot_recompute integer

      Number of time the timeslot evolution is recomputed (It is only computed if any amplitudes changed since the last call)

    num_fidelity_computes integer

      Number of time the fidelity is computed (It is only computed if any amplitudes changed since the last call)

    num_grad_computes integer

      Number of time the gradient is computed (It is only computed if any amplitudes changed since the last call)

    num_ctrl_amp_updates integer

      Number of times the control amplitudes are updated

    mean_num_ctrl_amp_updates_per_iter float

      Mean number of control amplitude updates per iteration

    num_timeslot_changes integer

      Number of times the amplitudes of a any control in a timeslot changes

    mean_num_timeslot_changes_per_update float

      Mean average number of timeslot amplitudes that are changed per update

    num_ctrl_amp_changes integer

      Number of times individual control amplitudes that are changed

    mean_num_ctrl_amp_changes_per_update float

      Mean average number of control amplitudes that are changed per update

  calculate()

    Perform the calculations (e.g. averages) that are required on the stats Should be called before calling report

  report()

    Print a report of the stats to the console

class Dump

  A container for dump items. The lists for dump items is depends on the type Note: abstract class

  Attributes:
    parent some control object (Dynamics or Optimizer)

      aka the host. Object that generates the data that is dumped and is host to this dump object.

    dump_dir str

      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` string

      The level of data dumping that will occur.

    write_to_file bool

      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_ext str

      Default file extension for any file names that are auto generated

    fname_base str

      First part of any auto generated file names. This is usually overridden in the subclass

    dump_summary bool

      If True a summary is recorded each time a new item is added to the the dump. Default is True

    summary_sep str

      delimiter for the summary file. default is a space

    data_sep str

      delimiter for the data files (arrays saved to file). default is a space

    summary_file str

      File path for summary file. Automatically generated. Can be set specifically

  create_dump_dir()

    Checks dump directory exists, creates it if not

  property level

    The level of data dumping that will occur.

    SUMMARY

      A summary will be recorded

    FULL

      All possible dumping

    CUSTOM

      Some customised level of dumping

    When first set to CUSTOM this is equivalent to SUMMARY. It is then up to the user to specify what specifically is dumped

class OptimDump(optim, level='SUMMARY')

  A container for dumps of optimisation data generated during the pulse optimisation.

  Attributes:
    dump_summary bool

      When True summary items are appended to the iter_summary

    iter_summary list of `qutip.control.optimizer.OptimIterSummary`

      Summary at each iteration

    dump_fid_err bool

      When True values are appended to the fid_err_log

    fid_err_log list of float

      Fidelity error at each call of the fid_err_func

    dump_grad_norm bool

      When True values are appended to the fid_err_log

    grad_norm_log list of float

      Gradient norm at each call of the grad_norm_log

    dump_grad bool

      When True values are appended to the grad_log

    grad_log list of ndarray

      Gradients at each call of the fid_grad_func

  add_iter_summary()

    add copy of current optimizer iteration summary

  property dump_all

    True if everything (ignoring the summary) is to be dumped

  property dump_any

    True if anything other than the summary is to be dumped

  update_fid_err_log(fid_err)

    add an entry to the fid_err log

  update_grad_log(grad)

    add an entry to the grad log

  update_grad_norm_log(grad_norm)

    add an entry to the grad_norm log

  writeout(f=None)

    write all the logs and the summary out to file(s)

    Parameters:
      f filename 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')

  A container for dumps of dynamics data. Mainly time evolution calculations.

  Attributes:
    dump_summary bool

      If True a summary is recorded

    evo_summary list of `tslotcomp.EvoCompSummary`

      Summary items are appended if dump_summary is True at each recomputation of the evolution.

    dump_amps bool

      If True control amplitudes are dumped

    dump_dyn_gen bool

      If True the dynamics generators (Hamiltonians) are dumped

    dump_prop bool

      If True propagators are dumped

    dump_prop_grad bool

      If True propagator gradients are dumped

    dump_fwd_evo bool

      If True forward evolution operators are dumped

    dump_onwd_evo bool

      If True onward evolution operators are dumped

    dump_onto_evo bool

      If True onto (or backward) evolution operators are dumped

    evo_dumps list of `EvoCompDumpItem`

      A new dump item is appended at each recomputation of the evolution. That is if any of the calculation objects are to be dumped.

  add_evo_comp_summary(dump_item_idx=None)

    add copy of current evo comp summary

  add_evo_dump()

    Add dump of current time evolution generating objects

  property dump_all

    True if all of the calculation objects are to be dumped

  property dump_any

    True if any of the calculation objects are to be dumped

  writeout(f=None)

    Write all the dump items and the summary out to file(s).

    Parameters:
      f filename or filehandle

        If specified then all summary and object data will go in one file. If None is specified then type specific files will be generated in the dump_dir. If a filehandle is specified then it must be a byte mode file as numpy.savetxt is used, and requires this.

class DumpItem

  An item in a dump list

class EvoCompDumpItem(dump)

  A copy of all objects generated to calculate one time evolution. Note the attributes are only set if the corresponding `DynamicsDump` `dump_*` attribute is set.

  writeout(f=None)

    write all the objects out to files

    Parameters:
      f filename or filehandle

        If specified then all object data will go in one file. If None is specified then type specific files will be generated in the dump_dir If a filehandle is specified then it must be a byte mode file as numpy.savetxt is used, and requires this.

class DumpSummaryItem

  A summary of the most recent iteration. Abstract class only.

  Attributes:
    idx int

      Index in the summary list in which this is stored