# Quantum Objects

## Qobj

class Qobj(

  arg: TypeAliasForwardRef('ArrayLike') | Any = None,
  dims: DimensionLike = None,
  copy: bool = True,
  superrep: str = None,
  isherm: bool = None,
  isunitary: bool = None,
  dtype: type | str = 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:
    arg: array_like, data object or :obj:`.Qobj`

      Data for vector/matrix representation of the quantum object.

    dims: list

      Dimensions of object used for tensor products.

    copy: bool

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

  Attributes:
    data object

      The data object storing the vector / matrix representation of the Qobj.

    dtype type

      The data-layer type used for storing the data. The possible types are described in Qobj.to.

    dims list

      List of dimensions keeping track of the tensor structure.

    `shape` list

      Return the shape of the Qobj data.

    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), ‘choi’ (Choi matrix with tr = dimension), or ‘chi’ (chi-matrix representation).

    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 Qobj represents a ket state.

    `isbra` bool

      Indicates if the Qobj represents a bra state.

    `isoper` bool

      Indicates if the Qobj represents an operator.

    `issuper` bool

      Indicates if the Qobj represents a superoperator.

    `isoperket` bool

      Indicates if the Qobj represents a operator-ket state.

    `isoperbra` bool

      Indicates if the Qobj represents a operator-bra state.

  Methods

  copy() | Create copy of Qobj
  conj() | Conjugate of quantum object.
  contract() | Contract subspaces of the tensor structure which are 1D.
  cosm() | Cosine of quantum object.
  dag() | Adjoint (dagger) of quantum object.
  data_as(format, copy) | Vector / matrix representation of quantum object.
  diag() | Diagonal elements of quantum object.
  dnorm() | Diamond norm of quantum operator.
  drop_scalar_dims() | Drops one-dimensional subsystems from the list of dimensions (`dims`)
  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.
  logm() | Matrix logarithm of quantum 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.
  overlap(other) | Overlap between two state vectors or two operators.
  permute(order) | Returns composite qobj with indices reordered.
  basis_expansion(decimal_places=14, term_separator=” + “, | dim_separator=”auto”, sort=”largest-first”) Return a string-representation of the basis expansion E.g. `"(0.5+0.15j) |010> + (0.25+0j) |000> + ..."`
  proj() | Computes the projector for a ket or bra vector.
  ptrace(sel) | Returns quantum object for selected dimensions after performing partial trace.
  purity() | Calculates the purity of a quantum object.
  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.

  __call__(other: Qobj) → Qobj

    Acts this Qobj on another Qobj either by left-multiplication, or by vectorization and devectorization, as appropriate.

  basis_expansion(
    decimal_places: int = 14,
    term_separator: str = ' + ',
    dim_separator: str = 'auto',
    sort: str = 'largest-first',
  ) → str

    > Return a string-representation of the basis expansion for a ket or a bra, e.g.

    > `"(0.5+0.15j) |010> + (0.25+0j) |000> + ..."`

    Parameters:
      decimal_places int

        > The number of decimal places to show for the coefficients.

        term_separator: str

          Separator string between terms. E.g. use “ +

      “

        > to print terms on separate lines.

        dim_separator: str

          Separator string between dimension indices. E.g. use “, “ to print as `"|0, 0, 0>"`. If dim_separator=”auto”, then “” is used for qubits and “, “ is used otherwise.

        sort: str

          Show largest elements (by magnitude) first if “largest-first”. Unsorted otherwise.

    Returns:
      basis_expansion str

        The requested string representation.

  check_herm() → bool

    Check if the quantum object is hermitian.

    Returns:
      isherm bool

        Returns the new value of isherm property.

  conj() → Qobj

    Get the element-wise conjugation of the quantum object.

  contract(inplace: bool = False) → Qobj

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

    For operators, only pairs of 1D subspaces are contracted, so dimensions `[[2, 1, 1], [2, 2, 1]]` will become `[[2, 1], [2, 2]]`. To drop all scalar dimensions, use `drop_scalar_dims` instead, resulting in `[[2], [2, 2]]` in this example. `drop_scalar_dims` is also defined for superoperators.

    Parameters:
      inplace: bool, optional

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

    Returns:
      out: `Qobj`

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

  copy() → Qobj

    Create identical copy

  cosm() → Qobj

    Cosine of a quantum operator.

    Operator must be square.

    Returns:
      oper `Qobj`

        Matrix cosine of operator.

    Raises:
      TypeError

        Quantum object is not square.

    Notes

    Uses the Q.expm() method.

  dag() → Qobj

    Get the Hermitian adjoint of the quantum object.

  data_as(format: str = None, copy: bool = True) → Any

    Matrix from quantum object.

    Parameters:
      format str, default: None

        Type of the output, “ndarray” for `Dense`, “csr_matrix” for `CSR`. A ValueError will be raised if the format is not supported.

      copy bool {False, True}

        Whether to return a copy

    Returns:
      data numpy.ndarray, scipy.sparse.matrix_csr, etc.

        Matrix in the type of the underlying libraries.

  diag() → ndarray

    Diagonal elements of quantum object.

    Returns:
      diags array

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

  dnorm(B: Qobj = None) → float

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

    Parameters:
      B `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.

  drop_scalar_dims(inplace: bool = False) → Qobj

    Drops one-dimensional subsystems from the list of dimensions. After performing a projection, the `dims` of a ket could for example be `[[2, 1, 3], [1]]`. This will simplify them to `[[2, 3], [1]]`.

    This differs from `contract` in that all scalar dimensions are dropped for operators. For example, if the `dims` of an operator are `[[2, 2], [2, 1]]`, then `contract` will leave them unchanged, but this function will simplify to `[[2, 2], [2]]`.

    Parameters:
      inplace: bool, optional

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

    Returns:
      out: `Qobj`

        Quantum object with scalar dimensions dropped. Will be `self` if `inplace` is `True`.

  dual_chan() → Qobj

    Dual channel of quantum object representing a completely positive map.

  eigenenergies(
    sparse: bool = False,
    sort: Literal['low', 'high'] = 'low',
    eigvals: int = 0,
    tol: float = 0,
    maxiter: int = 100000,
  ) → ndarray

    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. It is designed to compute only a few eigenvalues and can give wrong results when all eigenvalues are asked.

  eigenstates(
    sparse: bool = False,
    sort: Literal['low', 'high'] = 'low',
    eigvals: int = 0,
    tol: float = 0,
    maxiter: int = 100000,
    phase_fix: int = None,
    output_type: Literal['kets'] = 'kets',
  ) → tuple[ndarray, ndarray[Qobj]]
  eigenstates(
    sparse: bool = False,
    sort: Literal['low', 'high'] = 'low',
    eigvals: int = 0,
    tol: float = 0,
    maxiter: int = 100000,
    phase_fix: int = None,
    output_type: Literal['oper'] = 'oper',
  ) → tuple[ndarray, Qobj]

    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.

      output_type: Literal[‘kets’, ‘oper’]

        If ‘kets’, return the eigenstates as a list of kets. If ‘oper’, return the eigenstates as an operator with the states as columns.

    Returns:
      eigvals array

        Array of eigenvalues for operator.

      eigvecs array[Qobj], Qobj

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

        If output_type is oper, a Qobj representing the operator eigenstates is returned.

    Notes

    The sparse eigensolver is much slower than the dense version. Use sparse only if memory requirements demand it. It is designed to compute only a few eigenvalues and can give wrong results when all eigenvalues are asked.

  expm(dtype: LayerType = None) → Qobj

    Matrix exponential of quantum operator.

    Input operator must be square.

    Parameters:
      dtype type

        The data-layer type that should be output.

    Returns:
      oper `Qobj`

        Exponentiated quantum operator.

    Raises:
      TypeError

        Quantum operator is not square.

  full(
    order: Literal['C', 'F'] = 'C',
    squeeze: bool = False,
  ) → ndarray

    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.

  full_tensor() → ndarray

    Dense ndarray reshaped according to the tensor dimensions of the quantum object.

    Returns:
      data numpy.ndarray

        Dense ndarray representation of the quantum object with one axis for each entry in `dims`.

    Examples

        >>> oper = qutip.qeye([2, 3])
        >>> oper.full_tensor().shape
        (2, 3, 2, 3)

  groundstate(
    sparse: bool = False,
    tol: float = 0,
    maxiter: int = 100000,
    safe: bool = True,
  ) → tuple[float, Qobj]

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

        Eigenket for the ground state of quantum operator.

  inv(sparse: bool = False) → Qobj

    Matrix inverse of a quantum operator

    Operator must be square.

    Returns:
      oper `Qobj`

        Matrix inverse of operator.

    Raises:
      TypeError

        Quantum object is not square.

  property isbra: bool

    Indicates if the Qobj represents a bra state.

  property isket: bool

    Indicates if the Qobj represents a ket state.

  property isoper: bool

    Indicates if the Qobj represents an operator.

  property isoperbra: bool

    Indicates if the Qobj represents a operator-bra state.

  property isoperket: bool

    Indicates if the Qobj represents a operator-ket state.

  property issuper: bool

    Indicates if the Qobj represents a superoperator.

  logm() → Qobj

    Matrix logarithm of quantum operator.

    Input operator must be square.

    Returns:
      oper `Qobj`

        Logarithm of the quantum operator.

    Raises:
      TypeError

        Quantum operator is not square.

  matrix_element(
    bra: Qobj,
    ket: Qobj,
  ) → Qobj

    Calculates a matrix element.

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

    Parameters:
      bra `Qobj`

        Quantum object of type ‘bra’ or ‘ket’

      ket `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: Literal['l2', 'max', 'fro', 'tr', 'one'] = None,
    kwargs: dict[str, Any] = None,
  ) → float

    Norm of a quantum object.

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

    Parameters:
      norm str

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

      kwargs dict

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

    Returns:
      norm float

        The requested norm of the operator or state quantum object.

  overlap(other: Qobj) → complex

    Overlap between two state vectors or two operators.

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

    Parameters:
      other `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.

  permute(order: list) → Qobj

    Permute the tensor structure of a quantum object. For example,

    > `qutip.tensor(x, y).permute([1, 0])`

    will give the same result as

    > `qutip.tensor(y, x)`

    and

    > `qutip.tensor(a, b, c).permute([1, 2, 0])`

    will be the same as

    > `qutip.tensor(b, c, a)`

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

    For superoperators, we expect `order` to be something like

    > `[[0, 2], [1, 3]]`

    which tells us to permute according to [0, 2, 1, 3], and then group indices according to the length of each sublist. As another example, permuting a superoperator with dimensions of

    > `[[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]]`

    by an `order`

    > `[[0, 3], [1, 4], [2, 5]]`

    should give a new object with dimensions

    > `[[[1, 1], [2, 2], [3, 3]], [[1, 1], [2, 2], [3, 3]]]`.

    Parameters:
      order list

        List of indices specifying the new tensor order.

    Returns:
      P `Qobj`

        Permuted quantum object.

  proj() → Qobj

    Form the projector from a given ket or bra vector.

    Parameters:
      Q `Qobj`

        Input bra or ket vector

    Returns:
      P `Qobj`

        Projection operator.

  ptrace(
    sel: int | list[int],
    dtype: LayerType = None,
  ) → Qobj

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

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

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

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

    Parameters:
      sel int or iterable of int

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

    Returns:
      oper `Qobj`

        Quantum object representing partial trace with selected components remaining.

  purity() → complex

    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.

  property shape: tuple[int, int]

    Return the shape of the Qobj data.

  sinm() → Qobj

    Sine of a quantum operator.

    Operator must be square.

    Returns:
      oper `Qobj`

        Matrix sine of operator.

    Raises:
      TypeError

        Quantum object is not square.

    Notes

    Uses the Q.expm() method.

  sqrtm(
    sparse: bool = False,
    tol: float = 0,
    maxiter: int = 100000,
  ) → Qobj

    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 `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: float = None) → Qobj

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

        Quantum object with small elements removed.

  to(data_type: LayerType, copy: bool = False) → Qobj

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

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

    Parameters:
      data_type type, str

        The data-layer type or its string alias that the data of this `Qobj` should be converted to.

      copy Bool

        If the data store is already in the format requested, whether the function should return returns self or a copy.

    Returns:
      Qobj

        A `Qobj` with the data stored in the requested format.

  tr() → complex

    Trace of a quantum object.

    Returns:
      trace float

        Returns the trace of the quantum object.

  trans() → Qobj

    Get the matrix transpose of the quantum operator.

    Returns:
      oper `Qobj`

        Transpose of input operator.

  transform(
    inpt: list[Qobj] | TypeAliasForwardRef('ArrayLike'),
    inverse: bool = False,
  ) → Qobj

    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.

    Returns:
      oper `Qobj`

        Operator in new basis.

    Notes

    This function is still in development.

  trunc_neg(
    method: Literal['clip', 'sgs'] = 'clip',
  ) → Qobj

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

        A valid density operator.

  unit(
    inplace: bool = False,
    norm: Literal['l2', 'max', 'fro', 'tr', 'one'] = None,
    kwargs: dict[str, Any] = None,
  ) → Qobj

    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.

      kwargs dict

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

    Returns:
      obj `Qobj`

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

