# Utility Functions

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

clebsch(j1, j2, j3, m1, m2, m3)

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

  Parameters:
    j1 float

      Total angular momentum 1.

    j2 float

      Total angular momentum 2.

    j3 float

      Total angular momentum 3.

    m1 float

      z-component of angular momentum 1.

    m2 float

      z-component of angular momentum 2.

    m3 float

      z-component of angular momentum 3.

  Returns:
    cg_coeff float

      Requested Clebsch-Gordan coefficient.

convert_unit(value, orig='meV', to='GHz')

  Convert an energy from unit orig to unit to.

  Parameters:
    value float / array

      The energy in the old unit.

    orig str, {“J”, “eV”, “meV”, “GHz”, “mK”}, default: “meV”

      The name of the original unit.

    to str, {“J”, “eV”, “meV”, “GHz”, “mK”}, default: “GHz”

      The name of the new unit.

  Returns:
    value_new_unit float / array

      The energy in the new unit.

n_thermal(w, w_th)

  Return the number of photons in thermal equilibrium for an harmonic oscillator mode with frequency ‘w’, at the temperature described by ‘w_th’ where \(\omega_{\rm th} = k_BT/\hbar\).

  Parameters:
    w float or ndarray

      Frequency of the oscillator.

    w_th float

      The temperature in units of frequency (or the same units as w).

  Returns:
    n_avg float or array

      Return the number of average photons in thermal equilibrium for a an oscillator with the given frequency and temperature.

## Fitting Functions

iterated_fit(

  fun: Callable[[...], complex],
  num_params: int,
  xdata: ArrayLike,
  ydata: ArrayLike,
  target_rmse: float = 1e-05,
  Nmin: int = 1,
  Nmax: int = 10,
  guess: TypeAliasForwardRef('ArrayLike') | Callable[[int], TypeAliasForwardRef('ArrayLike')] = None,
  lower: ArrayLike = None,
  upper: ArrayLike = None,
  sigma: float | TypeAliasForwardRef('ArrayLike') = None,
  maxfev: int = None,

) → tuple[float, TypeAliasForwardRef('ArrayLike')]

  Iteratively tries to fit the given data with a model of the form

  \[y = \sum_{k=1}^N f(x; p_{k,1}, \dots, p_{k,n})\]

  where f is a model function depending on n parameters, and the number N of terms is increased until the normalized rmse (root mean square error) falls below the target value.

  Parameters:
    fun callable

      The model function. Its first argument is the array xdata, its other arguments are the fitting parameters.

    num_params int

      The number of fitting parameters per term (n in the equation above). The function fun must take num_params+1 arguments.

    xdata array_like

      The independent variable.

    ydata array_like

      The dependent data.

    target_rmse optional, float

      Desired normalized root mean squared error (default 1e-5).

    Nmin optional, int

      The minimum number of terms to be used for the fit (default 1).

    Nmax optional, int

      The maximum number of terms to be used for the fit (default 10). If the number Nmax of terms is reached, the function returns even if the target rmse has not been reached yet.

    guess optional, array_like or callable

      This can be either a list of length n, with the i-th entry being the guess for the parameter \(p_{k,i}\) (for all terms \(k\)), or a function that provides different initial guesses for each term. Specifically, given a number N of terms, the function returns an array [[p11, …, p1n], [p21, …, p2n], …, [pN1, …, pNn]] of initial guesses.

    lower optional, list of length num_params

      Lower bounds on the parameters for the fit.

    upper optional, list of length num_params

      Upper bounds on the parameters for the fit.

    sigma optional, float or array_like

      The uncertainty in the dependent data, see the documentation of `scipy.optimize.curve_fit`.

    maxfev optional, int

      The maximum number of function evaluations (per value of `N`).

  Returns:
    rmse float

      The normalized mean squared error of the fit

    params array_like

      The model parameters in the form [[p11, …, p1n], [p21, …, p2n], …, [pN1, …, pNn]].