## CoreOptions

class CoreOptions(**options)

  Options used by the core of qutip such as the tolerance of `Qobj` comparison or coefficient’s format.

  Values can be changed in `qutip.settings.core` or by using context:

  > `with CoreOptions(atol=1e-6): ...`

  ### Options:

  auto_tidyupbool

    Whether to tidyup during sparse operations.

  auto_tidyup_dimsbool [True]

    Whether to track the structure of scalar dimensions. Without auto_tidyup_dims:

    > `basis([2, 2]).dims == [[2, 2], [1, 1]]`

    With auto_tidyup_dims:

    > `basis([2, 2]).dims == [[2, 2], [1]]`

  atolfloat {1e-12}

    General absolute tolerance. Used in various functions to round off small values.

  rtolfloat {1e-12}

    General relative tolerance.

  auto_tidyup_atolfloat {1e-14}

    The absolute tolerance used in automatic tidyup (see the `auto_tidyup` parameter above) and the default value of `atol` used in `Qobj.tidyup`.

  function_coefficient_stylestr {“auto”}

    The signature expected by function coefficients. The options are:

    - “pythonic”: the signature should be `f(t, ...)` where `t` is the time and the `...` are the remaining arguments passed directly into the function. E.g. `f(t, w, b=5)`. Keyword arguments are supported: `f(t, **args)`.

    - “dict”: the signature shoule be `f(t, args)` where `t` is the time and `args` is a dict containing the remaining arguments. E.g. `f(t, {"w": w, "b": 5})`.

    - “auto”: select automatically between the two options above based on the signature of the supplied function. If the function signature is exactly `f(t, args)` then `dict` is used. Otherwise `pythonic` is used.

    From QuTiP 5.5, this options will be removed and only pythonic siganture will be supported.

  default_dtypestr, type {“core”}

    The specified data type will be used as output for different qutip functions determined by the “default_dtype_scope” options. Any data-layer known to `qutip.data.to` is accepted. The default core`, refers to any format available in the qutip package and functions will default to a sensible data type.

  default_dtype_scopestr {“creation”}

    Control where the default_dtype apply.

    - “creation”: Used in function creating `Qobj`, such as :func:”qeye” or :func:”rand_herm”. Also used when creating Qobj from list.

    - “missing”: “default_dtype” is also used in operations between data layers where no exact operation match. For example `Dense + Dense` will return a `Dense`, but `Dense + CSR` will use the default type.

    - “full”: “default_dtype” is used for the output of Qobj operations and forced when creating any Qobj. Be careful as it can affect the speed of operation greatly.

# Creation of States and Operators

## Quantum States

basis(

  dimensions: SpaceLike,
  n: int | list[int] = None,
  offset: int | list[int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Generates the vector representation of a Fock state.

  Note that the Fock index `n` starts from zero. Therefore, `basis(N, 0)` is the ground state of an N-dimensional system.

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    n int or list of ints, optional (default 0 for all dimensions)

      Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match `dimensions`, e.g. if `dimensions` is a list, then `n` must either be omitted or a list of equal length.

    offset int or list of ints, optional (default 0 for all dimensions)

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

    dtype type or str, optional

      storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state `Qobj`

      Qobj representing the requested number state `|n>`.

  Notes

  Advanced usage: This function can be used to create basis vectors in a summed Hilbert space. For the `dimensions` parameter, pass a tuple whose entries are the dimension specifications for the components of the direct sum. For `n`, pass a list where the first entry is an integer indicating the component and the second entry describes the basis state inside the component. The `offset` parameter is not allowed in this case.

  For example, the tuple `([M], [N])` denotes an `(M+N)`-dimensional space. Its basis vectors are `basis(([M], [N]), [0, [m]])` for \(0 \leq m < M\) and `basis(([M], [N]), [1, [n]])` for \(0 \leq n < N\).

  Examples

      >>> basis(5,2)
      Quantum object: dims = [[5], [1]], shape = (5, 1), type = ket
      Qobj data =
      [[ 0.+0.j]
       [ 0.+0.j]
       [ 1.+0.j]
       [ 0.+0.j]
       [ 0.+0.j]]
      >>> basis([2,2,2], [0,1,0])
      Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = (8, 1), type = ket
      Qobj data =
      [[0.]
       [0.]
       [1.]
       [0.]
       [0.]
       [0.]
       [0.]
       [0.]]
      >>> basis(([2], [3]), [1, [0]])
      Quantum object: dims=[([2], [3]), [1]], shape=(5, 1), type='ket', dtype=Dense
      Qobj data =
      [[0.]
       [0.]
       [1.]
       [0.]
       [0.]]

bell_state(

  state: Literal['00', '01', '10', '11'] = '00',
  *,
  dtype: LayerType = None,

) → Qobj

  Returns the selected Bell state:

  \[\begin{split}\begin{aligned} \lvert B_{00}\rangle &= \frac1{\sqrt2}(\lvert00\rangle+\lvert11\rangle)\\ \lvert B_{01}\rangle &= \frac1{\sqrt2}(\lvert00\rangle-\lvert11\rangle)\\ \lvert B_{10}\rangle &= \frac1{\sqrt2}(\lvert01\rangle+\lvert10\rangle)\\ \lvert B_{11}\rangle &= \frac1{\sqrt2}(\lvert01\rangle-\lvert10\rangle)\\ \end{aligned}\end{split}\]
  Parameters:
    state str [‘00’, ‘01’, ‘10’, ‘11’]

      Which bell state to return

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    Bell_state qobj

      Bell state

bra(

  seq: list[int | str] | str,
  dim: int | list[int] = 2,
  *,
  dtype: LayerType = None,

) → Qobj

  Produces a multiparticle bra state for a list or string, where each element stands for state of the respective particle.

  Parameters:
    seq str / list of ints or characters

      Each element defines state of the respective particle. (e.g. [1,1,0,1] or a string “1101”). For qubits it is also possible to use the following conventions:

      - ‘g’/’e’ (ground and excited state)

      - ‘u’/’d’ (spin up and down)

      - ‘H’/’V’ (horizontal and vertical polarization)

      Note: for dimension > 9 you need to use a list.

    dim int (default: 2) / list of ints

      Space dimension for each particle: int if there are the same, list if they are different.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    bra qobj

  Examples

      >>> bra("10")
      Quantum object: dims = [[1, 1], [2, 2]], shape = [1, 4], type = bra
      Qobj data =
      [[ 0.  0.  1.  0.]]

      >>> bra("Hue")
      Quantum object: dims = [[1, 1, 1], [2, 2, 2]], shape = [1, 8], type = bra
      Qobj data =
      [[ 0.  1.  0.  0.  0.  0.  0.  0.]]

      >>> bra("12", 3)
      Quantum object: dims = [[1, 1], [3, 3]], shape = [1, 9], type = bra
      Qobj data =
      [[ 0.  0.  0.  0.  0.  1.  0.  0.  0.]]

      >>> bra("31", [5, 2])
      Quantum object: dims = [[1, 1], [5, 2]], shape = [1, 10], type = bra
      Qobj data =
      [[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]]

coherent(

  N: int,
  alpha: float,
  offset: int = 0,
  method: str = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Generates a coherent state with eigenvalue alpha.

  Constructed using displacement operator on vacuum state.

  Parameters:
    N int

      Number of Fock states in Hilbert space.

    alpha float/complex

      Eigenvalue of coherent state.

    offset int, default: 0

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

    method string {‘operator’, ‘analytic’}, optional

      Method for generating coherent state.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state qobj

      Qobj quantum object for coherent state

  Notes

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

  Examples

      >>> coherent(5,0.25j)
      Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
      Qobj data =
      [[  9.69233235e-01+0.j        ]
       [  0.00000000e+00+0.24230831j]
       [ -4.28344935e-02+0.j        ]
       [  0.00000000e+00-0.00618204j]
       [  7.80904967e-04+0.j        ]]

coherent_dm(

  N: int,
  alpha: float,
  offset: int = 0,
  method: str = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Density matrix representation of a coherent state.

  Constructed via outer product of `coherent`

  Parameters:
    N int

      Number of basis states in Hilbert space.

    alpha float/complex

      Eigenvalue for coherent state.

    offset int, default: 0

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

    method string {‘operator’, ‘analytic’}, optional

      Method for generating coherent density matrix.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    dm qobj

      Density matrix representation of coherent state.

  Notes

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

  Examples

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

fock(

  dimensions: SpaceLike,
  n: int | list[int] = None,
  offset: int | list[int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Bosonic Fock (number) state.

  Same as `basis`.

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    n int or list of ints, default: 0 for all dimensions

      Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match `dimensions`, e.g. if `dimensions` is a list, then `n` must either be omitted or a list of equal length.

    offset int or list of ints, default: 0 for all dimensions

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

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

  Examples

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

fock_dm(

  dimensions: int | list[int] | Space,
  n: int | list[int] = None,
  offset: int | list[int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Density matrix representation of a Fock state

  Constructed via outer product of `basis`.

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    n int or list of ints, default: 0 for all dimensions

      Integer corresponding to desired number state, defaults to 0 for all dimensions if omitted. The shape must match `dimensions`, e.g. if `dimensions` is a list, then `n` must either be omitted or a list of equal length.

    offset int or list of ints, default: 0 for all dimensions

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    dm qobj

      Density matrix representation of Fock state.

  Examples

      >>> fock_dm(3,1)
      Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
      Qobj data =
      [[ 0.+0.j  0.+0.j  0.+0.j]
       [ 0.+0.j  1.+0.j  0.+0.j]
       [ 0.+0.j  0.+0.j  0.+0.j]]

ghz_state(N_qubit: int, *, dtype: LayerType = None) → Qobj
  Returns the N-qubit GHZ-state:

    `[ |00...00> + |11...11> ] / sqrt(2)`

  Parameters:
    N_qubit int

      Number of qubits in state

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    G qobj

      N-qubit GHZ-state

ket(

  seq: list[int | str] | str,
  dim: int | list[int] = 2,
  *,
  dtype: LayerType = None,

) → Qobj

  Produces a multiparticle ket state for a list or string, where each element stands for state of the respective particle.

  Parameters:
    seq str / list of ints or characters

      Each element defines state of the respective particle. (e.g. [1,1,0,1] or a string “1101”). For qubits it is also possible to use the following conventions: - ‘g’/’e’ (ground and excited state) - ‘u’/’d’ (spin up and down) - ‘H’/’V’ (horizontal and vertical polarization) Note: for dimension > 9 you need to use a list.

    dim int or list of ints, default: 2

      Space dimension for each particle: int if there are the same, list if they are different.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    ket qobj

  Examples

      >>> ket("10")
      Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket
      Qobj data =
      [[ 0.]
       [ 0.]
       [ 1.]
       [ 0.]]

      >>> ket("Hue")
      Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
      Qobj data =
      [[ 0.]
       [ 1.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]]

      >>> ket("12", 3)
      Quantum object: dims = [[3, 3], [1, 1]], shape = [9, 1], type = ket
      Qobj data =
      [[ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 1.]
       [ 0.]
       [ 0.]
       [ 0.]]

      >>> ket("31", [5, 2])
      Quantum object: dims = [[5, 2], [1, 1]], shape = [10, 1], type = ket
      Qobj data =
      [[ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 1.]
       [ 0.]
       [ 0.]]

ket2dm(Q: Qobj) → Qobj

  Takes input ket or bra vector and returns density matrix formed by outer product. This is completely identical to calling `Q.proj()`.

  Parameters:
    Q `Qobj`

      Ket or bra type quantum object.

  Returns:
    dm `Qobj`

      Density matrix formed by outer product of Q.

  Examples

      >>> x=basis(3,2)
      >>> ket2dm(x)
      Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
      Qobj data =
      [[ 0.+0.j  0.+0.j  0.+0.j]
       [ 0.+0.j  0.+0.j  0.+0.j]
       [ 0.+0.j  0.+0.j  1.+0.j]]

maximally_mixed_dm(

  dimensions: SpaceLike,
  *,
  dtype: LayerType = None,

) → Qobj

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

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    dm `Qobj`

      Thermal state density matrix.

phase_basis(

  N: int,
  m: int,
  phi0: float = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Basis vector for the mth phase of the Pegg-Barnett phase operator.

  Parameters:
    N int

      Number of basis states in Hilbert space.

    m int

      Integer corresponding to the mth discrete phase `phi_m = phi0 + 2 * pi * m / N`

    phi0 float, default: 0

      Reference phase angle.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state qobj

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

  Notes

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

projection(

  dimensions: int | list[int],
  n: int | list[int],
  m: int | list[int],
  offset: int | list[int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  The projection operator that projects state \(\lvert m\rangle\) on state \(\lvert n\rangle\).

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    n, m int

      The number states in the projection.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Requested projection operator.

qutrit_basis(*, dtype: LayerType = None) → list[Qobj]

  Basis states for a three level system (qutrit)

  dtypetype or str, optional

    storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    qstates array

      Array of qutrit basis vectors

singlet_state(*, dtype: LayerType = None) → Qobj

  Returns the two particle singlet-state:

  \[\lvert S\rangle = \frac1{\sqrt2}(\lvert01\rangle-\lvert10\rangle)\]

  that is identical to the fourth bell state.

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    Bell_state qobj

      \(\lvert B_{11}\rangle\) Bell state

spin_coherent(

  j: float,
  theta: float,
  phi: float,
  type: Literal['ket', 'bra', 'dm'] = 'ket',
  *,
  dtype: LayerType = None,

) → Qobj

  Generate the coherent spin state \(\lvert \theta, \phi\rangle\).

  Parameters:
    j float

      The spin of the state.

    theta float

      Angle from z axis.

    phi float

      Angle from x axis.

    type string {‘ket’, ‘bra’, ‘dm’}, default: ‘ket’

      Type of state to generate.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state qobj

      Qobj quantum object for spin coherent state

spin_state(

  j: float,
  m: float,
  type: Literal['ket', 'bra', 'dm'] = 'ket',
  *,
  dtype: LayerType = None,

) → Qobj

  Generates the spin state \(\lvert j, m\rangle\), i.e. the eigenstate of the spin-j Sz operator with eigenvalue m.

  Parameters:
    j float

      The spin of the state ().

    m float

      Eigenvalue of the spin-j Sz operator.

    type string {‘ket’, ‘bra’, ‘dm’}, default: ‘ket’

      Type of state to generate.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state qobj

      Qobj quantum object for spin state

state_index_number(dims: list[int], index: int) → tuple

  Return a quantum number representation given a state index, for a system of composite structure defined by dims.

  Example

      >>> state_index_number([2, 2, 2], 6)
      [1, 1, 0]

  Parameters:
    dims list or array

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

    index integer

      The index of the state in standard enumeration ordering.

  Returns:
    state tuple

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

state_number_enumerate(

  dims: list[int],
  excitations: int = None,

) → Iterator[tuple]

  An iterator that enumerates all the state number tuples (quantum numbers of the form (n1, n2, n3, …)) for a system with dimensions given by dims.

  Example

      >>> for state in state_number_enumerate([2,2]):
      >>>     print(state)
      ( 0  0 )
      ( 0  1 )
      ( 1  0 )
      ( 1  1 )

  Parameters:
    dims list

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

    excitations integer, optional

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

  Returns:
    state_number tuple

      Successive state number tuples that can be used in loops and other iterations, using standard state enumeration by definition.

state_number_index(dims: list[int], state: list[int]) → int

  Return the index of a quantum state corresponding to state, given a system with dimensions given by dims.

  Example

      >>> state_number_index([2, 2, 2], [1, 1, 0])
      6

  Parameters:
    dims list

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

    state list

      State number array.

  Returns:
    idx int

      The index of the state given by state in standard enumeration ordering.

state_number_qobj(

  dims: SpaceLike,
  state: int | list[int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Return a Qobj representation of a quantum state specified by the state array state.

  Note

  Deprecated in QuTiP 5.0, use `basis` instead.

  Example

      >>> state_number_qobj([2, 2, 2], [1, 0, 1])
      Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
      Qobj data =
      [[ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 0.]
       [ 1.]
       [ 0.]
       [ 0.]]

  Parameters:
    dims list or array

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

    state list

      State number array.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    state `Qobj`

      The state as a `Qobj` instance.

thermal_dm(

  N: int,
  n: float,
  method: Literal['operator', 'analytic'] = 'operator',
  *,
  dtype: LayerType = None,

) → Qobj

  Density matrix for a thermal state of n particles

  Parameters:
    N int

      Number of basis states in Hilbert space.

    n float

      Expectation value for number of particles in thermal state.

    method string {‘operator’, ‘analytic’}, default: ‘operator’

      `string` that sets the method used to generate the thermal state probabilities

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    dm qobj

      Thermal state density matrix.

  Notes

  The ‘operator’ method (default) generates the thermal state using the truncated number operator `num(N)`. This is the method that should be used in computations. The ‘analytic’ method uses the analytic coefficients derived in an infinite Hilbert space. The analytic form is not necessarily normalized, if truncated too aggressively.

  Examples

      >>> thermal_dm(5, 1)
      Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isHerm = True
      Qobj data =
      [[ 0.51612903  0.          0.          0.          0.        ]
       [ 0.          0.25806452  0.          0.          0.        ]
       [ 0.          0.          0.12903226  0.          0.        ]
       [ 0.          0.          0.          0.06451613  0.        ]
       [ 0.          0.          0.          0.          0.03225806]]

      >>> thermal_dm(5, 1, 'analytic')
      Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isHerm = True
      Qobj data =
      [[ 0.5      0.       0.       0.       0.     ]
       [ 0.       0.25     0.       0.       0.     ]
       [ 0.       0.       0.125    0.       0.     ]
       [ 0.       0.       0.       0.0625   0.     ]
       [ 0.       0.       0.       0.       0.03125]]

triplet_states(*, dtype: LayerType = None) → list[Qobj]

  Returns a list of the two particle triplet-states:

  \[\lvert T_1\rangle = \lvert11\rangle \lvert T_2\rangle = \frac1{\sqrt2}(\lvert01\rangle + \lvert10\rangle) \lvert T_3\rangle = \lvert00\rangle\]
  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    trip_states list

      2 particle triplet states

w_state(N_qubit: int, *, dtype: LayerType = None) → Qobj
  Returns the N-qubit W-state:

    `[ |100..0> + |010..0> + |001..0> + ... |000..1> ] / sqrt(n)`

  Parameters:
    N_qubit int

      Number of qubits in state

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    W `Qobj`

      N-qubit W-state

zero_ket(

  dimensions: SpaceLike,
  *,
  dtype: LayerType = None,

) → Qobj

  Creates the zero ket vector with shape Nx1 and dimensions dims.

  Parameters:
    dimensions int or list of ints, Space

      Number of basis states in Hilbert space. If a list, then the resultant object will be a tensor product over spaces with those dimensions.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    zero_ket qobj

      Zero ket on given Hilbert space.

## Quantum Operators

This module contains functions for generating Qobj representation of a variety of commonly occuring quantum operators.

charge(

  Nmax: int,
  Nmin: int = None,
  frac: float = 1,
  *,
  dtype: LayerType = None,

) → Qobj

  Generate the diagonal charge operator over charge states from Nmin to Nmax.

  Parameters:
    Nmax int

      Maximum charge state to consider.

    Nmin int, default: -Nmax

      Lowest charge state to consider.

    frac float, default: 1

      Specify fractional charge if needed.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    C Qobj

      Charge operator over [Nmin, Nmax].

  Notes

  Added in version 3.2.

commutator(

  A: Qobj,
  B: Qobj,
  kind: Literal['normal', 'anti'] = 'normal',

) → Qobj

  Return the commutator of kind kind (normal, anti) of the two operators A and B.

  Parameters:
    A, B `Qobj`, `QobjEvo`

      The operators to compute the commutator of.

    kind: str {“normal”, “anti”}, default: “anti”

      Which kind of commutator to compute.

create(

  N: int,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Creation (raising) operator.

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Qobj for raising operator.

  Examples

      >>> create(4)
      Quantum object: dims=[[4], [4]], shape=(4, 4), type='oper', isherm=False
      Qobj data =
      [[ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
       [ 1.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
       [ 0.00000000+0.j  1.41421356+0.j  0.00000000+0.j  0.00000000+0.j]
       [ 0.00000000+0.j  0.00000000+0.j  1.73205081+0.j  0.00000000+0.j]]

destroy(

  N: int,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Destruction (lowering) operator.

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Qobj for lowering operator.

  Examples

      >>> destroy(4)
      Quantum object: dims=[[4], [4]], shape=(4, 4), type='oper', isherm=False
      Qobj data =
      [[ 0.00000000+0.j  1.00000000+0.j  0.00000000+0.j  0.00000000+0.j]
       [ 0.00000000+0.j  0.00000000+0.j  1.41421356+0.j  0.00000000+0.j]
       [ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  1.73205081+0.j]
       [ 0.00000000+0.j  0.00000000+0.j  0.00000000+0.j  0.00000000+0.j]]

displace(

  N: int,
  alpha: float,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Single-mode displacement operator.

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    alpha float/complex

      Displacement amplitude.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Displacement operator.

  Examples

      >>> displace(4,0.25)
      Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
      Qobj data =
      [[ 0.96923323+0.j -0.24230859+0.j  0.04282883+0.j -0.00626025+0.j]
       [ 0.24230859+0.j  0.90866411+0.j -0.33183303+0.j  0.07418172+0.j]
       [ 0.04282883+0.j  0.33183303+0.j  0.84809499+0.j -0.41083747+0.j]
       [ 0.00626025+0.j  0.07418172+0.j  0.41083747+0.j  0.90866411+0.j]]

fcreate(n_sites: int, site, dtype: LayerType = None) → Qobj

  Fermionic creation operator. We use the Jordan-Wigner transformation, making use of the Jordan-Wigner ZZ..Z strings, to construct this as follows:

  \[a_j = \sigma_z^{\otimes j} \otimes (\frac{\sigma_x - i \sigma_y}{2}) \otimes I^{\otimes N-j-1}\]
  Parameters:
    n_sites int

      Number of sites in Fock space.

    site int

      The site in Fock space to add a fermion to. Corresponds to j in the above JW transform.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Qobj for raising operator.

  Examples

      >>> fcreate(2)
      Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4),     type = oper, isherm = False
      Qobj data =
      [[0. 0. 0. 0.]
      [0. 0. 0. 0.]
      [1. 0. 0. 0.]
      [0. 1. 0. 0.]]

fdestroy(n_sites: int, site, dtype: LayerType = None) → Qobj

  Fermionic destruction operator. We use the Jordan-Wigner transformation, making use of the Jordan-Wigner ZZ..Z strings, to construct this as follows:

  \[a_j = \sigma_z^{\otimes j} \otimes (\frac{\sigma_x + i \sigma_y}{2}) \otimes I^{\otimes N-j-1}\]
  Parameters:
    n_sites int

      Number of sites in Fock space.

    site int

      The site in Fock space to add a fermion to. Corresponds to j in the above JW transform.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Qobj for destruction operator.

  Examples

      >>> fdestroy(2)
      Quantum object: dims=[[2 2], [2 2]], shape=(4, 4),     type='oper', isherm=False
      Qobj data =
      [[0. 0. 1. 0.]
      [0. 0. 0. 1.]
      [0. 0. 0. 0.]
      [0. 0. 0. 0.]]

identity(

  dimensions: SpaceLike,
  *,
  dtype: LayerType = None,

) → Qobj

  Identity operator.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int), Space

      Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Identity operator Qobj.

  Examples

      >>> qeye(3)
      Quantum object: dims = [[3], [3]], shape = (3, 3), type = oper, isherm = True
      Qobj data =
      [[ 1.  0.  0.]
       [ 0.  1.  0.]
       [ 0.  0.  1.]]
      >>> qeye([2,2])
      Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4), type = oper, isherm = True
      Qobj data =
      [[1. 0. 0. 0.]
       [0. 1. 0. 0.]
       [0. 0. 1. 0.]
       [0. 0. 0. 1.]]

jmat(

  j: float,
  which: Literal[None],
  *,
  dtype: LayerType = None,

) → tuple[Qobj]
jmat(

  j: float,
  which: Literal['x', 'y', 'z', '+', '-'],
  *,
  dtype: LayerType = None,

) → Qobj

  Higher-order spin operators:

  Parameters:
    j float

      Spin of operator

    which str, optional

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    jmat Qobj or tuple of Qobj

      `qobj` for requested spin operator(s).

  Examples

      >>> jmat(1)
      [ Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
      Qobj data =
      [[ 0.          0.70710678  0.        ]
       [ 0.70710678  0.          0.70710678]
       [ 0.          0.70710678  0.        ]]
       Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
      Qobj data =
      [[ 0.+0.j          0.-0.70710678j  0.+0.j        ]
       [ 0.+0.70710678j  0.+0.j          0.-0.70710678j]
       [ 0.+0.j          0.+0.70710678j  0.+0.j        ]]
       Quantum object: dims = [[3], [3]], shape = [3, 3], type = oper, isHerm = True
      Qobj data =
      [[ 1.  0.  0.]
       [ 0.  0.  0.]
       [ 0.  0. -1.]]]

momentum(

  N: int,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Momentum operator p=-1j/sqrt(2)*(a-a.dag())

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Momentum operator as Qobj.

num(

  N: int,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Quantum object for number operator.

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper: qobj

      Qobj for number operator.

  Examples

      >>> num(4)
      Quantum object: dims=[[4], [4]], shape=(4, 4), type='oper', isherm=True
      Qobj data =
      [[0 0 0 0]
       [0 1 0 0]
       [0 0 2 0]
       [0 0 0 3]]

phase(

  N: int,
  phi0: float = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Single-mode Pegg-Barnett phase operator.

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    phi0 float, default: 0

      Reference phase.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Phase operator with respect to reference phase.

  Notes

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

position(

  N: int,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Position operator \(x = 1 / sqrt(2) * (a + a.dag())\)

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Position operator as Qobj.

qdiags(

  diagonals: ArrayLike | list[ArrayLike],
  offsets: int | list[int] = None,
  dims: DimensionLike = None,
  shape: tuple[int, int] = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Constructs an operator from an array of diagonals.

  Parameters:
    diagonals array_like or sequence of array_like

      Array of elements to place along the selected diagonals.

    offsets int or sequence of ints, optional
      Sequence for diagonals to be set:

        - k=0 main diagonal

        - k>0 kth upper diagonal

        - k<0 kth lower diagonal

    dims list, optional

      Dimensions for operator

    shape list, tuple, optional

      Shape of operator. If omitted, a square operator large enough to contain the diagonals is generated.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

      >>> qdiags(sqrt(range(1, 4)), 1)
      Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isherm = False
      Qobj data =
      [[ 0.          1.          0.          0.        ]
       [ 0.          0.          1.41421356  0.        ]
       [ 0.          0.          0.          1.73205081]
       [ 0.          0.          0.          0.        ]]

qeye(dimensions: SpaceLike, *, dtype: LayerType = None) → Qobj

  Identity operator.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int), Space

      Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Identity operator Qobj.

  Examples

      >>> qeye(3)
      Quantum object: dims = [[3], [3]], shape = (3, 3), type = oper, isherm = True
      Qobj data =
      [[ 1.  0.  0.]
       [ 0.  1.  0.]
       [ 0.  0.  1.]]
      >>> qeye([2,2])
      Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4), type = oper, isherm = True
      Qobj data =
      [[1. 0. 0. 0.]
       [0. 1. 0. 0.]
       [0. 0. 1. 0.]
       [0. 0. 0. 1.]]

qeye_like(qobj: Qobj) → Qobj

  Identity operator with the same dims and type as the reference quantum object.

  Parameters:
    qobj Qobj, QobjEvo

      Reference quantum object to copy the dims from.

  Returns:
    oper qobj

      Identity operator Qobj.

qutrit_ops(*, dtype: LayerType = None) → list[Qobj]

  Operators for a three level system (qutrit).

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    opers: array

      array of qutrit operators.

qzero(

  dimensions: SpaceLike,
  dims_right: SpaceLike = None,
  *,
  dtype: LayerType = None,

) → Qobj

  Zero operator.

  Parameters:
    dimensions int, list of int, list of list of int, Space

      Number of basis states in the Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    dims_right int, list of int, list of list of int, Space, optional

      Number of basis states in the right Hilbert space when the operator is rectangular.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    qzero qobj

      Zero operator Qobj.

qzero_like(qobj: Qobj) → Qobj

  Zero operator of the same dims and type as the reference.

  Parameters:
    qobj Qobj, QobjEvo

      Reference quantum object to copy the dims from.

  Returns:
    qzero qobj

      Zero operator Qobj.

sigmam(*, dtype: LayerType = None) → Qobj

  Annihilation operator for Pauli spins.

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

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

sigmap(*, dtype: LayerType = None) → Qobj

  Creation operator for Pauli spins.

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

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

sigmax(*, dtype: LayerType = None) → Qobj

  Pauli spin 1/2 sigma-x operator

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

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

sigmay(*, dtype: LayerType = None) → Qobj

  Pauli spin 1/2 sigma-y operator.

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

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

sigmaz(*, dtype: LayerType = None) → Qobj

  Pauli spin 1/2 sigma-z operator.

  Parameters:
    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Examples

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

spin_Jm(j: float, *, dtype: LayerType = None) → Qobj

  Spin-j annihilation operator

  Parameters:
    j float

      Spin of operator

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    op Qobj

      `qobj` representation of the operator.

spin_Jp(j: float, *, dtype: LayerType = None) → Qobj

  Spin-j creation operator

  Parameters:
    j float

      Spin of operator

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    op Qobj

      `qobj` representation of the operator.

spin_Jx(j: float, *, dtype: LayerType = None) → Qobj

  Spin-j x operator

  Parameters:
    j float

      Spin of operator

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    op Qobj

      `qobj` representation of the operator.

spin_Jy(j: float, *, dtype: LayerType = None) → Qobj

  Spin-j y operator

  Parameters:
    j float

      Spin of operator

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    op Qobj

      `qobj` representation of the operator.

spin_Jz(j: float, *, dtype: LayerType = None) → Qobj

  Spin-j z operator

  Parameters:
    j float

      Spin of operator

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    op Qobj

      `qobj` representation of the operator.

squeeze(

  N: int,
  z: float,
  offset: int = 0,
  *,
  dtype: LayerType = None,

) → Qobj

  Single-mode squeezing operator.

  Parameters:
    N int

      Dimension of hilbert space.

    z float/complex

      Squeezing parameter.

    offset int, default: 0

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

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper `Qobj`

      Squeezing operator.

  Examples

      >>> squeeze(4, 0.25)
      Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isHerm = False
      Qobj data =
      [[ 0.98441565+0.j  0.00000000+0.j  0.17585742+0.j  0.00000000+0.j]
       [ 0.00000000+0.j  0.95349007+0.j  0.00000000+0.j  0.30142443+0.j]
       [-0.17585742+0.j  0.00000000+0.j  0.98441565+0.j  0.00000000+0.j]
       [ 0.00000000+0.j -0.30142443+0.j  0.00000000+0.j  0.95349007+0.j]]

squeezing(

  a1: Qobj,
  a2: Qobj,
  z: float,

) → Qobj

  Generalized squeezing operator.

  \[S(z) = \exp\left(\frac{1}{2}\left(z^*a_1a_2 - za_1^\dagger a_2^\dagger\right)\right)\]
  Parameters:
    a1 `Qobj`

      Operator 1.

    a2 `Qobj`

      Operator 2.

    z float/complex

      Squeezing parameter.

  Returns:
    oper `Qobj`

      Squeezing operator.

tunneling(

  N: int,
  m: int = 1,
  *,
  dtype: LayerType = None,

) → Qobj

  Tunneling operator with elements of the form \(\\sum |N><N+m| + |N+m><N|\).

  Parameters:
    N int

      Number of basis states in the Hilbert space.

    m int, default: 1

      Number of excitations in tunneling event.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    T Qobj

      Tunneling operator.

## Quantum Gates

berkeley(*, dtype: LayerType = None) → Qobj

  Quantum object representing the Berkeley gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    berkeley_gate qobj

      Quantum object representation of Berkeley gate

cnot(*, dtype: LayerType = None) → Qobj

  Quantum object representing the CNOT gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    cnot_gate qobj

      Quantum object representation of CNOT gate

cphase(theta: float, *, dtype: LayerType = None) → Qobj

  Returns quantum object representing the controlled phase shift gate.

  Parameters:
    theta float

      Phase rotation angle.

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    U qobj

      Quantum object representation of controlled phase gate.

cs_gate(*, dtype: LayerType = None) → Qobj

  Controlled S gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing the rotation.

csign(*, dtype: LayerType = None) → Qobj

  Quantum object representing the CSIGN gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    csign_gate qobj

      Quantum object representation of CSIGN gate

ct_gate(*, dtype: LayerType = None) → Qobj

  Controlled T gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing the rotation.

cy_gate(*, dtype: LayerType = None) → Qobj

  Controlled Y gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing the rotation.

cz_gate(*, dtype: LayerType = None) → Qobj

  Controlled Z gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing the rotation.

fredkin(*, dtype: LayerType = None) → Qobj

  Quantum object representing the Fredkin gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    fredkin_gate qobj

      Quantum object representation of Fredkin gate.

globalphase(

  theta: float,
  N: int = 1,
  *,
  dtype: LayerType = None,

) → Qobj

  Returns quantum object representing the global phase shift gate.

  Parameters:
    theta float

      Phase rotation angle.

    N int:

      Number of qubits

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    phase_gate qobj

      Quantum object representation of global phase shift gate.

hadamard_transform(

  N: int = 1,
  *,
  dtype: LayerType = None,

) → Qobj

  Quantum object representing the N-qubit Hadamard gate.

  Parameters:
    N int:

      Number of qubits

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    q qobj

      Quantum object representation of the N-qubit Hadamard gate.

iswap(*, dtype: LayerType = None) → Qobj

  Quantum object representing the iSWAP gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    iswap_gate qobj

      Quantum object representation of iSWAP gate

molmer_sorensen(

  theta: float,
  *,
  dtype: LayerType = None,

) → Qobj

  Quantum object of a Mølmer–Sørensen gate.

  Parameters:
    theta: float

      The duration of the interaction pulse.

    target: int

      The indices of the target qubits.

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    molmer_sorensen_gate: `Qobj`

      Quantum object representation of the Mølmer–Sørensen gate.

phasegate(theta: float, *, dtype: LayerType = None) → Qobj

  Returns quantum object representing the phase shift gate.

  Parameters:
    theta float

      Phase rotation angle.

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    phase_gate qobj

      Quantum object representation of phase shift gate.

qrot(

  theta: float,
  phi: float,
  *,
  dtype: LayerType = None,

) → Qobj

  Single qubit rotation driving by Rabi oscillation with 0 detune.

  Parameters:
    phi float

      The inital phase of the rabi pulse.

    theta float

      The duration of the rabi pulse.

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    qrot_gate `Qobj`

      Quantum object representation of physical qubit rotation under a rabi pulse.

qubit_clifford_group(*, dtype: LayerType = None) → list[Qobj]

  Generates the Clifford group on a single qubit, using the presentation of the group given by Ross and Selinger (http://www.mathstat.dal.ca/~selinger/newsynth/).

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    op list of Qobj

      Clifford operators, represented as Qobj instances.

rx(phi: float, *, dtype: LayerType = None) → Qobj

  Single-qubit rotation for operator sigmax with angle phi.

  Parameters:
    phi float

      Rotation angle

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result qobj

      Quantum object for operator describing the rotation.

ry(phi: float, *, dtype: LayerType = None) → Qobj

  Single-qubit rotation for operator sigmay with angle phi.

  Parameters:
    phi float

      Rotation angle

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result qobj

      Quantum object for operator describing the rotation.

rz(phi: float, *, dtype: LayerType = None) → Qobj

  Single-qubit rotation for operator sigmaz with angle phi.

  Parameters:
    phi float

      Rotation angle

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result qobj

      Quantum object for operator describing the rotation.

s_gate(*, dtype: LayerType = None) → Qobj

  Single-qubit rotation also called Phase gate or the Z90 gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing a 90 degree rotation around the z-axis.

snot(*, dtype: LayerType = None) → Qobj

  Quantum object representing the SNOT (Hadamard) gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    snot_gate qobj

      Quantum object representation of SNOT gate.

sqrtiswap(*, dtype: LayerType = None) → Qobj

  Quantum object representing the square root iSWAP gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    sqrtiswap_gate qobj

      Quantum object representation of square root iSWAP gate

sqrtnot(*, dtype: LayerType = None) → Qobj

  Single-qubit square root NOT gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result qobj

      Quantum object for operator describing the square root NOT gate.

sqrtswap(*, dtype: LayerType = None) → Qobj

  Quantum object representing the square root SWAP gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    sqrtswap_gate qobj

      Quantum object representation of square root SWAP gate

swap(*, dtype: LayerType = None) → Qobj

  Quantum object representing the SWAP gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    swap_gate qobj

      Quantum object representation of SWAP gate

swapalpha(alpha: float, *, dtype: LayerType = None) → Qobj

  Quantum object representing the SWAPalpha gate.

  Parameters:
    alpha float

      Angle of the SWAPalpha gate.

    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    swapalpha_gate qobj

      Quantum object representation of SWAPalpha gate

t_gate(*, dtype: LayerType = None) → Qobj

  Single-qubit rotation related to the S gate by the relationship S=T*T.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    result `Qobj`

      Quantum object for operator describing a phase shift of pi/4.

toffoli(*, dtype: LayerType = None) → Qobj

  Quantum object representing the Toffoli gate.

  Parameters:
    dtype str or type, [keyword only] [optional]

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    toff_gate qobj

      Quantum object representation of Toffoli gate.

## Excitation-Number Restricted Operators

enr_destroy(dims, excitations, *, dtype=None)

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

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

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

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

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

  Parameters:
    dims list

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

    excitations integer

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

    dtype type or str, optional

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    a_ops list of qobj

      A list of annihilation operators for each mode in the composite quantum system described by dims.

enr_fock(dims, excitations, state, *, dtype=None)

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

  Parameters:
    dims list

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

    excitations integer

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

    state list of integers

      The state in the number basis representation.

    dtype type or str, optional

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    ket Qobj

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

enr_identity(dims, excitations, *, dtype=None)

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

  Parameters:
    dims list

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

    excitations integer

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

    dtype type or str, optional

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    op Qobj

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

enr_state_dictionaries(dims, excitations)

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

  Parameters:
    dims: list

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

    excitations integer

      The maximum numbers of dimension

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

      The number of states nstates, a dictionary for looking up state indices from a state tuple, and a dictionary for looking up state state tuples from state indices. state2idx and idx2state are reverses of each other, i.e., `state2idx[idx2state[idx]] = idx` and `idx2state[state2idx[state]] = state`.

enr_thermal_dm(dims, excitations, n, *, dtype=None)

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

  Parameters:
    dims list

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

    excitations integer

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

    n integer

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

    dtype type or str, optional

      Storage representation. Any data-layer known to qutip.data.to is accepted.

  Returns:
    dm Qobj

      Thermal state density matrix.

## Random Operators and States

This module is a collection of random state and operator generators.

rand_dm(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  density: float = 0.75,
  distribution: Literal['ginibre', 'hs', 'pure', 'eigen', 'uniform'] = 'ginibre',
  *,
  eigenvalues: Sequence[float] = (),
  rank: int = None,
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Creates a random density matrix of the desired dimensions.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      > Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either `oper` or `super` depending on the passed `dimensions`.

      densityfloat, default: 0.75

        Density between [0,1] of output density matrix. Used by the “pure”, “eigen” and “herm”.

      distribution : str {“ginibre”, “hs”, “pure”, “eigen”, “uniform”},

    default: “ginibre”

      > Method used to obtain the density matrices.

      > - “ginibre” : Ginibre random density operator of rank `rank` by using the algorithm of [BCSZ08].

      > - “hs” : Hilbert-Schmidt ensemble, equivalent to a full rank ginibre operator.

      > - “pure” : Density matrix created from a random ket.

      > - “eigen” : A density matrix with the given `eigenvalues`.

      > - “herm” : Build from a random hermitian matrix using `rand_herm`.

      eigenvaluesarray_like, optional

        Eigenvalues of the output Hermitian matrix. The len must match the shape of the matrix.

      rankint, optional

        When using the “ginibre” distribution, rank of the density matrix. Will default to a full rank operator when not provided.

      seedint, SeedSequence, Generator, optional

        Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

      dtypetype or str, optional

        Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Density matrix quantum operator.

rand_herm(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  density: float = 0.3,
  distribution: Literal['fill', 'pos_def', 'eigen'] = 'fill',
  *,
  eigenvalues: Sequence[float] = (),
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Creates a random sparse Hermitian quantum object.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    density float, default: 0.30

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

    distribution str {“fill”, “pos_def”, “eigen”}, default: “fill”

      Method used to obtain the density matrices.

      - “fill” : Uses \(H=0.5*(X+X^{+})\) where \(X\) is a randomly generated quantum operator with elements uniformly distributed between `[-1, 1] + [-1j, 1j]`.

      - “eigen” : A density matrix with the given `eigenvalues`. It uses random complex Jacobi rotations to shuffle the operator.

      - “pos_def” : Return a positive semi-definite matrix by diagonal dominance.

    eigenvalues array_like, optional

      Eigenvalues of the output Hermitian matrix. The len must match the shape of the matrix.

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper `Qobj`

      Hermitian quantum operator.

  Notes

  If given a list of eigenvalues the object is created using complex Jacobi rotations. While this method is fast for small matrices, it should not be repeatedly used for generating matrices larger than ~1000x1000.

rand_ket(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  density: float = 1,
  distribution: Literal['haar', 'fill'] = 'haar',
  *,
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Creates a random ket vector.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    density float, default: 1

      Density between [0,1] of output ket state when using the `fill` method.

    distribution str {“haar”, “fill”}, default: “haar”

      Method used to obtain the kets.

      - haar : Haar random pure state obtained by applying a Haar random unitary to a fixed pure state.

      - fill : Fill the ket with uniformly distributed random complex number.

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Ket quantum state vector.

rand_kraus_map(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  *,
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Creates a random CPTP map on an N-dimensional Hilbert space in Kraus form.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper_list list of qobj

      N^2 x N x N qobj operators.

rand_stochastic(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  density: float = 0.75,
  kind: Literal['left', 'right'] = 'left',
  *,
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Generates a random stochastic matrix.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    density float, default: 0.75

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

    kind str {“left”, “right”}, default: “left”

      Generate ‘left’ or ‘right’ stochastic matrix.

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Quantum operator form of stochastic matrix.

rand_super(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  *,
  superrep: Literal['super', 'choi', 'chi'] = 'super',
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

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

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    superrop str, default: “super”

      Representation of the super operator

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

rand_super_bcsz(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  enforce_tp: bool = True,
  rank: int = None,
  *,
  superrep: Literal['super', 'choi', 'chi'] = 'super',
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

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

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If an int is provided, it is understood as the Square root of the dimension of the superoperator to be returned, with the corresponding dims as `[[[N],[N]], [[N],[N]]]`. If provided as a list of ints, then the dimensions is understood as the space of density matrices this superoperator is applied to: `dimensions=[2,2]` `dims=[[[2,2],[2,2]], [[2,2],[2,2]]]`.

    enforce_tp bool, default: True

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

    rank int, optional

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

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    superrop str, default: “super”

      representation of the

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    rho Qobj

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

rand_unitary(

  dimensions: int | list[int] | list[list[int]] | Space | tuple[TypeAliasForwardRef('SpaceLike'), ...],
  density: float = 1,
  distribution: Literal['haar', 'exp'] = 'haar',
  *,
  seed: int | SeedSequence | Generator = None,
  dtype: str | type = None,

)

  Creates a random sparse unitary quantum object.

  Parameters:
    dimensions(int) or (list of int) or (list of list of int)

      Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the `dims` property of the new Qobj are set to this list. This can produce either oper or super depending on the passed dimensions.

    density float, default: 1

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

    distribution str {“haar”, “exp”}, default: “haar”

      Method used to obtain the unitary matrices.

      - haar : Haar random unitary matrix using the algorithm of [Mez07].

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

    seed int, SeedSequence, Generator, optional

      Seed to create the random number generator or a pre prepared generator. When none is suplied, a default generator is used.

    dtype type or str, optional

      Storage representation. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    oper qobj

      Unitary quantum operator.

# Manipulation of Qobj

## Tensor

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

composite(*args: Qobj) → Qobj
composite(

  *args: Qobj | QobjEvo,

) → QobjEvo

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

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

expand_operator(

  oper: QobjOrQobjEvo,
  dims: list[int],
  targets: int,
  dtype: str | type = None,

) → QobjOrQobjEvo

  Expand an operator to one that acts on a system with desired dimensions.

  Example

      expand_operator(oper, [2, 3, 4, 5], 2) ==
          tensor(qeye(2), qeye(3), oper, qeye(5))
      expand_operator(tensor(oper1, oper2), [2, 3, 4, 5], [2, 0]) ==
          tensor(oper2, qeye(3), oper1, qeye(5))

  Parameters:
    oper `Qobj`

      An operator that act on the subsystem, has to be an operator and the dimension matches the tensored dims Hilbert space e.g. oper.dims = `[[2, 3], [2, 3]]`

    dims list

      A list of integer for the dimension of each composite system. E.g `[2, 3, 2, 3, 4]`.

    targets int or list of int

      The indices of subspace that are acted on.

    dtype str, optional

      Data type of the output `Qobj`. By default it uses the data type specified in settings. If no data type is specified in settings it uses the `CSR` data type.

  Returns:
    expanded_oper `Qobj`

      The expanded operator acting on a system with the desired dimension.

super_tensor(*args: Qobj) → Qobj
super_tensor(

  *args: Qobj | QobjEvo,

) → QobjEvo

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

  Parameters:
    args array_like

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

  Returns:
    obj qobj

      A composite quantum object.

tensor(*args: Qobj) → Qobj
tensor(

  *args: Qobj | QobjEvo,

) → QobjEvo

  Calculates the tensor product of input operators.

  Parameters:
    args array_like

      `list` or `array` of quantum objects for tensor product.

  Returns:
    obj qobj

      A composite quantum object.

  Examples

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

tensor_contract(

  qobj: Qobj,
  *pairs: tuple[int, int],

) → Qobj

  Contracts a qobj along one or more index pairs.

  Note

  Note that this uses dense representations and thus should not be used for very large Qobjs.

  Parameters:
    qobj: :class:`.Qobj`

      Operator to contract subspaces on.

    pairs tuple

      One or more tuples `(i, j)` indicating that the `i` and `j` dimensions of the original qobj should be contracted.

  Returns:
    cqobj `Qobj`

      The original `Qobj` with all named index pairs contracted away.

tensor_swap(

  q_oper: Qobj,
  *pairs: tuple[int, int],

) → Qobj

  Transposes one or more pairs of indices of a `Qobj`.

  Note

  Note that this uses dense representations and thus should not be used for very large Qobjs.

  Parameters:
    q_oper `Qobj`

      Operator to swap dims.

    pairs tuple

      One or more tuples `(i, j)` indicating that the `i` and `j` dimensions of the original qobj should be swapped.

  Returns:
    sqobj `Qobj`

      The original `Qobj` with all named index pairs swapped with each other

The Quantum Object (Qobj) class, for representing quantum states and operators, and related functions.

ptrace(Q: Qobj, sel: int | list[int]) → Qobj

  Partial trace of the Qobj with selected components remaining.

  Parameters:
    Q `Qobj`

      Composite quantum object.

    sel int/list

      An `int` or `list` of components to keep after partial trace.

  Returns:
    oper `Qobj`

      Quantum object representing partial trace with selected components remaining.

  Notes

  This function is for legacy compatibility only. It is recommended to use the `ptrace()` Qobj method.

partial_transpose(rho, mask, method='dense')

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

  Parameters:
    rho `Qobj`

      A density matrix.

    mask list / array

      A mask that selects which subsystems should be transposed.

    method str {“dense”, “sparse”}, default: “dense”

      Choice of method. The “sparse” implementation can be faster for large and sparse systems (hundreds of quantum states).

  Returns:
    rho_pr: `Qobj`

      A density matrix with the selected subsystems transposed.

## Superoperators and Liouvillians

lindblad_dissipator(

  a: Qobj,
  b: Qobj,
  data_only: bool,
  chi: list[float],

) → Qobj
lindblad_dissipator(

  a: Qobj | QobjEvo,
  b: Qobj | QobjEvo,
  data_only: bool,
  chi: list[float],

) → QobjEvo

  Lindblad dissipator (generalized) for a single pair of collapse operators (a, b), or for a single collapse operator (a) when b is not specified:

  \[\mathcal{D}[a,b]\rho = a \rho b^\dagger - \frac{1}{2}a^\dagger b\rho - \frac{1}{2}\rho a^\dagger b\]
  Parameters:
    a Qobj or QobjEvo

      Left part of collapse operator.

    b Qobj or QobjEvo, optional

      Right part of collapse operator. If not specified, b defaults to a.

    chi float, optional

      In some systems it is possible to determine the statistical moments (mean, variance, etc) of the probability distribution of the occupation numbers of states by numerically evaluating the derivatives of the steady state occupation probability as a function of an artificial phase parameter `chi` which multiplies the `a \rho a^dagger` term of the dissipator by `e ^ (i * chi)`. The factor `e ^ (i * chi)` is introduced via the generating function of the statistical moments. For examples of the technique, see Full counting statistics of nano-electromechanical systems and Photon-mediated electron transport in hybrid circuit-QED. This parameter is deprecated and may be removed in QuTiP 5.

    data_only bool, default: False

      Return the data object instead of a Qobj

  Returns:
    D qobj, QobjEvo

      Lindblad dissipator superoperator.

liouvillian(

  H: Qobj,
  c_ops: list[Qobj],
  data_only: bool,
  chi: list[float],

) → Qobj
liouvillian(

  H: Qobj | QobjEvo,
  c_ops: list[Qobj | QobjEvo],
  data_only: bool,
  chi: list[float],

) → QobjEvo

  Assembles the Liouvillian superoperator from a Hamiltonian and a `list` of collapse operators.

  Parameters:
    H Qobj or QobjEvo, optional

      System Hamiltonian or Hamiltonian component of a Liouvillian. Considered 0 if not given.

    c_ops array_like of Qobj or QobjEvo, optional

      A `list` or `array` of collapse operators.

    data_only bool, default: False

      Return the data object instead of a Qobj

    chi array_like of float, optional

      In some systems it is possible to determine the statistical moments (mean, variance, etc) of the probability distributions of occupation of various states by numerically evaluating the derivatives of the steady state occupation probability as a function of artificial phase parameters `chi` which are included in the `lindblad_dissipator` for each collapse operator. See the documentation of `lindblad_dissipator` for references and further details. This parameter is deprecated and may be removed in QuTiP 5.

  Returns:
    L Qobj or QobjEvo

      Liouvillian superoperator.

operator_to_vector(op: Qobj) → Qobj

  Create a vector representation given a quantum operator in matrix form. The passed object should have a `Qobj.type` of ‘oper’ or ‘super’; this function is not designed for general-purpose matrix reshaping.

  Parameters:
    op Qobj or QobjEvo

      Quantum operator in matrix form. This must have a type of ‘oper’ or ‘super’.

  Returns:
    Qobj or QobjEvo

      The same object, but re-cast into a column-stacked-vector form of type ‘operator-ket’. The output is the same type as the passed object.

santicommutator(

  A: AnyQobj,

) → AnyQobj

  Generates the anticommutator superoperator for a given quantum object.

  This superoperator represents the linear map that takes an operator (such as a density matrix) to its anticommutator with the given operator A. Mathematically, it represents the operation: \({A, \rho} = A \rho + \rho A\)

  Parameters:
    A Qobj or QobjEvo

      Quantum operator for which the anticommutator superoperator is generated.

  Returns:
    super :Qobj or QobjEvo

      The anticommutator superoperator formed from the input quantum object.

scommutator(

  A: AnyQobj,

) → AnyQobj

  Generates the commutator superoperator for a given quantum object.

  This superoperator represents the linear map that takes an operator (such as a density matrix) to its commutator with the given operator A. Mathematically, it represents the operation: \([A, \rho] = A \rho - \rho A\)

  Parameters:
    A Qobj or QobjEvo

      Quantum operator for which the commutator superoperator is generated.

  Returns:
    super :Qobj or QobjEvo

      The commutator superoperator formed from the input quantum object.

spost(A: AnyQobj) → AnyQobj

  Superoperator formed from post-multiplication by operator A

  Parameters:
    A Qobj or QobjEvo

      Quantum operator for post multiplication.

  Returns:
    super Qobj or QobjEvo

      Superoperator formed from input qauntum object.

  Notes

  The function spost is only defined for square operators. For rectangular operators, use instead sprepost(qeye(…), A) with an identity operator of the appropriate dimensions.

spre(A: AnyQobj) → AnyQobj

  Superoperator formed from pre-multiplication by operator A.

  Parameters:
    A Qobj or QobjEvo

      Quantum operator for pre-multiplication.

  Returns:
    super :Qobj or QobjEvo

      Superoperator formed from input quantum object.

  Notes

  The function spre is only defined for square operators. For rectangular operators, use instead sprepost(A, qeye(…)) with an identity operator of the appropriate dimensions.

sprepost(

  A: Qobj,
  B: Qobj,

) → Qobj
sprepost(

  A: Qobj | QobjEvo,
  B: Qobj | QobjEvo,

) → QobjEvo

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

  Parameters:
    A Qobj or QobjEvo

      Quantum operator for pre-multiplication.

    B Qobj or QobjEvo

      Quantum operator for post-multiplication.

  Returns:
    super Qobj or QobjEvo

      Superoperator formed from input quantum objects.

vector_to_operator(op: Qobj) → Qobj

  Create a matrix representation given a quantum operator in vector form. The passed object should have a `Qobj.type` of ‘operator-ket’; this function is not designed for general-purpose matrix reshaping.

  Parameters:
    op Qobj or QobjEvo

      Quantum operator in column-stacked-vector form. This must have a type of ‘operator-ket’.

  Returns:
    Qobj or QobjEvo

      The same object, but re-cast into “standard” operator form. The output is the same type as the passed object.

## Superoperators and Liouvillians

bloch_redfield_tensor(

  H: Qobj,
  a_ops: list[tuple[Qobj, Coefficient | str | CoeffProtocol | BosonicEnvironment | FermionicEnvironment]],
  c_ops: list[Qobj] = None,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → Qobj
bloch_redfield_tensor(

  H: Qobj | QobjEvo,
  a_ops: list[tuple[Qobj | QobjEvo, Coefficient | str | CoeffProtocol | BosonicEnvironment | FermionicEnvironment]],
  c_ops: list[Qobj | QobjEvo] = None,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → QobjEvo

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

  Parameters:
    H `qutip.Qobj`, `qutip.QobjEvo`

      System Hamiltonian.

    a_ops list of (a_op, spectra)

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

      a_op`qutip.Qobj`, `qutip.QobjEvo`

        The operator coupling to the environment. Must be hermitian.

      spectra`Coefficient`, func, str, Environment

        The corresponding bath spectra. Bath can be provided as `BosonicEnvironment`, `FermionicEnvironment` or power spectra function. These can be a `Coefficient`, function or string. For coefficient, the frequency is passed as the ‘w’ args. The `SpectraCoefficient` can be used for array based coefficient.

        The spectra can depend on `t` if `a_op` is a `QobjEvo`.

      Example:

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

    c_ops list

      List of system collapse operators.

    sec_cutoff float {0.1}

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

    fock_basis bool {False}

      Whether to return the tensor in the input basis or the diagonalized basis.

    sparse_eigensolver bool {False}

      Deprecated

    br_computation_method[‘sparse’, ‘dense’, ‘matrix’]

      How computation for the tensor is made. With ‘dense’ or ‘sparse’, the secular cutoff is checked first and only elements within the approximation are computed and stored in an (sparse) array. With ‘matrix’, the tensor is build using matrix operation and the secular cutoff is applied at the end.

  Returns:
    R, [evecs]: `qutip.Qobj`, tuple of `qutip.Qobj`

      If `fock_basis`, return the Bloch Redfield tensor in the laboratory basis. Otherwise return the Bloch Redfield tensor in the diagonalized Hamiltonian basis and the eigenvectors of the Hamiltonian as hstacked column.

brcrossterm(

  H: Qobj,
  a_op: Qobj,
  b_op: Qobj,
  spectra: Coefficient | CoeffProtocol | str,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → Qobj
brcrossterm(

  H: Qobj | QobjEvo,
  a_op: Qobj | QobjEvo,
  b_op: Qobj | QobjEvo,
  spectra: Coefficient | CoeffProtocol | str,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → QobjEvo

  Calculates the contribution of one coupling operator to the Bloch-Redfield tensor.

  Parameters:
    H `qutip.Qobj`, `qutip.QobjEvo`

      System Hamiltonian.

    a_op `qutip.Qobj`, `qutip.QobjEvo`

      The operator coupling to the environment.

    b_op `qutip.Qobj`, `qutip.QobjEvo`

      The operator coupling to the environment.

    spectra `Coefficient`, func, str, Environment

      The corresponding bath spectra. Bath can be provided as `BosonicEnvironment`, `FermionicEnvironment` or power spectra function. These can be a `Coefficient`, function or string. For coefficient, the frequency is passed as the ‘w’ args. The `SpectraCoefficient` can be used for array based coefficient.

      The spectra can depend on `t` if `a_op` is a `QobjEvo`.

      Example:

      > coefficient(‘w>0’, args={“w”: 0}) SpectraCoefficient(coefficient(array, tlist=…)) lambda w: (w > 0) * 1. BosonicEnvironment(…)

    sec_cutoff float {0.1}

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

    fock_basis bool {False}

      Whether to return the tensor in the input basis or the diagonalized basis.

    sparse_eigensolver bool {False}

      Deprecated

    br_computation_method[‘dense’, ‘sparse’, ‘matrix’]

      How computation for the tensor is made. With ‘dense’ or ‘sparse’, the secular cutoff is checked first and only elements within the approximation are computed and stored in an (sparse) array. With ‘matrix’, the tensor is build using matrix operation and the secular cutoff is applied at the end.

  Returns:
    R, [evecs]: `Qobj`, `QobjEvo` or tuple

      If `fock_basis`, return the Bloch Redfield tensor in the outside basis. Otherwise return the Bloch Redfield tensor in the diagonalized Hamiltonian basis and the eigenvectors of the Hamiltonian as hstacked column. The tensors and, if given, evecs, will be `QobjEvo` if the `H` and `a_op` is time dependent, `Qobj` otherwise.

brterm(

  H: Qobj,
  a_op: Qobj,
  spectra: Coefficient | str | CoeffProtocol | BosonicEnvironment | FermionicEnvironment,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → Qobj
brterm(

  H: Qobj | QobjEvo,
  a_op: Qobj | QobjEvo,
  spectra: Coefficient | str | CoeffProtocol | BosonicEnvironment | FermionicEnvironment,
  sec_cutoff: float = 0.1,
  fock_basis: bool = False,
  sparse_eigensolver: bool = False,
  br_computation_method: str = 'sparse',

) → QobjEvo

  Calculates the contribution of one coupling operator to the Bloch-Redfield tensor.

  Parameters:
    H `qutip.Qobj`, `qutip.QobjEvo`

      System Hamiltonian.

    a_op `qutip.Qobj`, `qutip.QobjEvo`

      The operator coupling to the environment. Expected to be hermitian.

    spectra `Coefficient`, func, str, Environment

      The corresponding bath spectra. Bath can be provided as `BosonicEnvironment`, `FermionicEnvironment` or power spectra function. These can be a `Coefficient`, function or string. For coefficient, the frequency is passed as the ‘w’ args. The `SpectraCoefficient` can be used for array based coefficient.

      The spectra can depend on `t` if `a_op` is a `QobjEvo`.

      Example:

      > coefficient(‘w>0’, args={“w”: 0}) SpectraCoefficient(coefficient(array, tlist=…)) lambda w: (w > 0) * 1. BosonicEnvironment(…)

    sec_cutoff float {0.1}

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

    fock_basis bool {False}

      Whether to return the tensor in the input basis or the diagonalized basis.

    sparse_eigensolver bool {False}

      Deprecated

    br_computation_method[‘sparse’, ‘dense’, ‘matrix’]

      How computation for the tensor is made. With ‘dense’ or ‘sparse’, the secular cutoff is checked first and only elements within the approximation are computed and stored in an (sparse) array. With ‘matrix’, the tensor is build using matrix operation and the secular cutoff is applied at the end.

  Returns:
    R, [evecs]: `Qobj`, `QobjEvo` or tuple

      If `fock_basis`, return the Bloch Redfield tensor in the outside basis. Otherwise return the Bloch Redfield tensor in the diagonalized Hamiltonian basis and the eigenvectors of the Hamiltonian as hstacked column. The tensors and, if given, evecs, will be `QobjEvo` if the `H` and `a_op` is time dependent, `Qobj` otherwise.

## Superoperator Representations

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

kraus_to_choi(kraus_ops: list[Qobj]) → Qobj

  Convert a list of Kraus operators into Choi representation of the channel.

  Essentially, kraus operators are a decomposition of a Choi matrix, and its reconstruction from them should go as \(E = \sum_{i} |K_i\rangle\rangle \langle\langle K_i|\), where we use vector representation of Kraus operators.

  Parameters:
    kraus_ops list[Qobj]

      The list of Kraus operators to be converted to Choi representation.

  Returns:
    choi Qobj

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

kraus_to_super(

  kraus_list: list[Qobj],
  sparse=False,

) → Qobj

  Convert a list of Kraus operators to a superoperator.

  Parameters:
    kraus_list list of Qobj

      The list of Kraus super operators to convert.

    sparse: bool

      Prevents dense intermediates if true.

superpauli_to_super(q_oper)

  Convert a Pauli Transfer Matrix back to a standard superoperator in the column-stacking basis.

  Parameters:
    q_oper `Qobj`

      Superoperator in the Pauli basis.

  Returns:
    oper `Qobj`

      Superoperator in the standard QuTiP column-stacking basis with `superrep='super'`.

to_chi(q_oper: Qobj) → Qobj

  Converts a Qobj representing a quantum map to a representation as a chi (process) matrix in the Pauli basis, such that the trace of the returned operator is equal to the dimension of the system.

  Parameters:
    q_oper Qobj

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

  Returns:
    chi Qobj

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

  Raises:
    TypeError:

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

to_choi(q_oper: Qobj) → Qobj

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

  Parameters:
    q_oper Qobj

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

  Returns:
    choi Qobj

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

  Raises:
    TypeError:

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

to_kraus(

  q_oper: Qobj,
  tol: float = 1e-09,

) → list[Qobj]

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

  Parameters:
    q_oper Qobj

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

    tol Float, default: 1e-9

      Optional threshold parameter for eigenvalues/Kraus ops to be discarded.

  Returns:
    kraus_ops list of Qobj

      A list of quantum objects, each representing a Kraus operator in the decomposition of `q_oper`.

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

      decomposed into Kraus operators.

to_stinespring(

  q_oper: Qobj,
  threshold: float = 1e-10,

) → tuple[Qobj, Qobj]

  Converts a Qobj representing a quantum map \(\Lambda\) to a pair of partial isometries `A` and `B` such that \(\Lambda(X) = \Tr_2(A X B^\dagger)\) for all inputs `X`, where the partial trace is taken over a a new index on the output dimensions of `A` and `B`.

  For completely positive inputs, `A` will always equal `B` up to precision errors.

  Parameters:
    q_oper Qobj

      Superoperator to be converted to a Stinespring pair.

    threshold float, default: 1e-10

      Threshold parameter for eigenvalues/Kraus ops to be discarded.

  Returns:
    A, B Qobj

      Quantum objects representing each of the Stinespring matrices for the input Qobj.

to_super(q_oper: Qobj) → Qobj

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

  Parameters:
    q_oper Qobj

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

  Returns:
    superop Qobj

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

  Raises:
    TypeError

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

to_superpauli(q_oper)

  Convert a superoperator to the Pauli basis (Pauli Transfer Matrix).

  The Pauli basis is only defined for qubit systems. This representation is commonly used for visualization.

  Parameters:
    q_oper `Qobj`

      Superoperator or operator to be converted.

  Returns:
    ptm `Qobj`

      Quantum object representing the superoperator in the Pauli basis with `superrep='pauli'`.

## Direct Sum

direct_component(

  sum_qobj: Qobj,
  *index: int | slice,

) → Qobj
direct_component(

  sum_qobj: QobjEvo,
  *index: int | slice,

) → Qobj | QobjEvo

  Extract the component (block) at the given index from a direct sum `Qobj`.

  Parameters:
    sum_qobj `Qobj` or `QobjEvo`

      A direct sum object from which to extract a component.

    index list of int or slice

      One or two indices identifying the component to extract. If both the row and column spaces are sums, two indices (`row`, `col`) are required. If only one side is a sum, a single index is accepted and interpreted as the index into the summed side.

  Returns:
    component: `Qobj` or `QobjEvo`

      The extracted component.

  Notes

  Each index may be either an int indicating a single component or a slice indicating multiple components. For convenience, slices can be created using np.s_[start:stop]. Custom steps are not supported.

direct_sum(

  qobjs: list[Number | Qobj] | list[list[Number | Qobj]],
  dtype: LayerType = None,

) → Qobj
direct_sum(

  qobjs: list[Number | Qobj | QobjEvo] | list[list[Number | Qobj | QobjEvo]],
  dtype: LayerType = None,

) → QobjEvo

  Construct the direct sum of the provided component quantum objects. The matrix representing the returned direct sum is a block matrix, where the matrices of the components are all concatenated.

  This function accepts either a 1D list of components or a 2D square matrix (list of lists) of components. A 1D list is interpreted as a column or row block vector, depending on the element types:

  - If all elements are kets or scalars, the output will be a ket.

  - If all elements are bras or scalars, the output will be a bra.

  - If all elements are operator-kets, operators, or scalars, the operators will be converted to operator-kets automatically, and the output will be an operator-ket.

  - If all elements are operator-bras, operators, or scalars, the operators will be converted to operator-bras automatically, and the output will be an operator-bra.

  Python numbers are always accepted as scalars.

  A 2D square matrix may contain any types of Qobj, but the horizontal and vertical dimensions must match in each block row and block column. In a 2D square matrix, entries may be `None` to indicate zero blocks. However, each block row and each block column must contain at least one not-`None` entry. For direct sums with all-zero rows or columns, consider using `direct_sum_sparse`.

  Parameters:
    qobjs list

      1D list or 2D square matrix of components. The components may be Python numbers, `Qobj`, or `QobjEvo`.

    dtype type or str, optional

      Storage representation for the output `Qobj`. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    direct_sum: `Qobj` or `QobjEvo`

      The assembled direct-sum object. Returns a time-dependent object (`QobjEvo`) if any input component is time-dependent.

direct_sum_sparse(

  qobjs: dict[tuple[int, int], Number | Qobj],
  sum_dimensions: DimensionLike,
  dtype: LayerType = None,

) → Qobj
direct_sum_sparse(

  qobjs: dict[tuple[int, int], Number | Qobj | QobjEvo],
  sum_dimensions: DimensionLike,
  dtype: LayerType = None,

) → QobjEvo

  Construct the direct sum of the provided component quantum objects. This is a variant of `direct_sum` suitable for large, sparse block matrices. The caller must provide the dimensions of the direct sum, for example in list form as in `[([2], [3]), ([2], [3])]` for an operator on \(\mathbb C^2 \oplus \mathbb C^3\).

  In more detail: the `sum_dimensions` parameter is a list of two entries. The two entries of this list respectively correspond to the output and input Hilbert spaces of the quantum object. Each entry is the “list representation” of the dimensions of the corresponding Hilbert space, like it is used throughout QuTiP. For use in this function, either one of the two spaces or both of them must have the structure of a direct sum, which is represented as a tuple in the “list representation”.

  List representation syntax overview:

  - A normal, unmarked Hilbert space of dimension \(n\) is represented by the list `[n]`.

  - A product Hilbert space, where the constituents have the dimensions \(n_1\) up to \(n_k\), is represented by the list `[n1, n2, ..., nk]`.

  - The direct sum of Hilbert spaces, which have the list representations `l1` up to `[lk]`, is represented by the tuple `[l1, l2, ..., lk]`. Sum dimensions may be nested.

  - For example, the direct sum of a 2D space and a 3D space has the list representation `([2], [3])`.

  - As another example, the direct sum of a 2D space, and the product of two 3D spaces, is `([2], [3, 3])`.

  - Superoperators act on operator spaces; the list representation of an operator space is the list `[lOut, lIn]`, where `lIn` and `lOut` are list representations of the input and output spaces of the operators. Direct sum components may be either regular Hilbert spaces or operator spaces, but not mixed within the same quantum object.

  Parameters:
    qobjs dict

      Mapping that assigns a component to the given (row, col) location in the block matrix. Missing locations are filled with zero blocks. The components may be Python numbers, `Qobj`, or `QobjEvo`.

    sum_dimensions list of tuples or lists

      Dimensions of the resulting Qobj, like in the creation of a Qobj. See detailed explanation above.

    dtype type or str, optional

      Storage representation for the output `Qobj`. Any data-layer known to `qutip.data.to` is accepted.

  Returns:
    direct_sum: `Qobj` or `QobjEvo`

      The assembled direct-sum object. Returns a time-dependent object (`QobjEvo`) if any input component is time-dependent.

set_direct_component(

  sum_qobj: Qobj,
  component: Qobj,
  *index: int | slice,
  dtype: LayerType = None,

) → Qobj
set_direct_component(

  sum_qobj: Qobj | QobjEvo,
  component: Qobj | QobjEvo,
  *index: int | slice,
  dtype: LayerType = None,

) → QobjEvo

  Set (replace) a component in a direct sum `Qobj`. The function returns a new object where the component at the given index is replaced with `component`.

  Parameters:
    sum_qobj `Qobj` or `QobjEvo`

      The direct sum object whose component will be replaced.

    component `Qobj` or `QobjEvo`

      The new component to insert. `None` sets the component to zero.

    index list of int or slice

      One or two indices identifying the component to extract. If both the row and column spaces are sums, two indices (`row`, `col`) are required. If only one side is a sum, a single index is accepted and interpreted as the index into the summed side.

  Returns:
    updated: `Qobj` or `QobjEvo`

      The resulting direct sum object with the component set.

  Notes

  Each index may be either an int indicating a single component or a slice indicating multiple components. For convenience, slices can be created using np.s_[start:stop]. Custom steps are not supported.

## Operators and Superoperator Dimensions

Internal use module for manipulating dims specifications.

einsum(subscripts, *operands)

  Implementation of numpy.einsum for Qobj. Evaluates the Einstein summation convention on the operands.

  Parameters:
    subscripts: str

      Specifies the subscripts for summation as comma separated list of subscript labels.

    operands: list of array_like

      These are the arrays for the operation.

  Returns:
    Qobj (numpy.complex128)

      Result of einsum as Qobj (numpy.complex128 if result is scalar)

from_tensor_rep(tensorrep, dims)

  Reverse operator of `to_tensor_rep`. Create a Qobj From a N-dimensions numpy array and dimensions with N indices.

  Parameters:
    tensorrep: ndarray

      Numpy array with one dimension for each index in dims.

    dims: list of list, Dimensions

      Dimensions of the Qobj.

  Returns:
    Qobj

      Re constructed Qobj

to_tensor_rep(q_oper)

  Transform a `Qobj` to a numpy array whose shape is the flattened dimensions.

  Parameters:
    q_oper: Qobj

      Object to reshape

  Returns:
    ndarray:

      Numpy array with one dimension for each index in dims.

  Examples

      >>> ket.dims
      [[2, 3], [1]]
      >>> to_tensor_rep(ket).shape
      (2, 3, 1)

      >>> oper.dims
      [[2, 3], [2, 3]]
      >>> to_tensor_rep(oper).shape
      (2, 3, 2, 3)

      >>> super_oper.dims
      [[[2, 3], [2, 3]], [[2, 3], [2, 3]]]
      >>> to_tensor_rep(super_oper).shape
      (2, 3, 2, 3, 2, 3, 2, 3)

## Miscellaneous

simdiag(

  ops,
  evals: bool = True,
  *,
  tol: float = 1e-14,
  safe_mode: bool = True,
  use_dense_solver: bool = True,

)

  Simultaneous diagonalization of commuting Hermitian matrices.

  Parameters:
    ops list, array

      `list` or `array` of qobjs representing commuting Hermitian operators.

    evals bool, default: True

      Whether to return the eigenvalues for each ops and eigenvectors or just the eigenvectors.

    tol float, default: 1e-14

      Tolerance for detecting degenerate eigenstates.

    safe_mode bool, default: True

      Whether to check that all ops are Hermitian and commuting. If set to `False` and operators are not commuting, the eigenvectors returned will often be eigenvectors of only the first operator.

    use_dense_solver: bool, default: True

      Whether to force use of numpy dense eigen solver. When `False` sparse operators will use scipy sparse eigen solver which is not appropriate for this use.

  Returns:
    eigs tuple

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

# Extracting data from Qobj

## Expectation Values

expect(oper: Qobj, state: Qobj) → complex
expect(

  oper: Qobj,
  state: Qobj | Sequence[Qobj],

) → ndarray[tuple[Any, ...], dtype[complex]]
expect(

  oper: Qobj | Sequence[Qobj],
  state: Qobj,

) → list[complex]
expect(

  oper: Qobj | Sequence[Qobj],
  state: Qobj | Sequence[Qobj],

) → list[ndarray[tuple[Any, ...], dtype[complex]]]

  Calculate the expectation value for operator(s) and state(s). The expectation of state `k` on operator `A` is defined as `k.dag() @ A @ k`, and for density matrix `R` on operator `A` it is `trace(A @ R)`.

  Parameters:
    oper qobj / list of Qobj

      A single or a list of operators for expectation value.

    state qobj / list of Qobj

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

  Returns:
    expt float / complex / list / array

      Expectation value(s). `real` if `oper` is Hermitian, `complex` otherwise. If multiple `oper` are passed, a list of array. A (nested) array of expectaction values if `state` or `oper` are arrays.

  Examples

      >>> expect(num(4), basis(4, 3)) == 3
          True

variance(oper: Qobj, state: Qobj) → complex
variance(

  oper: Qobj,
  state: list[Qobj],

) → ndarray[tuple[Any, ...], dtype[complex]]

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

  Parameters:
    oper Qobj

      Operator for expectation value.

    state Qobj / list of Qobj

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

  Returns:
    var float

      Variance of operator ‘oper’ for given state.

## Entropy Functions

concurrence(rho)

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

  Parameters:
    state qobj

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

  Returns:
    concur float

      Concurrence

  References

  [1]

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

entropy_conditional(rho, selB, base=2.718281828459045, sparse=False)

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

  Parameters:
    rho qobj

      Density matrix of composite object

    selB int/list

      Selected components for density matrix B

    base{e, 2}, default: e

      Base of logarithm.

    sparse bool, default: False

      Use sparse eigensolver.

  Returns:
    ent_cond float

      Value of conditional entropy

entropy_linear(rho)

  Linear entropy of a density matrix.

  Parameters:
    rho qobj

      sensity matrix or ket/bra vector.

  Returns:
    entropy float

      Linear entropy of rho.

  Examples

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

entropy_mutual(rho, selA, selB, base=2.718281828459045, sparse=False)

  Calculates the mutual information S(A:B) between selection components of a system density matrix.

  Parameters:
    rho qobj

      Density matrix for composite quantum systems

    selA int/list

      int or list of first selected density matrix components.

    selB int/list

      int or list of second selected density matrix components.

    base{e, 2}, default: e

      Base of logarithm.

    sparse bool, default: False

      Use sparse eigensolver.

  Returns:
    ent_mut float

      Mutual information between selected components.

entropy_relative(rho, sigma, base=2.718281828459045, sparse=False, tol=1e-12)

  Calculates the relative entropy S(rho||sigma) between two density matrices.

  Parameters:
    rho `Qobj`

      First density matrix (or ket which will be converted to a density matrix).

    sigma `Qobj`

      Second density matrix (or ket which will be converted to a density matrix).

    base{e, 2}, default: e

      Base of logarithm. Defaults to e.

    sparse bool, default: False

      Flag to use sparse solver when determining the eigenvectors of the density matrices. Defaults to False.

    tol float, default: 1e-12

      Tolerance to use to detect 0 eigenvalues or dot producted between eigenvectors. Defaults to 1e-12.

  Returns:
    rel_ent float

      Value of relative entropy. Guaranteed to be greater than zero and should equal zero only when rho and sigma are identical.

  References

  See Nielsen & Chuang, “Quantum Computation and Quantum Information”, Section 11.3.1, pg. 511 for a detailed explanation of quantum relative entropy.

  Examples

  First we define two density matrices:

      >>> rho = qutip.ket2dm(qutip.ket("00"))
      >>> sigma = rho + qutip.ket2dm(qutip.ket("01"))
      >>> sigma = sigma.unit()

  Then we calculate their relative entropy using base 2 (i.e. `log2`) and base e (i.e. `log`).

      >>> qutip.entropy_relative(rho, sigma, base=2)
      1.0
      >>> qutip.entropy_relative(rho, sigma)
      0.6931471805599453

entropy_vn(rho, base=2.718281828459045, sparse=False)

  Von-Neumann entropy of density matrix

  Parameters:
    rho qobj

      Density matrix.

    base{e, 2}, default: e

      Base of logarithm.

    sparse bool, default: False

      Use sparse eigensolver.

  Returns:
    entropy float

      Von-Neumann entropy of rho.

  Examples

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

## Density Matrix Metrics

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

average_gate_fidelity(oper, target=None)

  Returns the average gate fidelity of a quantum channel to the target channel, or to the identity channel if no target is given.

  Parameters:
    oper `Qobj`/list

      A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

    target `Qobj`

      A unitary operator

  Returns:
    fid float

      Average gate fidelity between oper and target, or between oper and identity.

  Notes

  The average gate fidelity is defined for example in: A. Gilchrist, N.K. Langford, M.A. Nielsen, Phys. Rev. A 71, 062310 (2005). The definition of state fidelity that the average gate fidelity is based on is the one from R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994). It is the square of the fidelity implemented in `qutip.core.metrics.fidelity` which follows Nielsen & Chuang, “Quantum Computation and Quantum Information”

bures_angle(A, B)

  Returns the Bures Angle between two density matrices A & B.

  The Bures angle ranges from 0, for states with unit fidelity, to pi/2.

  Parameters:
    A qobj

      Density matrix or state vector.

    B qobj

      Density matrix or state vector with same dimensions as A.

  Returns:
    angle float

      Bures angle between density matrices.

bures_dist(A, B)

  Returns the Bures distance between two density matrices A & B.

  The Bures distance ranges from 0, for states with unit fidelity, to sqrt(2).

  Parameters:
    A qobj

      Density matrix or state vector.

    B qobj

      Density matrix or state vector with same dimensions as A.

  Returns:
    dist float

      Bures distance between density matrices.

dnorm(A, B=None, solver='CVXOPT', verbose=False, force_solve=False, sparse=True)

  Calculates the diamond norm of the quantum map q_oper, using the simplified semidefinite program of [Wat13].

  The diamond norm SDP is solved by using CVXPY.

  If B is provided and both A and B are unitary, then the diamond norm of the difference is calculated more efficiently using the following geometric interpretation: \(\|A - B\|_{\diamond}\) equals \(2 \sqrt(1 - d^2)\), where \(d`is the distance between the origin and the convex hull of the eigenvalues of :math:`A B^{\dagger}\). See [AKN98] page 18, in the paragraph immediately below the proof of 12.6, as a reference.

  Parameters:
    A Qobj

      Quantum map to take the diamond norm of.

    B Qobj or None

      If provided, the diamond norm of \(A - B\) is taken instead.

    solver str {“CVXOPT”, “SCS”}, default: “CVXOPT”

      Solver to use with CVXPY. “SCS” tends to be significantly faster, but somewhat less accurate.

    verbose bool, default: False

      If True, prints additional information about the solution.

    force_solve bool, default: False

      If True, forces dnorm to solve the associated SDP, even if a special case is known for the argument.

    sparse bool, default: True

      Whether to use sparse matrices in the convex optimisation problem. Default True.

  Returns:
    dn float

      Diamond norm of q_oper.

  Raises:
    ImportError

      If CVXPY cannot be imported.

fidelity(A, B)

  Calculates the fidelity (pseudo-metric) between two density matrices.

  Parameters:
    A qobj

      Density matrix or state vector.

    B qobj

      Density matrix or state vector with same dimensions as A.

  Returns:
    fid float

      Fidelity pseudo-metric between A and B.

  Notes

  Uses the definition from Nielsen & Chuang, “Quantum Computation and Quantum Information”. It is the square root of the fidelity defined in R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994), used in `qutip.core.metrics.process_fidelity`.

  Examples

      >>> x = fock_dm(5,3)
      >>> y = coherent_dm(5,1)
      >>> np.testing.assert_almost_equal(fidelity(x,y), 0.24104350624628332)

hellinger_dist(A, B, sparse=False, tol=0)

  Calculates the quantum Hellinger distance between two density matrices.

  Formula:

  > `hellinger_dist(A, B) = sqrt(2 - 2 * tr(sqrt(A) * sqrt(B)))`

  See: D. Spehner, F. Illuminati, M. Orszag, and W. Roga, “Geometric measures of quantum correlations with Bures and Hellinger distances” arXiv:1611.03449

  Parameters:
    A `Qobj`

      Density matrix or state vector.

    B `Qobj`

      Density matrix or state vector with same dimensions as A.

    tol float, default: 0

      Tolerance used by sparse eigensolver, if used. (0 = Machine precision)

    sparse bool, default: False

      Use sparse eigensolver.

  Returns:
    hellinger_dist float

      Quantum Hellinger distance between A and B. Ranges from 0 to sqrt(2).

  Examples

      >>> x = fock_dm(5,3)
      >>> y = coherent_dm(5,1)
      >>> np.allclose(hellinger_dist(x, y), 1.3725145002591095)
          True

hilbert_dist(A, B)

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

  Parameters:
    A qobj

      Density matrix or state vector.

    B qobj

      Density matrix or state vector with same dimensions as A.

  Returns:
    dist float

      Hilbert-Schmidt distance between density matrices.

  Notes

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

process_fidelity(oper, target=None)

  Returns the process fidelity of a quantum channel to the target channel, or to the identity channel if no target is given. The process fidelity between two channels is defined as the state fidelity between their normalized Choi matrices.

  Parameters:
    oper `Qobj`/list

      A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

    target `Qobj`/list, optional

      A unitary operator, or a superoperator in supermatrix, Choi or chi-matrix form, or a list of Kraus operators

  Returns:
    fid float

      Process fidelity between oper and target, or between oper and identity.

  Notes

  Since Qutip 5.0, this function computes the process fidelity as defined for example in: A. Gilchrist, N.K. Langford, M.A. Nielsen, Phys. Rev. A 71, 062310 (2005). Previously, it computed a function that is now implemented as `get_fidelity` in qutip-qtrl.

  The definition of state fidelity that the process fidelity is based on is the one from R. Jozsa, Journal of Modern Optics, 41:12, 2315 (1994). It is the square of the one implemented in `qutip.core.metrics.fidelity` which follows Nielsen & Chuang, “Quantum Computation and Quantum Information”

tracedist(A, B, sparse=False, tol=0)

  Calculates the trace distance between two density matrices.. See: Nielsen & Chuang, “Quantum Computation and Quantum Information”

  Parameters:
    A qobj

      Density matrix or state vector.

    B qobj

      Density matrix or state vector with same dimensions as A.

    tol float, default: 0

      Tolerance used by sparse eigensolver, if used. (0 = Machine precision)

    sparse bool, default: False

      Use sparse eigensolver.

  Returns:
    tracedist float

      Trace distance between A and B.

  Examples

      >>> x=fock_dm(5,3)
      >>> y=coherent_dm(5,1)
      >>> np.testing.assert_almost_equal(tracedist(x,y), 0.9705143161472971)

unitarity(oper)

  Returns the unitarity of a quantum map, defined as the Frobenius norm of the unital block of that map’s superoperator representation.

  Parameters:
    oper Qobj

      Quantum map under consideration.

  Returns:
    u float

      Unitarity of `oper`.

## Measurement of quantum states

Module for measuring quantum objects.

measure(state, ops, tol=None)

  A dispatch method that provides measurement results handling both observable style measurements and projector style measurements (POVMs and PVMs).

  For return signatures, please check:

  - `measure_observable` for observable measurements.

  - `measure_povm` for POVM measurements.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    ops `Qobj` or iterable of `Qobj`

      - measurement observable (`Qobj`); or

      - iterable of measurement operators \(M_i\) or kets (iterable of `Qobj`) Either:

      1. specifying a POVM such that \(E_i = M_i^\dagger M_i\)

      2. projection operators if ops correspond to projectors (such that

           \(E_i = M_i^\dagger = M_i\))

      3. kets (transformed to projectors)

    tol float, optional

      Smallest value for the probabilities. Default is qutip’s core settings’ `atol`.

measure_observable(state, op, tol=None)

  Perform a measurement specified by an operator on the given state.

  This function simulates the classic quantum measurement described in many introductory texts on quantum mechanics. The measurement collapses the state to one of the eigenstates of the given operator and the result of the measurement is the corresponding eigenvalue.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    op `Qobj`

      The measurement operator.

    tol float, optional

      Smallest value for the probabilities. Default is qutip’s core settings’ `atol`.

  Returns:
    measured_value float

      The result of the measurement (one of the eigenvalues of op).

    state `Qobj`

      The new state (a ket if a ket was given, otherwise a density matrix).

  Examples

  Measure the z-component of the spin of the spin-up basis state:

      >>> measure_observable(basis(2, 0), sigmaz())
      (1.0, Quantum object: dims = [[2], [1]], shape = (2, 1), type = ket
      Qobj data =
      [[-1.]
       [ 0.]])

  Since the spin-up basis is an eigenstate of sigmaz, this measurement always returns 1 as the measurement result (the eigenvalue of the spin-up basis) and the original state (up to a global phase).

  Measure the x-component of the spin of the spin-down basis state:

      >>> measure_observable(basis(2, 1), sigmax())
      (-1.0, Quantum object: dims = [[2], [1]], shape = (2, 1), type = ket
      Qobj data =
      [[-0.70710678]
       [ 0.70710678]])

  This measurement returns 1 fifty percent of the time and -1 the other fifty percent of the time. The new state returned is the corresponding eigenstate of sigmax.

  One may also perform a measurement on a density matrix. Below we perform the same measurement as above, but on the density matrix representing the pure spin-down state:

      >>> measure_observable(ket2dm(basis(2, 1)), sigmax())
      (-1.0, Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper
      Qobj data =
      [[ 0.5 -0.5]
       [-0.5  0.5]])

  The measurement result is the same, but the new state is returned as a density matrix.

measure_povm(state, ops, tol=None)

  Perform a measurement specified by list of POVMs.

  This function simulates a POVM measurement. The measurement collapses the state to one of the resultant states of the measurement and returns the index of the operator corresponding to the collapsed state as well as the collapsed state.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    ops iterable of `Qobj`

      Iterable of measurement operators \(M_i\) or kets. Either:

      1. specifying a POVM such that \(E_i = M_i^\dagger M_i\)

      2. projection operators if ops correspond to projectors (such that \(E_i = M_i^\dagger = M_i\))

      3. kets (transformed to projectors)

    tol float, optional

      Smallest value for the probabilities. Default is qutip’s core settings’ `atol`.

  Returns:
    index float

      The resultant index of the measurement.

    state `Qobj`

      The new state (a ket if a ket was given, otherwise a density matrix).

measurement_statistics(state, ops, tol=None)

  A dispatch method that provides measurement statistics handling both observable style measurements and projector style measurements(POVMs and PVMs).

  For return signatures, please check:

  - `measurement_statistics_observable` for observable measurements.

  - `measurement_statistics_povm` for POVM measurements.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    ops `Qobj` or iterable of `Qobj`

      - measurement observable (:class:.Qobj); or

      - iterable of measurement operators \(M_i\) or kets (iterable of `Qobj`) Either:

      1. specifying a POVM such that \(E_i = M_i^\dagger * M_i\)

      2. projection operators if ops correspond to projectors (such that

           \(E_i = M_i^\dagger = M_i\))

      3. kets (transformed to projectors)

    tol float, optional

      Smallest value for the probabilities. Default is qutip’s core settings’ `atol`.

measurement_statistics_observable(state, op, tol=None)

  Return the measurement eigenvalues, eigenstates (or projectors) and measurement probabilities for the given state and measurement operator.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    op `Qobj`

      The measurement operator.

    tol float, optional

      Smallest value for the probabilities. Default is qutip’s core settings’ `atol`.

  Returns:
    eigenvalues: list of float

      The list of eigenvalues of the measurement operator.

    projectors: list of `Qobj`

      Return the projectors onto the eigenstates.

    probabilities: list of float

      The probability of measuring the state as being in the corresponding eigenstate (and the measurement result being the corresponding eigenvalue).

measurement_statistics_povm(state, ops, tol=None)

  Returns measurement statistics (resultant states and probabilities) for a measurement specified by a set of positive operator valued measurements on a specified ket or density matrix.

  Parameters:
    state `Qobj`

      The ket or density matrix specifying the state to measure.

    ops iterable of `Qobj`

      Iterable of measurement operators \(M_i\) or kets. Either:

      1. specifying a POVM such that \(E_i = M_i^\dagger M_i\)

      2. projection operators if ops correspond to projectors (such that \(E_i = M_i^\dagger = M_i\))

      3. kets (transformed to projectors)

    tol float, optional

      Smallest value for the probabilities. Smaller probabilities will be rounded to `0`. Default is qutip’s core settings’ `atol`.

  Returns:
    collapsed_states list of `Qobj`

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

    probabilities list of floats

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