aaa(

  func: Callable[[...], complex] | TypeAliasForwardRef('ArrayLike'),
  z: ArrayLike,
  tol: float = 1e-13,
  max_iter: int = 100,

) → dict[str, Any]

  Computes a rational approximation of the function according to the AAA algorithm as explained in [AAA] . This implementation is a Python adaptation of the Chebfun version in that paper.

  Parameters:
    func callable or np.ndarray

      The function to be approximated

    z np.ndarray

      The sampling points on which to perform the rational approximation. Even though linearly spaced sample points will yield good approximations, logarithmically spaced points will usually give better exponent approximations.

    tol float, optional

      Relative tolerance of the approximation

    max_iter int, optional

      Maximum number of support points ~2*n where n is the number of bath exponents

  Returns:
    A dictionary containing:
      “function”callable

        Rational approximation of the function

      “poles”np.ndarray

        Poles of the approximant function

      “residues”np.ndarray

        Residues of the approximant function

      “zeros”np.ndarray

        Zeros of the approximant function

      “errors”np.ndarray

        Error by iteration

      “rmse”float

        Normalized root mean squared error from the fit

      “support points”np.ndarray

        The values used as the support points for the approximation

      “indices”np.ndarray

        The indices of the support point values

      “indices ordered”np.ndarray

        The indices of the support point values, sorted by importance

prony_methods(

  method: Literal['prony', 'esprit'],
  signal: ArrayLike,
  n: int,

) → tuple[float, TypeAliasForwardRef('ArrayLike')]

  Estimate amplitudes and frequencies using prony methods. Based on the description in [ESPIRAvsESPRIT] and their matlab implementation.

  Parameters:
    method: str

      The method to obtain the roots of the prony polynomial can be prony, and Estimation of signal parameters via rotational invariant techniques (ESPRIT)

    signal: n.ndarray

      The input signal (1D complex array).

    n: int

      Desired number of modes to use as estimation (rank of the signal).

  Returns:
    rmse:

      Normalized mean squared error

    params:

      A list of tuples containing the amplitudes and phases of our approximation

espira1(

  signal: ArrayLike,
  n: int,
  tol: float = 1e-13,

) → tuple[float, TypeAliasForwardRef('ArrayLike')]

  Estimate amplitudes and frequencies using ESPIRA-I. Based on the description in [ESPIRAvsESPRIT] and their matlab implementation.

  Parameters:
    signal: np.ndarray

      The input signal (1D complex array).

    n: int

      Desired number of modes to use as estimation (rank of the signal).

    tol: float

      Tolerance used in the AAA algorithm. If it is not low enough, the desired number of exponents may not be reached, as AAA converges in less iterations

  Returns:
    rmse:

      Normalized mean squared error

    params:

      A list of tuples containing the amplitudes and phases of our approximation

espira2(

  signal: ArrayLike,
  n: int,
  tol: float = 1e-13,

) → tuple[float, TypeAliasForwardRef('ArrayLike')]

  Estimate amplitudes and frequencies using ESPIRA-II. Based on the description in [ESPIRAvsESPRIT] and their matlab implementation

  Parameters:
    signal: np.ndarray

      The input signal (1D complex array).

    n: int

      Desired number of modes to use as estimation (rank of the signal).

    tol: float

      Tolerance used in the AAA algorithm. If it is not low enough, the desired number of exponents may not be reached, as AAA converges in less iterations

  Returns:
    rmse:

      Normalized mean squared error

    params:

      A list of tuples containing the amplitudes and phases of our approximation

## File I/O Functions

file_data_read(filename, sep=None)

  Retrieves an array of data from the requested file.

  Parameters:
    filename str or pathlib.Path

      Name of file containing reqested data.

    sep str, optional

      Seperator used to store data.

  Returns:
    data array_like

      Data from selected file.

file_data_store(filename, data, numtype='complex', numformat='decimal', sep=',')

  Stores a matrix of data to a file to be read by an external program.

  Parameters:
    filename str or pathlib.Path

      Name of data file to be stored, including extension.

    data: array_like

      Data to be written to file.

    numtype str {‘complex, ‘real’}, default: ‘complex’

      Type of numerical data.

    numformat str {‘decimal’,’exp’}, default: ‘decimal’

      Format for written data.

    sep str, default: ‘,’

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

qload(filename)

  Loads data file from file `filename` in current directory.

  Parameters:
    filename str or pathlib.Path

      Name of data file to be loaded.

  Returns:
    qobject instance / array_like

      Object retrieved from requested file.

qsave(data, filename='qutip_data')

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

  Parameters:
    data instance/array_like

      Input Python object to be stored.

    filename str or pathlib.Path, default: “qutip_data”

      Name of output data file.

## IPython Notebook Tools

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

version_table(verbose=False)

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

  Parameters:
    verbose bool, default: False

      Add extra information about install location.

  Returns:
    version_table: str

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

## Miscellaneous

Command line output of information on QuTiP and dependencies.

about()

  About box for QuTiP. Gives version numbers for QuTiP, NumPy, SciPy, Cython, and MatPlotLib and information about installed QuTiP family packages.