# qspec package

## qspec.algebra module

### qspec.algebra

Created on 30.04.2020

@author: Patrick Mueller

Module including methods for calculating dipole coefficients.

`qspec.algebra.``a`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The A coefficient as an S-object or float.

`qspec.algebra.``a_dipole`(i, j_l, f_l, m_l, j_u, f_u, m_u, q, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - m_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the lower state

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - m_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the upper state.

    - q (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The polarisation component. Can be either -1, 0 or 1 for sigma-, pi or sigma+ light.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The q component of the spherical dipole matrix elements A_q(F_l, m_l, F_u, m_u) between two hyperfine Zeeman states of an electric transition with quantum numbers j_l and j_u. See [Brown et al., Phys. Rev. A 87, 032504 (2013)].

`qspec.algebra.``a_dipole_cart`(i, j_l, f_l, m_l, j_u, f_u, m_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - m_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the lower state

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - m_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `ndarray`

  Returns

    The cartesian reduced dipole vector.

`qspec.algebra.``a_m_tilda`(i, j_l, f_l, m_l, j_u, f_u, m_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - m_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the lower state

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - m_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the upper state

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The relative transition strengths between Zeeman substates normed as in tilda.

`qspec.algebra.``a_tilda`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The relative transition strengths normed as in tilda.

`qspec.algebra.``ab`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    (typing.Union[sympy.core.numbers.Integer, sympy.core.numbers.Float, sympy.core.numbers.Rational, sympy.core.add.Add, sympy.core.mul.Mul, float], typing.Union[sympy.core.numbers.Integer, sympy.core.numbers.Float, sympy.core.numbers.Rational, sympy.core.add.Add, sympy.core.mul.Mul, float])

  Returns

    The A and B coefficients as S-objects or floats.

`qspec.algebra.``abc`(i, j_l, f_l, j_u, f1_u, f2_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f1_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The first total angular momentum quantum number F of the upper state. This is used for A and B.

    - f2_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The second total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    (typing.Union[sympy.core.numbers.Integer, sympy.core.numbers.Float, sympy.core.numbers.Rational, sympy.core.add.Add, sympy.core.mul.Mul, float], typing.Union[sympy.core.numbers.Integer, sympy.core.numbers.Float, sympy.core.numbers.Rational, sympy.core.add.Add, sympy.core.mul.Mul, float], typing.Union[sympy.core.numbers.Integer, sympy.core.numbers.Float, sympy.core.numbers.Rational, sympy.core.add.Add, sympy.core.mul.Mul, float])

  Returns

    The A, B and C coefficient as S-objects.

`qspec.algebra.``b`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The B coefficient as an S-object or float.

`qspec.algebra.``c`(i, j_l, f_l, j_u, f1_u, f2_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f1_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The first total angular momentum quantum number F of the upper state.

    - f2_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The second total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The C coefficient as an S-object.

`qspec.algebra.``c_dipole`(i, j_i, f_i, m_i, j_u, f_u, j_f, f_f, m_f, theta_l, scatter_pol, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the initial lower state.

    - f_i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the initial lower state.

    - m_i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the initial lower state

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the intermediate upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the intermediate upper state.

    - j_f (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the final lower state.

    - f_f (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the final lower state.

    - m_f (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The z-projection quantum number m of the total angular moment of the final lower state.

    - theta_l (`Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `int`, `float`, `complex`]) – The angle between the electric field of the linear laser polarisation and the direction of detection.

    - scatter_pol (`str`) – The label for the two orthogonal polarizations of the scattered light. Can be either ‘x’ or anything else.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The transition dipole element C_{i->f}^{F’} as defined in [Brown et al., Phys. Rev. A 87, 032504 (2013)].

`qspec.algebra.``cast_sympy`(as_sympy, *args, dtype=<class 'float'>)
  Parameters

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

    - args (`Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `int`, `float`, `complex`]) – sympy_like arguments.

    - dtype (`type`) – The type to use if as_sympy is False.

  Returns

    The specified arguments as sympy types if ‘as_sympy’ is True and else as floats.

`qspec.algebra.``clebsch_gordan`(j_1, j_2, j_3, m_1, m_2, m_3, as_sympy=False)
  \[\langle J_1, m_1, J_2, m_2\, |\, J_3, m_3\rangle\]
  Parameters

    - j_1 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – J1.

    - j_2 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – J2.

    - j_3 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The coupled J3 <- J1 + J2.

    - m_1 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – m1.

    - m_2 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – m2.

    - m_3 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The coupled m3 <- m1 + m2.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The Clebsch-Gordan coefficient.

`qspec.algebra.``f_0`(i, j_l, f_l, j_u, f_u, theta_l, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - theta_l (`Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `int`, `float`, `complex`]) – The angle between the electric field of the linear laser polarisation and the direction of detection.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The value of the f_0 function at the specified position. See [Brown et al., Phys. Rev. A 87, 032504 (2013)].

`qspec.algebra.``g_0`(i, j_l, f_l, j_u, f1_u, f2_u, theta_l, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - f1_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The first total angular momentum quantum number F of the upper state.

    - f2_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The second total angular momentum quantum number F of the upper state.

    - theta_l (`Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `int`, `float`, `complex`]) – The angle between the electric field of the linear laser polarisation and the direction of detection.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Return type

    `Union`[`Integer`, `Float`, `Rational`, `Add`, `Mul`, `float`]

  Returns

    The value of the g_0 function at the specified position. See [Brown et al., Phys. Rev. A 87, 032504 (2013)].

`qspec.algebra.``reduced_f`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The relative hyperfine transition strengths.

`qspec.algebra.``reduced_f_root`(i, j_l, f_l, j_u, f_u, as_sympy=False)
  Parameters

    - i (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The nuclear spin quantum number I.

    - j_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the lower state.

    - f_l (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the lower state.

    - j_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The electronic total angular momentum quantum number J of the upper state.

    - f_u (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The total angular momentum quantum number F of the upper state.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The square root of the relative hyperfine transition strengths.

`qspec.algebra.``wigner_3j`(j_1, j_2, j_3, m_1, m_2, m_3, as_sympy=False)
  \[\begin{split}\begin{pmatrix} J_1 & J_2 & J_3 \\ m_1 & m_2 & m_3 \end{pmatrix}\end{split}\]
  Parameters

    - j_1 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – J1.

    - j_2 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – J2.

    - j_3 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The coupled J3 <- J1 + J2.

    - m_1 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – m1.

    - m_2 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – m2.

    - m_3 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – The coupled m3 <- m1 + m2.

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The wigner-3j symbol.

`qspec.algebra.``wigner_6j`(j_1, j_2, j_3, j_4, j_5, j_6, as_sympy=False)
  \[\begin{split}\begin{Bmatrix} J_1 & J_2 & J_3 \\ J_4 & J_5 & J_6 \end{Bmatrix}\end{split}\]
  Parameters

    - j_1 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_1\).

    - j_2 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_2\).

    - j_3 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_3\).

    - j_4 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_4\).

    - j_5 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_5\).

    - j_6 (`Union`[`Integer`, `Float`, `Rational`, `int`, `float`]) – \(J_6\).

    - as_sympy (`bool`) – Whether to return the result as a sympy type.

  Returns

    The wigner-6j symbol.

## qspec.analyze module

### qspec.analyze

Created on 07.05.2020

@author: Patrick Mueller

Module for analyzing/evaluating/fitting data.

Linear regression algorithms:

  - york(); [York et al., Am. J. Phys. 72, 367 (2004)]

  - linear_monte_carlo(); based on [Gebert et al., Phys. Rev. Lett. 115, 053003 (2015), Suppl.]

  - linear_monte_carlo_nd(); based on [Gebert et al., Phys. Rev. Lett. 115, 053003 (2015), Suppl.]

Curve fitting methods:

  - curve_fit(); Reimplements the scipy.optimize.curve_fit method to allow fixing parameters and having parameter-dependent y-uncertainties.

  - odr_fit(); Encapsulates the scipy.odr.odr method to accept inputs similarly to curve_fit().

Classes:

  - King; Creates a King plot with isotope shifts or nuclear charge radii.

LICENSE NOTES:

  The method curve_fit is a modified version of scipy.optimize.curve_fit. Therefore, it is licensed under the ‘BSD 3-Clause “New” or “Revised” License’ provided with scipy.

class `qspec.analyze.``King`(a, m, x_abs=None, subtract_electrons=0.0, element_label=None)

  Bases: `object`

  `fit`(a, a_ref, x=None, y=None, xy=None, func=<function york>, alpha=0, find_alpha=False, show=True, **kwargs)
    Parameters

      - a (`Union`[`ndarray`, `Iterable`]) – An Iterable of the mass numbers of the used isotopes.

      - a_ref (`Union`[`ndarray`, `Iterable`]) – An Iterable of the mass numbers of the used reference isotopes.

      - x (`Union`[`ndarray`, `Iterable`, `None`]) – The x-values and their uncertainties of the King-fit to be performed. If ‘mode’ is “radii”, this must contain the differences of mean square nuclear charge radii or the Lambda-factor. ‘x’ must have shape (len(a), 2). Units: (fm ** 2) or (MHz).

      - y (`Union`[`ndarray`, `Iterable`, `None`]) – The isotope shifts and their uncertainties of the King-fit to be performed. ‘y’ must have shape (len(a), 2). If None, ‘y’ is tried to be inherited from ‘self.f’. Units: (MHz).

      - xy (`Optional`[`Iterable`[`int`]]) – A 2-tuple of indices (ix, iy) which select the axes to use for the King-fit from ‘King.x_abs’ if x or y is not specified. The default value is (0, 1), fitting the second against the first axis.

      - func (`Callable`) – The fitting routine.

      - alpha (`Union`[`int`, `float`]) – An x-axis offset to reduce the correlation coefficient between the y-intercept and the slope. Unit: (u fm ** 2) or (u MHz).

      - find_alpha (`bool`) – Whether to search for the best ‘alpha’. Uses the given ‘alpha’ as a starting point. May not give the desired result if ‘alpha’ was initialized to far from its optimal value.

      - show (`bool`) – Whether to plot the fit result.

      - kwargs – Additional keyword arguments are passed to ‘self.plot’.

    Returns

      A list of results as defined by the routine ‘linear_alpha’: a, b, sigma_a, sigma_b, corr_ab, alpha. The best y-intercept and slope, their respective 1-sigma uncertainties, their correlation coefficient and the used alpha.

  `fit_nd`(a, a_ref, x=None, axis=0, show=True, **kwargs)
    Parameters

      - a (`Union`[`ndarray`, `Iterable`]) – An Iterable of the mass numbers of the used isotopes.

      - a_ref (`Union`[`ndarray`, `Iterable`]) – An Iterable of the mass numbers of the used reference isotopes.

      - x (`Union`[`ndarray`, `Iterable`, `None`]) – The x data. ‘x’ is an iterable of vectors with uncertainties with arbitrary but fixed dimension n_vec. For a set of n_data data points, the shape of x must be (n_data, n_vec, 2).

      - axis (`int`) – The axis to use for the parametrization. For example, a King plot with the isotope shifts of two transitions [‘D1’, ‘D2’], yields the slope F_D2 / F_D1 if ‘axis’ == 0.

      - show (`bool`) – Whether to plot the fit result.

      - kwargs – Additional keyword arguments are passed to ‘self.plot_nd’.

    Returns

      A list of results as defined by the routine ‘linear_monte_carlo_nd’: A tuple (a, b, sigma_a, sigma_b, corr_ab) of arrays. The best y-intercepts and slopes, their respective 1-sigma uncertainties and their correlation matrix. Additionally, a second tuple with the accepted points, offsets, slopes and a mask for the accepted points is returned if full_output == True.

  `get_popt`()
    Return type

      (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

    Returns

      The y-intercept and slope of the performed fit and their correlation, if alpha was zero (Only changes the y-intercept). This returns the mass- and field-shift factors K and F if the x-axis are radii and the y-intercept Ky - Fy/Fx * Kx and field-shift ratio Fy/Fx if the x-axis are isotope shifts.

  `get_popt_nd`()
    Return type

      (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

    Returns

      The slopes and y-intercepts of the performed fit. This returns the mass- and field-shift factors K and F if the x-axis are radii and the y-intercept Ky - Fy/Fx * Kx and field-shift ratio Fy/Fx if the x-axis are isotope shifts. The returned arrays k and f have shape (n, 2) were n is number of dimensions of the King-fit.

  `get_unmodified_input_x_nd`()
    Return type

      `Optional`[`ndarray`]

    Returns

      The unmodified x values improved by the ‘fit_nd’.

  `get_unmodified_x`(a, a_ref, y, results=None, show=False, **kwargs)
    Parameters

      - a (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to the isotopes of the given ‘y’ values.

      - a_ref (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to reference isotopes of the given ‘y’ values.

      - y (`Union`[`ndarray`, `Iterable`]) – The unmodified y values of the given mass numbers. Must have shape (len(a), 2).

      - results (`Optional`[`tuple`]) – The results of a King plot. Must be a tuple of the shape (a, b, sigma_a, sigma_b, corr_ab, alpha), compare the module-level method ‘linear_alpha’. If None, the results are derived from ‘self.results’.

      - show (`bool`) – Whether to draw the King plot with the specified values.

      - kwargs – Additional keyword arguments are passed to ‘self.plot’.

    Return type

      `Optional`[`ndarray`]

    Returns

      The unmodified x values calculated with the fit results and the given ‘y’ values.

  `get_unmodified_x_nd`(a, a_ref, y, axis)
    Parameters

      - a (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to the isotopes of the given ‘y’ values.

      - a_ref (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to reference isotopes of the given ‘y’ values.

      - y (`Union`[`ndarray`, `Iterable`]) – The unmodified y values of the given mass numbers. Must have shape (len(a), 2).

      - axis (`int`) – The axis of the input values.

    Return type

      `Optional`[`ndarray`]

    Returns

      The unmodified values improved by ‘fit_nd’.

  `get_unmodified_y`(a, a_ref, x, results=None)
    Parameters

      - a (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to the isotopes of the given ‘x’ values.

      - a_ref (`Union`[`ndarray`, `Iterable`]) – An Iterable of mass numbers corresponding to reference isotopes of the given ‘x’ values.

      - x (`Union`[`ndarray`, `Iterable`]) – The unmodified x values of the given mass numbers. Must have shape (len(a), 2).

      - results (`Optional`[`tuple`]) – The results of a King plot. Must be a tuple of the shape (a, b, sigma_a, sigma_b, corr_ab, alpha), compare the module-level method ‘linear_alpha’. If None, the results are derived from ‘self.results’.

    Return type

      `Optional`[`ndarray`]

    Returns

      The unmodified y values calculated with the fit results and the given ‘x’ values.

  `plot`(mode='', sigma2d=True, show=True, add_xy=None, add_a=None)
    Parameters

      - mode (`str`) – The mode of the King-fit. If mode=’radii’, the :math:’x’-axis must contain the differences of mean square nuclear charge radii or the Lambda-factor. For every other value, the :math:’x’-axis is assumed to be an isotope shift such that the slope corresponds to a field-shift ratio :math:’F(y_i) / F(x)’.

      - sigma2d (`bool`) – Whether to draw the actual two-dimensional uncertainty bounds or the classical errorbars.

      - show (`bool`) – Whether to show the plot.

      - add_xy (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Additional :math:’x’ and :math:’y’ data to plot. Must have shape (:, 4).

      - add_a (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Additional mass numbers for the additional data- Must have shape (:, 2). The reference is the second column.

    Returns

      None. Generates a King-Plot based on the modified axes ‘self.x_mod’ and ‘self.y_mod’ as well as the fit results ‘self.results’.

  `plot_nd`(axis=0, mode='', sigma2d=True)
    Parameters

      - axis (`int`) – The axis which is used as the x-axis throughout the plots.

      - mode (`str`) – The mode of the King-plot. If mode=’radii’, the :math:’x’-axis must contain the differences of mean square nuclear charge radii or the Lambda-factor. For every other value, the :math:’x’-axis is assumed to be an isotope shift such that the slope corresponds to a field-shift ratio :math:’F(y_i) / F(x)’.

      - sigma2d (`bool`) – Whether to draw the actual two-dimensional uncertainty bounds or the classical errorbars.

    Returns

      None. Generates a King-Plot based on the modified axes ‘self.x_mod_nd’ and ‘self.y_mod_nd’ as well as the fit results ‘self.results_nd’.

`qspec.analyze.``curve_fit`(f, x, y, p0=None, p0_fixed=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(- inf, inf), method=None, jac=None, full_output=False, report=False, **kwargs)
  Parameters

    - f (`Callable`) – The model function to fit to the data.

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`, `object`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The y data.

    - p0 (`Union`[`ndarray`, `Iterable`, `None`]) – A numpy array or an Iterable of the initial guesses for the parameters. Must have at least the same length as the minimum number of parameters required by the function ‘f’. If ‘p0’ is None, 1 is taken as an initial guess for all non-keyword parameters.

    - p0_fixed (`Union`[`ndarray`, `Iterable`, `None`]) – A numpy array or an Iterable of bool values specifying, whether to fix a parameter. Must have the same length as p0.

    - sigma (`Union`[`ndarray`, `Iterable`, `Callable`, `None`]) – The 1-sigma uncertainty of the y data. This can also be a function g such that ‘g(x, y, f(x, *params), *params) -> sigma’.

    - absolute_sigma (`bool`) – See scipy.optimize.curve_fit.

    - check_finite (`bool`) – See scipy.optimize.curve_fit.

    - bounds ((<class 'numpy.ndarray'>, <class 'numpy.ndarray'>)) – See scipy.optimize.curve_fit.

    - method (`Optional`[`str`]) – See scipy.optimize.curve_fit.

    - jac (`Union`[`Callable`, `str`, `None`]) – See scipy.optimize.curve_fit. Must not be callable if ‘sigma’ is callable.

    - full_output (`bool`) – See scipy.optimize.curve_fit.

    - report (`bool`) – Whether to print the result of the fit.

    - kwargs – See scipy.optimize.curve_fit.

  Returns

    popt, pcov. The optimal parameters and their covariance matrix. Additional output if full_output is True. See scipy.optimize.curve_fit.

`qspec.analyze.``draw_sigma2d`(x, y, sigma_x, sigma_y, corr, n=1, **kwargs)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data.

    - sigma_x (`Union`[`ndarray`, `Iterable`]) – The 1-sigma uncertainties of the x data.

    - sigma_y (`Union`[`ndarray`, `Iterable`]) – The 1-sigma uncertainties of the y data.

    - corr (`Union`[`ndarray`, `Iterable`]) – The correlation coefficients between the x and y data.

    - n (`int`) – The maximum sigma region to draw

    - kwargs – Additional keyword arguments are passed to plt.plot(). Use key ‘fmt’ to specify the third argument of plt.plot().

  Returns

    None. Draws the sigma-bounds of the given data points (x, y) until the n-sigma region.

`qspec.analyze.``draw_straight_unc_area`(x, y, sigma_a, sigma_b, corr_ab, **kwargs)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x values.

    - y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The y values.

    - sigma_a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the y-intercept.

    - sigma_b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the slope.

    - corr_ab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The correlation coefficient between the slope and y-intercept.

    - kwargs – The keyword arguments for the fill_between function.

  Returns

    The standard deviation of a straight line where the x values do not have uncertainties.

`qspec.analyze.``ellipse2d`(x, y, scale_x, scale_y, phi, corr)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x-component of the position of the ellipse.

    - y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The y-component of the position of the ellipse.

    - scale_x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The amplitude of the x-component.

    - scale_y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The amplitude of the y-component.

    - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the vector to the point on the ellipse and the x-axis.

    - corr (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The correlation coefficient between the x and y data.

  Return type

    (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

  Returns

    A point on an ellipse in 2d-space with amplitudes ‘x’, ‘y’ and correlation ‘corr’ between x- and y-component.

`qspec.analyze.``linear_alpha`(x, y, sigma_x=None, sigma_y=None, corr=None, func=<function york>, alpha=0, find_alpha=True, report=True, show=False, **kwargs)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The 1-sigma uncertainty of the x data.

    - sigma_y (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The 1-sigma uncertainty of the y data.

    - corr (`Union`[`ndarray`, `Iterable`, `None`]) – The correlation coefficients between the x and y data.

    - func (`Callable`) – The fitting routine.

    - alpha (`Union`[`int`, `float`]) – An x-axis offset to reduce the correlation coefficient between the y-intercept and the slope.

    - find_alpha (`bool`) – Whether to search for the best ‘alpha’. Uses the given ‘alpha’ as a starting point. May not give the desired result if ‘alpha’ was initialized to far from its optimal value.

    - report (`bool`) – Whether to print the result of the fit.

    - show (`bool`) – Whether to plot the fit result.

    - kwargs – Additional keyword arguments are passed to the fitting routine.

  Returns

    a, b, sigma_a, sigma_b, corr_ab, alpha. The best y-intercept and slope, their respective 1-sigma uncertainties, their correlation coefficient and the used alpha.

`qspec.analyze.``linear_monte_carlo`(x, y, sigma_x=None, sigma_y=None, corr=None, n=1000000, report=True, show=False)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainties of the x data.

    - sigma_y (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainties of the y data.

    - corr (`Union`[`ndarray`, `Iterable`, `None`]) – The correlation coefficients between the x and y data.

    - n (`int`) – The number of samples generated for each data point.

    - report (`bool`) – Whether to print the result of the fit.

    - show (`bool`) – Whether to plot the fit result.

  Returns

    a, b, sigma_a, sigma_b, corr_ab. The best y-intercept and slope, their respective 1-sigma uncertainties and their correlation coefficient.

`qspec.analyze.``linear_monte_carlo_nd`(x, cov=None, axis=None, n=1000000, full_output=False, report=True, show=False)

  A Monte-Carlo fitter that finds a straight line in n-dimensional space.

  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The x data. ‘x’ is an iterable of vectors with arbitrary but fixed dimension.

    - cov (`Union`[`ndarray`, `Iterable`, `None`]) – The covariance matrices of the x data vectors. Must have shape (x.shape[0], x.shape[1], x.shape[1]).

    - axis (`Optional`[`int`]) – The axis to use for the parametrization. If None, the directional vector is normalized.

    - n (`int`) – The number of samples generated for each data point.

    - full_output (`bool`) – Whether to also return the generated points ‘p’ and a mask for the ‘accepted’ points. The accepted points are p[accepted]. p has shape (n, x.shape).

    - report (`bool`) – Whether to print the result of the fit.

    - show (`bool`) – Whether to plot the fit result.

  Returns

    A list of results as defined by the routine ‘linear_monte_carlo_nd’: A tuple (a, b, sigma_a, sigma_b, corr_ab) of arrays. The best y-intercepts and slopes, their respective 1-sigma uncertainties and their correlation matrix. The y-intercepts and slopes are defined through ‘axis’ by a(x[axis] == 0) and b(dx[i != axis] / dx[axis]), respectively. Additionally, a second tuple with the accepted points, offsets, slopes and a mask for the accepted points is returned if full_output == True.

`qspec.analyze.``odr_fit`(f, x, y, sigma_x=None, sigma_y=None, p0=None, p0_d=None, p0_fixed=None, report=False, **kwargs)
  Parameters

    - f (`Callable`) – The model function to fit to the data.

    - x (`Union`[`ndarray`, `Iterable`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainty of the x data.

    - sigma_y (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainty of the y data.

    - p0 (`Union`[`ndarray`, `Iterable`, `None`]) – A numpy array or an Iterable of the initial guesses for the parameters. Must have at least the same length as the minimum number of parameters required by the function ‘f’. If ‘p0’ is None, 1 is taken as an initial guess for all non-keyword parameters.

    - p0_d (`Union`[`ndarray`, `Iterable`, `None`]) – A numpy array or an Iterable of the uncertainties of the initial guesses for the parameters. Must have the same length as p0.

    - p0_fixed (`Union`[`ndarray`, `Iterable`, `None`]) – A numpy array or an Iterable of bool values specifying, whether to fix a parameter. Must have the same length as p0.

    - report (`bool`) – Whether to print the result of the fit.

    - kwargs – Keyword arguments passed to odr.ODR.

  Return type

    (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

  Returns

    popt, pcov. The optimal parameters and their covariance matrix.

`qspec.analyze.``straight`(x, a, b)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x values.

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The y-intercept.

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The slope.

  Return type

    `ndarray`

  Returns

    The y values resulting from the ‘x’ values via the given linear relation.

`qspec.analyze.``straight_slope`(p_0, p_1, axis=- 1)
  Parameters

    - p_0 (`Union`[`ndarray`, `Iterable`]) – The first point(s).

    - p_1 (`Union`[`ndarray`, `Iterable`]) – The second point(s).

    - axis – The axis along which the vector components are aligned.

  Return type

    `ndarray`

  Returns

    The parametrization of a straight line in n dimensions.

`qspec.analyze.``straight_std`(x, sigma_a, sigma_b, corr_ab)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x values.

    - sigma_a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the y-intercept.

    - sigma_b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the slope.

    - corr_ab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The correlation coefficient between the slope and y-intercept.

  Return type

    `ndarray`

  Returns

    The standard deviation of a straight line where the x values do not have uncertainties.

`qspec.analyze.``straight_x_std`(x, b, sigma_x, sigma_a, sigma_b, corr_ab)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x values.

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The slope.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the x values.

    - sigma_a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the y-intercept.

    - sigma_b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the slope.

    - corr_ab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The correlation coefficient between the slope and y-intercept.

  Return type

    `ndarray`

  Returns

    The standard deviation of a straight line where all input values have uncertainties.

`qspec.analyze.``weight`(sigma)
  Parameters

    sigma – The 1-sigma uncertainty.

  Returns

    The weight corresponding to the 1-sigma uncertainty ‘sigma’

`qspec.analyze.``york`(x, y, sigma_x=None, sigma_y=None, corr=None, iter_max=200, report=False, show=False)

  A linear regression algorithm to find the best straight line, given normally distributed errors for x and y and correlation coefficients between errors in x and y. The algorithm is described in [‘Unified equations for the slope, intercept, and standard errors of the best straight line’, York et al., American Journal of Physics 72, 367 (2004)]. See the comments to compare the individual steps.

  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The x data.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainties of the x data.

    - sigma_y (`Union`[`ndarray`, `Iterable`, `None`]) – The 1-sigma uncertainties of the y data.

    - corr (`Union`[`ndarray`, `Iterable`, `None`]) – The correlation coefficients between the x and y data.

    - iter_max (`int`) – The maximum number of iterations to find the best slope.

    - report (`bool`) – Whether to print the result of the fit.

    - show (`bool`) – Whether to plot the fit result.

  Returns

    a, b, sigma_a, sigma_b, corr_ab. The best y-intercept and slope, their respective 1-sigma uncertainties and their correlation coefficient.

## qspec.models module

### qspec.models

Created on 14.03.2022

@author: Patrick Mueller

Module for constructing lineshape models.

class `qspec.models.``Amplifier`(order=None)

  Bases: `qspec.models._base.Model`

  A polynomial of order ‘order’.

  property `dx`
  `evaluate`(x, *args, **kwargs)
  `max`()
  `min`()

class `qspec.models.``Convolved`(model_0, model_1)

  Bases: `qspec.models._base.Model`

  property `dx`
  `evaluate`(x, *args, **kwargs)
  `gen_x_int`(*args)
  `intervals`()
  `max`()
  `min`()
  `set_val`(i, val, force=False)

class `qspec.models.``Custom`(model=None, parameters=None)

  Bases: `qspec.models._base.Model`

  `evaluate`(x, *args, **kwargs)

class `qspec.models.``Empty`

  Bases: `qspec.models._base.Model`

  An empty model, returning zeros with the same shape as x.

  `evaluate`(x, *args, **kwargs)

class `qspec.models.``Gauss`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()
  `max`()
  `min`()

class `qspec.models.``GaussChi2`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()
  `max`()
  `min`()

class `qspec.models.``GaussChi2Convolved`(model)

  Bases: `qspec.models._convolved.Convolved`

  `evaluate`(x, *args, **kwargs)

class `qspec.models.``GaussConvolved`(model)

  Bases: `qspec.models._convolved.Convolved`

  `evaluate`(x, *args, **kwargs)

class `qspec.models.``Hyperfine`(model, i, j_l, j_u, name)

  Bases: `qspec.models._splitter.Splitter`

  `evaluate`(x, *args, **kwargs)
  `intervals`()
  `max`()
  `min`()
  `racah`()

class `qspec.models.``HyperfineMixed`(model, i, j_l, j_u, name, config)

  Bases: `qspec.models._splitter.Splitter`

  Hyperfine-mixing model based on https://doi.org/10.1103/PhysRevA.55.2728 [1].

  `evaluate`(x, *args, **kwargs)
  `intervals`()
  `max`()
  `min`()
  `racah`()
  `x0`(*args)

class `qspec.models.``HyperfineQI`(model, i, j_l, j_u, name, qi_path=None)

  Bases: `qspec.models._splitter.Splitter`

  `evaluate`(x, *args, **kwargs)
  `intervals`()
  `max`()
  `min`()
  `racah`()

class `qspec.models.``Linked`(models)

  Bases: `qspec.models._base.Listed`

  `evaluate`(x, *args, **kwargs)
  `set_fix`(i, fix, force=False)
  `set_link`(i, link, force=False)

class `qspec.models.``Listed`(models, labels=None)

  Bases: `qspec.models._base.Model`

  `inherit_fixes`(force=False)
  `inherit_links`(force=False)
  `inherit_vals`(force=False)
  `set_fix`(i, fix, force=False)
  `set_link`(i, link, force=False)
  `set_val`(i, val, force=False)

class `qspec.models.``Lorentz`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()
  `max`()
  `min`()

class `qspec.models.``LorentzConvolved`(model)

  Bases: `qspec.models._convolved.Convolved`

  `evaluate`(x, *args, **kwargs)

class `qspec.models.``LorentzQI`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `evaluate_qi`(x, x_qi, *args, **kwargs)
  `fwhm`()
  `max`()
  `min`()

class `qspec.models.``Model`(model=None)

  Bases: `object`

  Base class for all models.

  property `description`
  property `dx`
  property `error`
  `evaluate`(x, *args, **kwargs)
  `fit_prepare`()
  `get_pars`()
  `intervals`()
  `max`()
  `min`()
  property `model`
  `set_fix`(i, fix, force=False)
  `set_fixes`(fixes, force=False)
  `set_link`(i, link, force=False)
  `set_links`(links, force=False)
  `set_pars`(pars, force=False)
  `set_val`(i, val, force=False)
  `set_vals`(vals, force=False)
  property `size`
    Returns

      The number of parameters required by the model.

  `update`()
  `update_args`(args)
  `x`()

class `qspec.models.``NPeak`(model, n_peaks=1)

  Bases: `qspec.models._base.Model`

  Evaluates the given ‘model’ at the positions xi with scalings pi where i < ‘n_peaks’.

  `evaluate`(x, *args, **kwargs)
  `intervals`()
  `max`()
  `min`()

class `qspec.models.``Offset`(model=None, x_cuts=None, offsets=None)

  Bases: `qspec.models._base.Model`

  Cuts the x-axis and adds y-axis offsets to every segment.

  `evaluate`(x, *args, **kwargs)
  `gen_offset_map`()
  `gen_offset_masks`(x)
  `guess_offset`(x, y)
  `set_x_cuts`(x_cuts)

class `qspec.models.``Spectrum`

  Bases: `qspec.models._base.Model`

  property `dx`
  `evaluate`(x, *args, **kwargs)
  `fwhm`()
  `max`()
  `min`()

class `qspec.models.``Splitter`(model, i, j_l, j_u, name)

  Bases: `qspec.models._base.Model`

  `racah`()

class `qspec.models.``SplitterSummed`(splitter_models)

  Bases: `qspec.models._base.Summed`

  `racah`()

class `qspec.models.``Summed`(models, labels=None)

  Bases: `qspec.models._base.Listed`

  property `dx`
  `evaluate`(x, *args, **kwargs)
  `intervals`()
  `max`()
  `min`()

class `qspec.models.``Voigt`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()

class `qspec.models.``VoigtAsy`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()

class `qspec.models.``VoigtCEC`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()

class `qspec.models.``VoigtDerivative`

  Bases: `qspec.models._spectrum.Spectrum`

  `evaluate`(x, *args, **kwargs)
  `fwhm`()

class `qspec.models.``YPars`(model)

  Bases: `qspec.models._base.Model`

  `evaluate`(x, *args, **kwargs)

`qspec.models.``find_model`(model, sub_model)
  Parameters

    - model (`Model`) – The model to search.

    - sub_model (`Union`[`Model`, `type`]) – The sub model to find.

  Returns

    The first sub model of type or with the same type as ‘sub_model’. If ‘model’ already hast the same type as ‘sub_model’, ‘model’ will be returned. Returns None if ‘model’ has no sub model ‘sub_model’.

`qspec.models.``find_models`(model, sub_model, model_list=None)
  Parameters

    - model (`Model`) – The model to search.

    - sub_model (`Union`[`Model`, `type`]) – The sub model to find.

    - model_list (`Optional`[`Iterable`]) – The initial list of models to return.

  Returns

    This function returns a list of the first models of every branch in model.

`qspec.models.``fit`(model, x, y, sigma_x=None, sigma_y=None, report=False, routine=None, guess_offset=False, mc_sigma=0, **kwargs)
  Parameters

    - model (`Model`) – The model to fit.

    - x (`Union`[`ndarray`, `Iterable`]) – The x data. Can be any object accepted by the model. If model is a Linked model, x should be a list of objects compatible with the linked models.

    - y (`Union`[`ndarray`, `Iterable`]) – The y data. This has to be a 1-d array or a list of 1-d arrays if model is a Linked model.

    - sigma_x (`Union`[`ndarray`, `Iterable`, `None`]) – The uncertainties of the x-values. This is only compatible with Monte-Carlo sampling and the odr_fit routine. If sigma_x is not None, no routine is specified and mc_sigma == 0, the routine is automatically set to odr_fit.

    - sigma_y (`Union`[`ndarray`, `Iterable`, `Callable`, `None`]) – The uncertainties of the y-values. This has to be a 1-d array or a list of 1-d arrays if model is a Linked model and have the same shape as ‘y’. If routine is ‘curve_fit’, sigma may be a function g such that ‘g(x, y, model(x, *params), *params) -> sigma’. g should accept the same x as the model and y and model(x, *params) as 1-d arrays.

    - report (`bool`) – Whether to print the fit results.

    - routine (`Union`[`Callable`, `str`, `None`]) – The routine to use for fitting. Currently supported are {curve_fit, odr_fit}. If None, curve_fit is used. See ‘sigma_x’ for one exception.

    - guess_offset (`bool`) – Guess initial parameters for Offset models. Currently, this is not working if x is not a 1d-array.

    - mc_sigma (`int`) – The number of samples to generate from the data. If it is 0, no Monte-Carlo sampling will be done. This is not available with linked fitting.

    - kwargs – Additional kwargs to pass to the fit ‘routine’.

  Returns

    The optimized parameters their covariance matrix and a dictionary containing info about the fit.

  Raises

    (ValueError, TypeError) –

`qspec.models.``fwhm_voigt`(gamma, sigma)

`qspec.models.``fwhm_voigt_d`(gamma, gamma_d, sigma, sigma_d)

`qspec.models.``gen_model`(ijj, shape, qi=False, hf_mixing=False, n_peaks=1, offsets=None, x_cuts=None, convolve=None)

  Create a lineshape model to fit arbitrary atomic fluorescence spectra.

  Parameters

    - ijj – The three or an Iterable of three quantum numbers I, J_l and J_u. Must have the format [I, J_l, J_u] or [[I0, J0_l, J0_u], [I1, J1_l, J1_u], …].

    - shape (`Union`[`str`, `type`, `Spectrum`]) – A str representation of or a Spectrum type.

    - qi (`bool`) – Whether to use a quantum interference model. NOT IMPLEMENTED.

    - hf_mixing (`bool`) – Whether to use a hyperfine mixing model. NOT IMPLEMENTED.

    - n_peaks (`int`) – The number of “peaks per resonance”.

    - offsets (`Union`[`int`, `list`, `None`]) – The orders of the offset polynomials of the separate x-axis intervals. Must be a list or a single value. In the former case len(offsets) == len(x_cuts) + 1 must hold. If offsets is None, a single constant offset is assumed.

    - x_cuts (`Union`[`int`, `float`, `list`, `None`]) – The x values where to cut the x-axis. Must be a list or a single value. In the former case len(offsets) == len(x_cuts) + 1 must hold. If x_cuts is None, the x-axis will not be cut.

    - convolve (`Union`[`str`, `type`, `Spectrum`, `None`]) – A str representation of or a Convolved type.

  Returns

    The defined lineshape model.

`qspec.models.``gen_splitter_model`(qi=False, hf_mixing=False)

`qspec.models.``get_all_f`(i, j)

`qspec.models.``hf_coeff`(i, j, f)

  Return the tuple of hyperfine coefficients for A and B-factor for a given quantum state

`qspec.models.``hf_int`(i, j_l, j_u, transitions)

  Calculate relative line intensities

`qspec.models.``hf_shift`(hyper_l, hyper_u, coeff_l, coeff_u)
  Parameters

    - hyper_l – The hyperfine structure constants of the lower state (Al, Bl, Cl, …).

    - hyper_u – The hyperfine structure constants of the upper state (Au, Bu, Cu, …).

    - coeff_l – The coefficients of the lower state to be multiplied by the constants (coAl, coBl, coCl, …).

    - coeff_u – The coefficients of the lower state to be multiplied by the constants (coAu, coBu, coCu, …).

  Returns

    The hyperfine structure shift of an optical transition.

`qspec.models.``hf_trans`(i, j_l, j_u)

  Calculate all allowed hyperfine transitions and their hyperfine coefficients. Returns (f_l, f_u, coAl, coBl, coAu, coBu)

`qspec.models.``reduced_chi2`(model, x, y, sigma_y)

`qspec.models.``residuals`(model, x, y)

`qspec.models.``sigma_poisson`(x, y, y_model, *params)

## qspec.physics module

### qspec.physics

Created on 01.04.2020

@author: Patrick Mueller

Module for physical functions useful for CLS.

`qspec.physics.``a_hyper_mu`(i, j, mu, b)
  Parameters

    - i (`Union`[`int`, `float`]) – The nuclear spin quantum number I.

    - j (`Union`[`int`, `float`]) – The electronic total angular momentum quantum number J.

    - mu (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The magnetic moment of the nucleus in units of the nuclear magneton (mu_N).

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The B-field of the atomic electrons at the nucleus (T).

  Returns

    The hyperfine structure constant A (MHz).

`qspec.physics.``alpha_atom`(alpha, v)
  Parameters

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between a velocity- and a wave-vector in the laboratory frame (rad).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The angle between the velocity- and the wave-vector in the atoms rest frame (rad).

`qspec.physics.``beta`(v)
  Parameters

    v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The velocity v relative to light speed.

`qspec.physics.``boost`(x, v, axis=- 1)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The 4-vector x in the current rest frame (arb. units).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity 3-vector (m/s).

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The 4-vector x in the coordinate system moving with velocity v relative to the current rest frame ([x]).

  Raises

    ValueError – x and v must have 4 and 3 components along the specified axis, respectively. The shapes of x and v must be compatible.

`qspec.physics.``convolved_boltzmann_norm_pdf`(e, t, scale_e, e0=0)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – energy quantiles (eV).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

    - scale_e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the normal distribution (eV).

    - e0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mean energy of the normal distribution (eV).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density at the energy e, distributed according to a convolution of the boltzmann and a normal distribution (1/eV).

`qspec.physics.``convolved_thermal_norm_f_lin_pdf`(f, xi, sigma, col=True)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Frequency quantiles (arb. units).

    - xi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The proportionality constant between kinetic energy differences and frequency differences ([f]).

    - sigma (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the underlying normal distribution in frequency units ([f]).

    - col – Col/Acol alignment of the laser relative to the atom beam.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density at the frequency ‘f’ in the atoms rest frame, related to differences in kinetic energy via the proportionality constant ‘xi’. The kinetic energies are distributed according to a convolution of the boltzmann and a normal distribution (1/[f]).

`qspec.physics.``convolved_thermal_norm_f_pdf`(f, f_lab, alpha, m, t, scale_e, e0=0, relativistic=True)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Frequency quantiles (arb. units).

    - f_lab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Laser frequency in the laboratory frame ([f]).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Angle between the laser and the atoms velocity direction (rad).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the ensembles bodies (amu).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

    - scale_e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the normal distribution (eV).

    - e0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mean energy of the normal distribution (eV).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density at the frequency ‘f’ in the atoms rest frame, related to the kinetic energy via the laser frequency ‘f_lab’ and the Doppler effect. The kinetic energies are distributed according to a convolution of the boltzmann and a normal distribution (1/MHz).

`qspec.physics.``convolved_thermal_norm_v_pdf`(v, m, t, scale_e, e0=0, relativistic=True)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – velocity quantiles. All values must have the same sign (m/s).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the ensembles bodies (amu).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

    - scale_e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The standard deviation of the normal distribution (eV).

    - e0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mean energy of the normal distribution (eV).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density at the velocity v, corresponding to the kinetic energy, distributed according to a convolution of the boltzmann and a normal distribution (s/m).

`qspec.physics.``delta_r2`(r, r_d, r_ref, r_ref_d, delta_r, delta_r_d, v2, v2_ref)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of an isotope.

    - r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius.

    - r_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of a reference isotope.

    - r_ref_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius of the reference isotope.

    - delta_r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The difference between the Barrett radius of the isotope and the reference isotope.

    - delta_r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the difference between the Barrett radius of the isotope and the reference isotope.

    - v2 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V2 factor of the isotope.

    - v2_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V2 factor of the reference isotope.

  Returns

    The difference of the mean square nuclear charge radius between two isotopes and its uncertainty.

`qspec.physics.``delta_r4`(r, r_d, r_ref, r_ref_d, delta_r, delta_r_d, v4, v4_ref)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of an isotope.

    - r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius.

    - r_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of a reference isotope.

    - r_ref_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius of the reference isotope.

    - delta_r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The difference between the Barrett radius of the isotope and the reference isotope.

    - delta_r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the difference between the Barrett radius of the isotope and the reference isotope.

    - v4 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V4 factor of the isotope.

    - v4_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V4 factor of the reference isotope.

  Returns

    The difference of the mean quartic nuclear charge radius between two isotopes and its uncertainty.

`qspec.physics.``delta_r6`(r, r_d, r_ref, r_ref_d, delta_r, delta_r_d, v6, v6_ref)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of an isotope.

    - r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius.

    - r_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Barrett radius of a reference isotope.

    - r_ref_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the Barrett radius of the reference isotope.

    - delta_r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The difference between the Barrett radius of the isotope and the reference isotope.

    - delta_r_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the difference between the Barrett radius of the isotope and the reference isotope.

    - v6 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V6 factor of the isotope.

    - v6_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The V6 factor of the reference isotope.

  Returns

    The difference of the mean sextic nuclear charge radius between two isotopes and its uncertainty.

`qspec.physics.``doppler`(f, v, alpha, return_frame='atom')
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light (arb. units).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - return_frame – The coordinate system in which the frequency is returned. Can be either ‘atom’ or ‘lab’.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the Doppler-shifted frequency in either the rest frame of the atom or the laboratory frame ([f]).

  Raises

    ValueError – rest_frame must be either ‘atom’ or ‘lab’.

`qspec.physics.``doppler_3d`(k, v, return_frame='atom', axis=- 1)
  Parameters

    - k (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The k-wave-3-vector of light (arb. units).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity 3-vector (m/s).

    - return_frame – The coordinate system in which the frequency is returned. Can be either ‘atom’ or ‘lab’.

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the Doppler-shifted k-wave-4-vector in either the rest frame of the atom or the laboratory frame ([k]).

  Raises

    ValueError – rest_frame must be either ‘atom’ or ‘lab’. The shapes of k and v must be compatible.

`qspec.physics.``doppler_d1`(f, v, alpha, return_frame='atom')
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light (arb. units).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - return_frame – The coordinate system in which the frequency is returned. Can be either ‘atom’ or ‘lab’.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the first derivative of the ‘doppler’ formula regarding ‘v’ ([f] s/m).

  Raises

    ValueError – rest_frame must be either ‘atom’ or ‘lab’.

`qspec.physics.``doppler_e_d1`(f, alpha, e, m, v0=0, return_frame='atom', relativistic=True)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light (arb. units).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Energy which is added to the kinetic energy of a body with velocity v0 (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - return_frame – The coordinate system in which the frequency is returned. Can be either ‘atom’ or ‘lab’.

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the first derivative of the ‘doppler’ formula regarding ‘e’ ([f]/eV).

  Raises

    ValueError – rest_frame must be either ‘atom’ or ‘lab’.

`qspec.physics.``doppler_el_d1`(f, alpha, u, q, m, v0=0.0, return_frame='atom', relativistic=True)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light (arb. units).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - u (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric potential difference added to the kinetic energy of a body with velocity v0 (V).

    - q (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The charge of a body (e).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - return_frame – The coordinate system in which the frequency is returned. Can be either ‘atom’ or ‘lab’.

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the first derivative of the ‘doppler’ formula regarding ‘u’ ([f]/V).

  Raises

    ValueError – rest_frame must be either ‘atom’ or ‘lab’.

`qspec.physics.``e_el`(u, q)
  Parameters

    - u (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric potential difference (V).

    - q (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The charge of a body (e).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The potential energy difference of a body with charge q inside an electric potential with voltage u (eV).

`qspec.physics.``e_kin`(v, m, relativistic=True)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The kinetic energy of a body with velocity v and mass m (eV).

`qspec.physics.``e_rest`(m)
  Parameters

    m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of a body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The resting energy of the body with mass m (eV).

`qspec.physics.``e_total`(v, m)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The total energy of a body with velocity v and mass m (eV).

`qspec.physics.``freq_to_inv_cm`(freq)
  Parameters

    freq (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency f of a transition (MHz)

  Returns

    The wavenumber k corresponding to the frequency freq (cm ** -1).

`qspec.physics.``freq_to_wavelength`(freq)
  Parameters

    freq (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency f of a transition (MHz)

  Returns

    The wavelength corresponding to the frequency freq (um).

`qspec.physics.``gamma`(v)
  Parameters

    v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The time-dilation/Lorentz factor corresponding to the velocity v.

`qspec.physics.``gamma_3d`(v, axis=- 1)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity 3-vector (m/s).

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The time-dilation/Lorentz factor corresponding to the velocity vector v.

  Raises

    ValueError – v must have 3 components along the specified axis.

`qspec.physics.``gamma_e`(e, m)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The total energy of a body, including the energy of the rest mass (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The time-dilation/Lorentz factor corresponding to the total energy e of a body with mass m.

`qspec.physics.``gamma_e_kin`(e, m)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The kinetic energy of a body (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The time-dilation/Lorentz factor corresponding to the kinetic energy e of a body with mass m.

`qspec.physics.``gaussian_beam_3d`(r, k, w0, r0=None, p0=None, axis=- 1)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The position 3-vector where to calculate the beam intensity (m).

    - k (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The k-wave-3-vector of light (rad / m).

    - w0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The beam waist (m).

    - r0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The position 3-vector of the beam waist. Is (0m, 0m, 0m) if r0 is not specified (m).

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The total power propagated by the gaussian beam. Is 1W if p0 is not specified (W).

    - axis (`int`) – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The intensity of a gaussian beam with k-wave-vector k at the position r - r0 (W/m**2 == µW/mm**2).

  Raises

    ValueError – r, k and r0 must have 3 components along the specified axis. The shapes of r, k, w0, r0 and p0 must be compatible.

`qspec.physics.``gaussian_doppler_3d`(r, k, w0, v, r0=None, axis=- 1)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The position 3-vector relative to ‘r0’ where to calculate the doppler-shifted wave number (m).

    - k (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The k-wave-3-vector of light (rad / m).

    - w0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The beam waist (m).

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity 3-vector (m/s).

    - r0 – The position 3-vector of the beam waist. Is (0m, 0m, 0m) if r0 is not specified (m).

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The length of the k-wave-3-vector in the atoms rest frame (rad / m).

  Raises

    ValueError – r, k, v and r0 must have 3 components along the specified axis. The shapes of r, k, w0, v and r0 must be compatible.

`qspec.physics.``get_f`(i, j)
  Parameters

    - i (`Union`[`int`, `float`]) – The nuclear spin quantum number I.

    - j (`Union`[`int`, `float`]) – The electronic total angular momentum quantum number J.

  Returns

    All possible f quantum numbers.

`qspec.physics.``get_m`(f)
  Parameters

    f (`Union`[`int`, `float`]) – The total angular momentum quantum number F (= J if I == 0).

  Returns

    All possible zeeman substates of the specified quantum number.

`qspec.physics.``gn_s` = -3.82608545

  Units

`qspec.physics.``hyper_zeeman`(i, s, ll, j, f, m, g_n, a_hyper, b_hyper, b, g_n_as_gyro=False, as_freq=True)
  Parameters

    - i (`float`) – The nuclear spin quantum number I.

    - s (`float`) – The electron spin quantum number S.

    - ll (`float`) – The electronic angular momentum quantum number L.

    - j (`float`) – The electronic total angular momentum quantum number J.

    - f (`float`) – The total angular momentum quantum number F.

    - m (`float`) – The B-field-axis component quantum number m of the total angular momentum.

    - g_n (`float`) – The nuclear g-factor or the gyromagnetic ratio if g_n_as_gyro == True.

    - a_hyper (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The magnetic dipole hyperfine constant A (eV or MHz).

    - b_hyper (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric quadrupole hyperfine constant B ([a]).

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The B-field (T).

    - g_n_as_gyro (`bool`) – Whether g_n is the nuclear g-factor or the gyromagnetic ratio.

    - as_freq (`bool`) – The shift can be returned in energy or frequency units.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The total energy shift of an atomic state due to the hyperfine splitting and the zeeman effect in energy or frequency units (eV or MHz).

`qspec.physics.``hyperfine`(i, j, f, a, b=None)
  Parameters

    - i (`float`) – The nuclear spin quantum number I.

    - j (`float`) – The electronic total angular momentum quantum number J.

    - f (`float`) – The total angular momentum quantum number F.

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The magnetic dipole hyperfine constant A (arb. units).

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The electric quadrupole hyperfine constant B ([a]).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The hyperfine shift of an atomic state (i, j, f) with hyperfine constants a and b ([a]).

`qspec.physics.``inv_cm_to_freq`(k)
  Parameters

    k (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The wavenumber k of a transition (cm ** -1)

  Returns

    The frequency corresponding to the wavenumber k (MHz).

`qspec.physics.``inv_cm_to_wavelength`(k)
  Parameters

    k (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The wavenumber k of a transition (cm ** -1)

  Returns

    The wavelength corresponding to the wavenumber k (um).

`qspec.physics.``inverse_doppler`(f_atom, f_lab, alpha, mode='raise-raise', return_mask=False)
  Parameters

    - f_lab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the laboratory frame (arb. units).

    - f_atom (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the atoms rest frame ([f_lab]).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - mode – The mode how to handle numpy.nans and ambiguous velocities. Available options are: * ‘raise-raise’: Raise an error if there are numpy.nans and if the velocity is ambiguous. * ‘raise-small’: Raise an error if there are numpy.nans and return the smaller velocity. * ‘raise-large’: Raise an error if there are numpy.nans and return the larger velocity. * ‘isnan-raise’: Ignore numpy.nans and raise an error if the velocity is ambiguous. * ‘isnan-small’: Ignore numpy.nans and return the smaller velocity. * ‘isnan-large’: Ignore numpy.nans and return the larger velocity.

    - return_mask – Whether the mask where the velocity is ambiguous is returned as a second argument.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the velocity required to shift f_lab to f_atom (m/s) and optionally the mask where the velocity is ambiguous.

`qspec.physics.``inverse_doppler_d1`(f_atom, f_lab, alpha, mode='raise-raise', return_mask=False)
  Parameters

    - f_lab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the laboratory frame (arb. units).

    - f_atom (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the atoms rest frame ([f_lab]).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the velocity- and the wave-vector in the laboratory frame (rad).

    - mode – The mode how to handle numpy.nans and ambiguous velocities. Available options are: * ‘raise-raise’: Raise an error if there are numpy.nans and if the velocity is ambiguous. * ‘raise-small’: Raise an error if there are numpy.nans and return the smaller velocity. * ‘raise-large’: Raise an error if there are numpy.nans and return the larger velocity. * ‘isnan-raise’: Ignore numpy.nans and raise an error if the velocity is ambiguous. * ‘isnan-small’: Ignore numpy.nans and return the smaller velocity. * ‘isnan-large’: Ignore numpy.nans and return the larger velocity.

    - return_mask – Whether the mask where the velocity is ambiguous is returned as a second argument.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    the first derivative of the ‘inverse_doppler’ formula regarding f_atom (m/(s MHz)).

`qspec.physics.``lambda_r`(r, r_d, r_ref, r_ref_d, delta_r, delta_r_d, v2, v2_ref, v4, v4_ref, v6, v6_ref, c2c1, c3c1)
  Parameters

    - r (`float`) – The Barrett radius of an isotope.

    - r_d (`float`) – The uncertainty of the Barrett radius.

    - r_ref (`float`) – The Barrett radius of a reference isotope.

    - r_ref_d (`float`) – The uncertainty of the Barrett radius of the reference isotope.

    - delta_r (`float`) – The difference between the Barrett radius of the isotope and the reference isotope.

    - delta_r_d (`float`) – The uncertainty of the difference between the Barrett radius of the isotope and the reference isotope.

    - v2 (`float`) – The V2 factor of the isotope.

    - v2_ref (`float`) – The V2 factor of the reference isotope.

    - v4 (`float`) – The V4 factor of the isotope.

    - v4_ref (`float`) – The V4 factor of the reference isotope.

    - v6 (`float`) – The V6 factor of the isotope.

    - v6_ref (`float`) – The V6 factor of the reference isotope.

    - c2c1 (`float`) – Seltzer’s coefficient for the quartic moment.

    - c3c1 (`float`) – Seltzer’s coefficient for the sextic moment.

  Returns

    The difference of the mean sextic nuclear charge radius between two isotopes and its uncertainty.

`qspec.physics.``lambda_rn`(r_2, r_2_d, r_4, r_4_d, r_6, r_6_d, c2c1, c3c1)
  Parameters

    - r_2 (`float`) – The difference of the mean square nuclear charge radius between two isotopes.

    - r_2_d (`float`) – The uncertainty of the difference of the mean square nuclear charge radius.

    - r_4 (`float`) – The difference of the mean quartic nuclear charge radius between two isotopes.

    - r_4_d (`float`) – The uncertainty of the difference of the mean quartic nuclear charge radius.

    - r_6 (`float`) – The difference of the mean sextic nuclear charge radius between two isotopes.

    - r_6_d (`float`) – The uncertainty of the difference of the mean sextic nuclear charge radius.

    - c2c1 (`float`) – Seltzer’s coefficient for the quartic moment.

    - c3c1 (`float`) – Seltzer’s coefficient for the sextic moment.

  Returns

    the Lambda observable for the given differences in mean square, quartic and sextic nuclear charge radii and its uncertainty.

`qspec.physics.``lande_f`(i, j, f, g_n, g_j)
  Parameters

    - i (`float`) – The nuclear spin quantum number I.

    - j (`float`) – The electronic total angular momentum quantum number J.

    - f (`float`) – The total angular momentum quantum number F.

    - g_n (`float`) – The nuclear g-factor.

    - g_j (`float`) – The electronic g-factor.

  Return type

    `float`

  Returns

    The hyperfine structure g-factor.

`qspec.physics.``lande_j`(s, ll, j, approx_g_s=False)
  Parameters

    - s (`float`) – The electron spin quantum number S.

    - ll (`float`) – The electronic angular momentum quantum number L.

    - j (`float`) – The electronic total angular momentum quantum number J.

    - approx_g_s (`bool`) – Whether to use g_s = -2 or the QED result g_s = -2.0023… .

  Return type

    `float`

  Returns

    The electronic g-factor.

`qspec.physics.``lande_n`(gyro)
  Parameters

    gyro (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The gyromagnetic ratio (MHz).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The nuclear g-factor.

`qspec.physics.``mass_factor`(m, m_ref, m_d=0, m_ref_d=0, k_inf=True)
  Parameters

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the isotope (amu).

    - m_ref (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the reference isotope (amu). Must be a scalar or have the same shape as ‘m’.

    - m_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the mass of the isotope (amu). Must be a scalar or have the same shape as ‘m’.

    - m_ref_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainty of the mass of the reference isotope (amu). Must be a scalar or have the same shape as ‘m’.

    - k_inf (`bool`) – Whether the normal mass-shift factor K(NMS) is defined mass independently as m_e * T(inf) (= True) or as m_e * T(A_ref) (= False). Compare (6.4) with (3.17) in [W. H. King, Isotope shifts in atomic spectra (1984)].

  Return type

    (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

  Returns

    the mass factor and its uncertainty needed to calculate modified isotope shifts or charge radii.

`qspec.physics.``p_e`(e, m, p0=0, relativistic=True)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Energy which is added to the kinetic energy of a body with velocity v0 (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial momentum of the body (amu m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The momentum of a body with starting momentum p0 and mass m after the addition of the kinetic energy e (amu m/s).

`qspec.physics.``p_el`(u, q, m, p0=0, relativistic=True)
  Parameters

    - u (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric potential difference added to the kinetic energy of a body with velocity v0 (V).

    - q (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The charge of a body (e).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial momentum of the body (amu m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The momentum of a body with starting momentum p0, charge q and mass m after electrostatic acceleration with voltage u.

`qspec.physics.``p_v`(v, m, relativistic=True)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The momentum of a body with velocity v and mass m.

`qspec.physics.``photon_recoil`(f, m)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the atoms rest frame (MHz).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of a body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The change of a transition frequency of an atom at rest due to the absorption of a photon with frequency f (MHz).

`qspec.physics.``photon_recoil_v`(v, alpha, f_lab, m)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The velocity of a body (m/s).

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between a velocity- and a wave-vector in the laboratory frame (rad).

    - f_lab (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in the laboratory frame (MHz).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of a body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The change of a transition frequency of an atom moving with velocity v due to the absorption of a laser photon with frequency f (MHz).

`qspec.physics.``rabi`(a, s)
  Parameters

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein A coefficient (MHz).

    - s (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The saturation parameter.

  Returns

    The rabi frequency.

`qspec.physics.``saturation`(i, f, a, a_dipole)
  Parameters

    - i (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The intensity of the laser (MHz).

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of the transition (MHz).

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein A coefficient (MHz).

    - a_dipole (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The reduced dipole coefficient of the transition (see algebra.a_dipole).

  Returns

    The saturation parameter.

`qspec.physics.``saturation_intensity`(f, a, a_dipole)
  Parameters

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of the transition (MHz).

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein A coefficient (MHz).

    - a_dipole (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The reduced dipole coefficient of the transition (see algebra.a_dipole).

  Returns

    The saturation intensity.

`qspec.physics.``scattering_rate`(df, a, s)
  Parameters

    - df (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The detuning of to be scattered light from the transition. This must be differences of real frequencies, such that w = 2 pi * df (MHz).

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein A coefficient (MHz).

    - s (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The saturation parameter.

  Returns

    The 2-state-equilibrium scattering-rate of an electronic transition.

`qspec.physics.``schmidt_line`(ll, j, is_proton)

`qspec.physics.``sellmeier`(w, a, b)
  Parameters

    - w (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The wavelength in µm.

    - a (`Union`[`ndarray`, `Iterable`]) – The a coefficients.

    - b (`Union`[`ndarray`, `Iterable`]) – The b coefficients.

  Returns

    The index of refraction for the wavelength w and the given material.

`qspec.physics.``source_energy_pdf`(f, f0, sigma, xi, collinear=True)
  Parameters

    - f – Frequency quantiles (arb. units).

    - f0 – Frequency offset (arb. units).

    - sigma – The standard deviation of the underlying normal distribution in frequency units ([f]).

    - xi – The proportionality constant between kinetic energy differences and frequency differences ([f]).

    - collinear –

  Returns

    PDF of rest frame frequencies after acceleration of thermally and normally distributed kinetic energies.

`qspec.physics.``thermal_e_pdf`(e, t)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – energy quantiles (eV).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density at the energy e, distributed according to a boltzmann distribution (1/eV).

`qspec.physics.``thermal_e_rvs`(t, size=1)
  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

    - size (`Union`[`int`, `tuple`]) – Either the size (int) or shape (tuple) of the returned energy array. If ‘t’ is an iterable/array, its shape must be appended to the desired shape of the random samples.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    Random energies according to the boltzmann distribution (m/s).

`qspec.physics.``thermal_v_pdf`(v, m, t)
  Parameters

    - v (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – velocity quantiles (m/s).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the ensembles bodies (amu).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The probability density in thermal equilibrium at the velocity v (s/m).

`qspec.physics.``thermal_v_rvs`(m, t, size=1)
  Parameters

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the ensembles bodies (amu).

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The temperature of the ensemble (K).

    - size (`Union`[`int`, `tuple`]) – Either the size (int) or shape (tuple) of the returned velocity array. If ‘m’ or ‘t’ is an iterable/array, their common shape must be appended to the desired shape of the random samples.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    Random velocities according to the thermal equilibrium distribution (m/s).

`qspec.physics.``v_e`(e, m, v0=0, relativistic=True)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Energy which is added to the kinetic energy of a body with velocity v0 (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The velocity of a body with mass m and velocity v0 after the addition of the kinetic energy e (m/s).

`qspec.physics.``v_e_d1`(e, m, v0=0, relativistic=True)
  Parameters

    - e (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Energy which is added to the kinetic energy of a body with velocity v0 (eV).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The first derivative of ‘v_e’ regarding ‘e’ (m/(s eV)).

`qspec.physics.``v_el`(u, q, m, v0=0, relativistic=True)
  Parameters

    - u (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric potential difference added to the kinetic energy of a body with velocity v0 (V).

    - q (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The charge of a body (e).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The velocity of a body with starting velocity v0, charge q and mass m after electrostatic acceleration with voltage u (m/s).

`qspec.physics.``v_el_d1`(u, q, m, v0=0, relativistic=True)
  Parameters

    - u (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The electric potential difference added to the kinetic energy of a body with velocity v0 (V).

    - q (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The charge of a body (e).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass of the body (amu).

    - v0 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The initial velocity of the body (m/s).

    - relativistic – The calculation is performed either relativistically or classically.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The first derivative of ‘v_el’ regarding ‘u’ (m/(s V)).

`qspec.physics.``v_rec`(f, m)
  Parameters

    - f – The frequency of light in the atoms rest frame (MHz).

    - m – The mass of a body (amu).

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The change of velocity of an atom at rest due to the absorption of a photon with frequency f (m/s).

`qspec.physics.``wavelength_to_freq`(lam)
  Parameters

    lam (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The wavelength lambda of a transition (um)

  Returns

    The frequency corresponding to the wavelength lam (MHz).

`qspec.physics.``wavelength_to_inv_cm`(lam)
  Parameters

    lam (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The wavelength lambda of a transition (um)

  Returns

    The wavenumber k corresponding to the wavelength lam (cm ** -1).

`qspec.physics.``zeeman`(m, b, g, as_freq=True)
  Parameters

    - m (`float`) – The B-field-axis component quantum number m of the total angular momentum.

    - b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The B-field (T).

    - g (`float`) – The g-factor.

    - as_freq – The zeeman shift can be returned in energy or frequency units.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The energy shift of an atomic state due to the zeeman effect in energy or frequency units (eV or MHz).

## qspec.simulate module

### qspec.simulate

Created on 20.05.2023

@author: Patrick Mueller

Module for simulations of laser-atom interactions.

class `qspec.simulate.``Atom`(states=None, decay_map=None, mass=0, instance=None)

  Bases: `object`

  Class representing an Atom and its inner structure.

  property `decay_map`
    Returns

      The decay map which connects the atomic states.

  property `dipoles`
    Returns

      The dipole strengths between the atomic states in the 3 basis-components of the spherical vector basis ( sigma-, pi, sigma+ ). This can be used to calculate Rabi-frequencies by multiplying it with the square-root of a laser intensity in the corresponding polarization. The resulting array has shape (3, size, size).

  `get_state_indexes`(labels=None, f=None)
    Parameters

      - labels (`Union`[`Iterable`[`str`], `str`, `None`]) – The labels of the states whose indexes are to be returned.

      - f (`Union`[`Iterable`[`Union`[`int`, `float`]], `int`, `float`, `None`]) – The F quantum numbers whose indexes are to be returned.

    Return type

      `ndarray`

    Returns

      The indexes corresponding to the specified labels and F quantum numbers.

  `get_y0`(ground_state_labels=None)
    Parameters

      ground_state_labels (`Union`[`Iterable`[`str`], `str`, `None`]) – An Iterable of labels belonging to ground states.

    Return type

      `ndarray`

    Returns

      The initial population of the atom.

  property `gs`
    Return type

      `ndarray`

    Returns

      The indices of the ground states.

  property `l0`
  property `l1`
  property `mass`
    Returns

      The mass of the atom (u).

  `plot`(indices=None, draw_bounds=False, show=True)

    Plot a term scheme of the atom.

    Parameters

      - indices (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The indices of the states to be drawn. If None, all states are drawn.

      - draw_bounds (`bool`) – Whether to draw the upper vertical bounds of the states.

      - show (`bool`) – Whether to show the plot.

    Returns

      The x and y positions of the states as well as the distance constant d.

  `scattering_rate`(rho, theta=None, phi=None, as_density_matrix=True, i=None, j=None, axis=1)
    Parameters

      - rho (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The state vector (density matrix) of the atom. Must have the same size as the atom along the specified ‘axis’ (and ‘axis’ + 1).

      - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The elevation angle of detection.

      - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The azimuthal angle of detection.

      - as_density_matrix (`bool`) – Whether ‘rho’ is a state vector or a density matrix.

      - i (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initially excited state indexes to consider for spontaneous decay. If None, all states are considered.

      - j (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The final decayed state indexes to consider for spontaneous decay. If None, all states are considered.

      - axis (`int`) – The axis along which the population is aligned in ‘rho’.

    Returns

      The scattering rate of the atom given the population ‘rho’ (MHz or Events / s).

    Raises

      ValueError – ‘rho’ must have the same size as the atom along the specified ‘axis’.

  property `size`
    Returns

      The number of states of the atom.

  property `states`
    Returns

      The states of the atom.

  `update`()

    Update the atom.

    Returns

      None.

class `qspec.simulate.``DecayMap`(labels=None, a=None, instance=None)

  Bases: `object`

  Class linking sets of atomic states via Einstein-A coefficients.

  property `a`
    Returns

      The list of Einstein-A coefficients.

  `get`(label_0, label_1)
    Returns

      The number of linked sets of atomic states.

  property `labels`
    Returns

      The list of label pairs, corresponding to atomic states which get connected.

  property `size`
    Returns

      The number of linked sets of atomic states.

class `qspec.simulate.``Environment`(E=None, B=None, instance=None)

  Bases: `object`

  Class representing an electromagnetic environment.

  property `B`
  property `E`

class `qspec.simulate.``Geometry`

  Bases: `object`

  Class representing a fluorescence detection geometry. The solid angle over which fluorescence light is detected can be defined through intervals of the two angles ‘theta’ and ‘phi’. With these, every spacial direction can be addressed using an orthonormal system defined by

  \[\begin{split}\hat{e}_r &:= \begin{pmatrix}\sin(\theta) \\ \cos(\theta)\sin(\phi) \\ \cos(\theta)\cos(\phi)\end{pmatrix}.\end{split}\]

  If the user specifies a rotation object with unitary matrix \(R\), the new system is \(\hat{e}_r^\prime = R \hat{e}_r\) The entire two-dimensional interval is defined through the cartesian product \(\bigcup_i \theta_i \times \bigcup_i \phi_i\). For every disjoint interval a weight can be defined through a ‘weights’ matrix. A probability distribution function (pdf) can be defined to have continuous angle weights. A rotation matrix can be defined to rotate the entire coordinate systems/detection geometry. A sample of angle pairs from the defined intervals can be generated using the ‘integration_sample’ method.

  `integration_sample`(step=None)
    Parameters

      step (`Union`[`int`, `float`, `None`]) – None or a scalar which defines the approximate spacing between the equidistant values of the integration sample. If step == None, the currently defined step size is used. The standard value is pi/32.

    Return type

      (<class ‘list’>, <class ‘list’>)

    Returns

      Two lists of arrays with equidistant values in the defined intervals for ‘theta’ and ‘phi’, respectively. Note that all intervals are exactly covered by an odd number of values (for Simpson integration) under the expense of not matching the ‘step’ size exactly.

  `plot`(show=True)

    Shows a 3d plot of the angular range covered by the geometry object. :returns: The axes object.

  `set_intervals`(theta, phi)
    Parameters

      - theta (`Union`[`ndarray`, `Iterable`]) – An interval or a list of intervals for the angle ‘theta’.

      - phi (`Union`[`ndarray`, `Iterable`]) – An interval or a list of intervals for the angle ‘phi’.

    Returns

      None. Merges overlapping intervals and calculates the solid angle corresponding to the defined intervals.

  `set_pdf`(pdf)
    Parameters

      pdf (`Optional`[`Callable`]) – None or a callable which accepts two arguments (theta, phi).

    Returns

      None. Sets the ‘pdf’ attribute of the Geometry object.

  `set_rotation`(r=None)
    Parameters

      r (`Optional`[`Rotation`]) – None or a 3x3 matrix defining a rotation.Therefore, dot(r, r.T) = I and Det(r) = 1 must be fulfilled. If r == None, the Identity matrix is used.

    Returns

      None. Sets the ‘R’ attribute of the Geometry object.

  `set_weights`(weights)
    Parameters

      weights (`Union`[`ndarray`, `Iterable`, `None`]) – None or a matrix of weights for the defined disjoint intervals. The shape of the weights must fulfill weights.shape == (len(self.theta_intervals), len(self.phi_intervals)).

    Returns

      None. Sets the ‘weights’ attribute of the geometry object.

class `qspec.simulate.``Interaction`(atom=None, lasers=None, delta_max=1000.0, controlled=False, instance=None)

  Bases: `object`

  Class representing an Interaction between lasers and an atom.

  property `atom`
    Returns

      The atom of the interaction.

  property `atommap`
    Returns

      A projection matrix A mapping the state frequencies onto the diagonal of the Hamiltonian. It holds diag(H)_i <- sum_j(A_ij * state_j.freq).

  property `controlled`
    Returns

      Whether the ODE solver uses an error controlled stepper or a fixed step size. Setting this to True is particularly useful for dynamics where a changing resolution is required. However, this comes at the cost of computing time.

  property `delta_max`
    Returns

      The maximum absolute difference between a laser and a transition frequency for that transition to be considered laser-driven (MHz). The default value is 1 GHz.

  property `deltamap`
    Returns

      A projection matrix B mapping the laser frequencies onto the diagonal of the Hamiltonian. It holds diag(H)_i <- sum_j(B_im * laser_m.freq).

  property `dt`
    Returns

      The maximum step size of the solver and the rough time spacing of generated results. However, this comes at the cost of computing time.

  property `environment`
    Returns

      The environment of the interaction.

  `get_delta`()
  `get_rabi`(m=None)
    Parameters

      m (`Optional`[`int`]) – The laser number ‘m’. If None, the Rabi frequencies are returned for all lasers as an array with shape (#lasers, atom.size, atom.size).

    Returns

      The Rabi frequencies (generated by the laser ‘m’).

  property `history`
    Returns

      The history of states visited during the generation of the diagonal maps.

  property `history_size`
    Returns

      The length of the history of states visited during the generation of the diagonal maps.

  property `lasers`
    Returns

      The lasers of the interaction.

  property `loop`
    Returns

      Whether there are loops formed by the lasers in the atom.

  `master`(t, delta=None, m=0, v=None, y0=None)
    Parameters

      - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The times when to compute the solution.

      - delta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – An array of frequency shifts for the laser(s). ‘delta’ must be a scalar or a 1d- or 2d-array with shapes (n, ) or (n, #lasers), respectively.

      - m (`Optional`[`int`]) – The index of the shifted laser. If delta is a 2d-array, ‘m’ ist omitted.

      - v (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Atom velocities. Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) are assumed to be aligned with the x-axis.

      - y0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial state / density matrix of the atom. This must be None or have shape (#states, ) or (n, #states, #states). If None, the ground states are populated equally.

    Returns

      The integrated master equation as a complex-valued array of shape (n, #states, #states, #times).

  `mc_master`(t, delta=None, m=0, v=None, y0=None, dynamics=False, ntraj=500)
    Parameters

      - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The times when to compute the solution.

      - delta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – An array of frequency shifts for the laser(s). ‘delta’ must be a scalar or a 1d- or 2d-array with shapes (n, ) or (n, #lasers), respectively.

      - m (`Optional`[`int`]) – The index of the shifted laser. If delta is a 2d-array, ‘m’ ist omitted.

      - v (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Atom velocities. Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) are assumed to be aligned with the x-axis.

      - y0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial state of the atom. This must be None or have shape (n, #states). If None, only the first ground state is populated.

      - dynamics (`bool`) – Whether to compute the dynamics of the photon-atom interactions.

      - ntraj (`int`) – The number of samples to compute if no samples were given with ‘delta’, ‘v’, or ‘y0’.

    Returns

      The integrated MC-Schroedinger equation as a complex-valued array of shape (n, #states, #times).

  `rates`(t, delta=None, m=0, v=None, y0=None)
    Parameters

      - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The times when to compute the solution.

      - delta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – An array of frequency shifts for the laser(s). ‘delta’ must be a scalar or a 1d- or 2d-array with shapes (n, ) or (n, #lasers), respectively.

      - m (`Optional`[`int`]) – The index of the shifted laser. If delta is a 2d-array, ‘m’ ist omitted.

      - v (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Atom velocities. Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) is assumed to be aligned with the x-axis.

      - y0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial state of the atom. This must be None or have shape (n, #states). If None, the ground states are populated equally.

    Returns

      The integrated rate equations as a real-valued array of shape (n, #states, #times).

  `resonance_info`()

    Prints the detunings of the base frequencies of the lasers in the given atomic system. In particular useful for systems with a hyperfine structure. Here

    \[\Delta = \nu_0 - \nu_L.\]
    Returns

      None.

  `scattering_rate`(rho, theta=None, phi=None, i=None, j=None, axis=1)
    Parameters

      - rho (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The density matrix of the atom. Must have the same size as the atom along the specified ‘axis’ and ‘axis’ + 1.

      - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The elevation angle of detection.

      - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The azimuthal angle of detection.

      - i (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initially excited state indexes to consider for spontaneous decay. If None, all states are considered.

      - j (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The final decayed state indexes to consider for spontaneous decay. If None, all states are considered.

      - axis (`int`) – The axis along which the population is aligned in ‘rho’.

    Returns

      The scattering rate of the atom given the population ‘rho’ (MHz or Events / s).

    Raises

      ValueError – ‘rho’ must have the same size as the atom along the specified ‘axis’.

  `schroedinger`(t, delta=None, m=0, v=None, y0=None)
    Parameters

      - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The times when to compute the solution.

      - delta (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – An array of frequency shifts for the laser(s). ‘delta’ must be a scalar or a 1d- or 2d-array with shapes (n, ) or (n, #lasers), respectively.

      - m (`Optional`[`int`]) – The index of the shifted laser. If delta is a 2d-array, ‘m’ ist omitted.

      - v (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Atom velocities. Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) are assumed to be aligned with the x-axis.

      - y0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial state of the atom. This must be None or have shape (n, #states). If None, only the first ground state is populated.

    Returns

      The integrated Schroedinger equation as a complex-valued array of shape (n, #states, #times).

  property `summap`
    Returns

      A (atom.size x atom.size)-matrix indicating the states which are laser-connected.

  property `time_dependent`
    Returns

      Whether the system hamiltonian is allowed to be time dependent.

  `update`()

    Updates the Interaction.

    Returns

      None.

class `qspec.simulate.``Laser`(freq, intensity=1.0, polarization=None, k=None, instance=None)

  Bases: `object`

  Class representing a laser.

  property `freq`
    Returns

      The frequency of the laser.

  property `intensity`
    Returns

      The intensity of the laser.

  property `k`
    Returns

      The direction of the laser. The default direction is ( 1, 0, 0 ).

  property `polarization`
    Returns

      The polarization of the laser.

class `qspec.simulate.``Polarization`(vec=None, q_axis=2, vec_as_q=True, instance=None)

  Bases: `object`

  Class representing a polarization state of light. The property ‘x’ holds the polarization in cartesian coordinates. The property ‘q’ holds the polarization in spherical coordinates ( sigma-, pi, sigma+ ) with respect to the chosen quantization axis.

  `def_q_axis`(q_axis=2, q_fixed=False)

    Defines the quantization axis. This changes either ‘x’ or ‘q’, depending on ‘q_fixed’.

    Parameters

      - q_axis (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The quantization axis. Must be an integer in {0, 1, 2} or a 3d-vector. The default is 2 (z-axis).

      - q_fixed (`bool`) – Whether ‘q’ should stay the same with the new quantization axis (True) or ‘x’ (False).

  property `q`
    Return type

      `ndarray`

    Returns

      The complex polarization in spherical coordinates ( sigma-, pi, sigma+ ).

  property `q_axis`
    Return type

      `ndarray`

    Returns

      The complex polarization in spherical coordinates ( sigma-, pi, sigma+ ).

  property `x`
    Return type

      `ndarray`

    Returns

      The complex polarization in cartesian coordinates ( x, y, z ).

class `qspec.simulate.``ScatteringRate`(atom, i_decay=0, geometry=None, polarization=None, b=None)

  Bases: `object`

  Class representing the perturbative scattering rate of a closed electronic transition. The spectrum is excited by a laser with the specified ‘polarization’ and recorded with a FDR defined by ‘geometry’. An external magnetic field can be defined through ‘b’.

  `check_atom`()

    Check whether the structure of the atom fulfills all requirements to calculate the scattering rate.

    Raises

      ValueError – The atom has to consist of a single closed transition between two fine-structure states. Their common nucleus can have an arbitrary spin.

    Returns

      None.

  `generate_dipoles`()
    Returns

      None. Generates an array of frequencies which cover the entire spectrum and saves it to the x attribute of the Spectrum object.

  `generate_x`(width=20.0, step=None)
    Parameters

      - width (`Union`[`int`, `float`]) – The covered width around resonances in natural linewidths.

      - step (`Union`[`int`, `float`, `None`]) – The step size between generated x values. Note that between resonances, there might be a larger step.

    Returns

      An array of frequencies which covers the entire spectrum.

  `generate_y`(x, theta, phi, decimals=8)
    Parameters

      - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in an atoms rest frame (MHz).

      - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle between the emission direction of the fluorescence light and the x-axis + 90°.

      - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mixing angle between the y- and z-axis (sin(phi), cos(phi)).

      - decimals (`int`) – The precision of the vector calculus in considered decimal places.

    Returns

      The fluorescence spectrum for incident light with frequency ‘x’ for the direction of emission defined by ‘theta’ and ‘phi’.

  `generate_y0`(x)
    Parameters

      x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in an atoms rest frame (MHz).

    Return type

      `Union`[`ndarray`, `Iterable`, `int`, `float`]

    Returns

      The spectrum for the case of unpolarized light and the detection of the complete solid angle (4 pi).

  `generate_y_4pi`(x)
    Parameters

      x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in an atoms rest frame (MHz).

    Return type

      `Union`[`ndarray`, `Iterable`, `int`, `float`]

    Returns

      The spectrum for the detection of the complete solid angle (4 pi).

  `integrate_y`(x, step=None)
    Parameters

      - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency of light in an atoms rest frame (MHz).

      - step (`Union`[`int`, `float`, `None`]) – The step size used for the integration over the angles theta and phi.

    Returns

      The fluorescence spectrum for incident light with frequencies ‘x’ integrated over the directions of emission ‘theta’ and ‘phi’.

  `plot_angular_distribution`(x=None, n=5, theta=None, phi=None, mode=None, show=True, save=None)
    Parameters

      - x (`Union`[`int`, `float`, `None`]) – The frequency of light in an atoms rest frame (MHz). If None, the position of the first maximum is taken (self.x0[0][0]).

      - n (`int`) – 2 ** n + 1 samples for ‘theta’ and 2 ** (n + 1) + 1 samples for ‘phi’ are drawn, giving a total of 2 ** (2n + 1) + 3 * 2 ** n + 1 points to draw.

      - theta (`Union`[`ndarray`, `Iterable`, `None`]) – A custom array for theta. Overwrites ‘n’.

      - phi (`Union`[`ndarray`, `Iterable`, `None`]) – A custom array for phi. Overwrites ‘n’.

      - mode (`Optional`[`str`]) – Either ‘3d’ for a surface plot or anything else for a color-mesh plot.

      - save (`Optional`[`str`]) – The path where to save the plot. If None, the plot will not be saved.

      - show (`bool`) – Whether to show the plot.

    Returns

      theta, phi and z. Optionally, a plot is drawn and saved.

  `plot_mixed_distribution`(n=5, mode=None, show=True, save=None)
    Parameters

      - n (`int`) – 2 ** n + 1 samples for ‘theta’ and 2 ** (n + 1) + 1 samples for ‘phi’ are drawn, giving a total of (2 ** n + 1) * len(self.x) and (2 ** (n + 1) + 1) * len(self.x) points to draw for theta and phi, respectively.

      - mode (`Optional`[`str`]) – Either ‘3d’ for a surface plot or anything else for a color-mesh plot.

      - save (`Optional`[`str`]) – The path where to save the plot. If None, the plot will not be saved.

      - show (`bool`) – Whether to show the plot.

    Returns

      None. Optionally, two plots are drawn for theta and phi as the y-axes and saved.

  `plot_setup`()
    Returns

      None. Creates a 3D-plot of the physical situation, including the axis of the magnetic field (quantization axis), the real and imaginary axis of the polarization and the are which is covered by the detector geometry.

  `plot_spectrum`(norm_to_4pi=False, step=None)
    Parameters

      - norm_to_4pi (`bool`) – Whether to renormalize the spectrum defined by geometry to have the same maximum as the spectrum for the detection with the complete solid angle 4 pi. If True, the difference between the two spectra is plotted as well. Default is False.

      - step (`Union`[`int`, `float`, `None`]) – The step size for the integration of the scattering rate.

    Returns

      None. Plots the spectrum for the given geometry and that for the detection with the complete solid angle 4 pi.

  `set_b`(b)
    Parameters

      b (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The magnetic field vector.

    Returns

      None. Sets the new magnetic field for all states and updates the quantization axis and the resonance positions.

  `set_geometry`(geometry=None)
    Parameters

      geometry (`Optional`[`Geometry`]) – The geometry object. If None, the entire solid angle is covered by the detector.

    Returns

      None. Sets the geometry object.

  `set_polarization`(polarization=None)
    Parameters

      polarization (`Optional`[`Polarization`]) – The polarization object. If None, the light is linearly polarized along the z-axis.

    Returns

      None. Sets the polarization object and the local polarization vector ‘e_l’.

  `set_states`()

    Define lower and upper states.

    Returns

      None.

  `set_x0`()
    Returns

      None. Updates the resonance positions.

class `qspec.simulate.``State`(freq_j, s, l, j, i, f, m, hyper_const=None, g=0, label=None, instance=None)

  Bases: `object`

  Class representing an atomic quantum state \(|(\mathrm{label})SLJIFm\rangle\).

  property `f`
    Returns

      The total angular momentum quantum number F.

  property `freq`
    Returns

      The shifted frequency of the hyperfine-structure state.

  property `freq_j`
    Returns

      The frequency of the fine-structure state.

  property `g`
    Returns

      The nuclear g-factor.

  `get_shift`()
    Returns

      The difference between the shifted frequency of the hyperfine-structure and the frequency of the fine-structure state.

  property `hyper_const`
    Returns

      The hyperfine-structure constants as a 3d-vector.

  property `i`
    Returns

      The nuclear spin quantum number I.

  property `j`
    Returns

      The electronic total angular momentum quantum number J.

  property `l`
    Returns

      The electronic angular momentum quantum number L.

  property `label`
    Returns

      The label of the state. The label is used to link states via decay maps.

  property `m`
    Returns

      The B-field-axis component quantum number m of the total angular momentum.

  property `s`
    Returns

      The electron spin quantum number S.

  `update`(environment=None)

    Update the shifted frequency of the state.

    Returns

      None.

`qspec.simulate.``construct_electronic_state`(freq_0, s, l, j, i=0, hyper_const=None, g=0, label=None)

  Creates all substates of a fine-structure state using a common label.

  Parameters

    - freq_0 (`Union`[`int`, `float`]) – The energetic position of the state without the hyperfine structure or the magnetic field (MHz).

    - s (`Union`[`int`, `float`]) – The electron spin quantum number S.

    - l (`Union`[`int`, `float`]) – The electronic angular momentum quantum number L.

    - j (`Union`[`int`, `float`]) – The electronic total angular momentum quantum number J.

    - i (`Union`[`int`, `float`]) – The nuclear spin quantum number I.

    - hyper_const (`Optional`[`Iterable`[`Union`[`int`, `float`]]]) – The hyperfine-structure constants. Currently, constants up to the electric quadrupole order are supported (A, B). If ‘hyper_const’ is a scalar, it is assumed to be the constant A and the other orders are 0 (MHz).

    - g (`Union`[`int`, `float`]) – The nuclear g-factor.

    - label (`Optional`[`str`]) – The label of the states. The labels are used to link states via decay maps.

  Returns

    A list of the created states.

`qspec.simulate.``construct_hyperfine_state`(freq_0, s, l, j, i, f, hyper_const=None, g=0, label=None)

  Creates all substates of a fine-structure state using a common label.

  Parameters

    - freq_0 (`Union`[`int`, `float`]) – The energetic position of the state without the hyperfine structure or the magnetic field (MHz).

    - s (`Union`[`int`, `float`]) – The electron spin quantum number S.

    - l (`Union`[`int`, `float`]) – The electronic angular momentum quantum number L.

    - j (`Union`[`int`, `float`]) – The electronic total angular momentum quantum number J.

    - i (`Union`[`int`, `float`]) – The nuclear spin quantum number I.

    - f (`Union`[`int`, `float`]) – The hyperfine structure total angular momentum quantum number F.

    - hyper_const (`Optional`[`Iterable`[`Union`[`int`, `float`]]]) – The hyperfine-structure constants. Currently, constants up to the electric quadrupole order are supported (A, B). If ‘hyper_const’ is a scalar, it is assumed to be the constant A and the other orders are 0 (MHz).

    - g (`Union`[`int`, `float`]) – The nuclear g-factor.

    - label (`Optional`[`str`]) – The label of the states. The labels are used to link states via decay maps.

  Returns

    A list of the created states.

`qspec.simulate.``ct_markov_analytic`(t, n, rates, r=1.0)

  Computes the analytic solution of the evolution of a linear continuous-time markov chain.

  CAUTION! Computation of analytic solution problematic (Multiplication of very small numbers with very large numbers).

  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The time at which the probability is returned (us).

    - n (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The number of the state for which the probability is returned. The first state corresponds to ‘n’ = 0.

    - rates (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The rate(s) at which the markov chain is transferring population from state i to state i + 1. If ‘rates’ is a scalar, this rate is assumed for all 0 &#8804; i &#8804; ‘n’. If ‘rates’ is an Iterable, it must have length max(‘n’) + 1 and individual rates ‘rates[i]’ are assumed for the states 0 &#8804; i &#8804; ‘n’.

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The ratio of the population which is transferred from state i to state i + 1. Then 1 - r is the ratio of the population that is lost during the transition from state i to state i + 1.

  Returns

    The probability for the markov chain to be in state ‘n’ after the time ‘t’ for P(t=0, n=0) = 1. The normalization condition is sum_n(P(n, t0)) = 1 for every single point in time t0. If ‘t’ and ‘n’ are Iterables, a 2-d array is returned with shape (t.size, n.size), containing all probabilities P(t, n).

`qspec.simulate.``ct_markov_dgl`(t, n, rates, r=1.0, p0=None, time_resolved=False, show=False)

  Computes the evolution of a linear continuous-time markov chain numerically by solving the underlying ODE system.

  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The time after which the probability is returned. If all times from 0 to ‘t’ are required, use ‘time_resolved’=True (us).

    - n (`int`) – The maximum state number to compute. The first state corresponds to ‘n’ = 0.

    - rates (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The rate(s) at which the markov chain is transferring population from state i to state i + 1. If ‘rates’ is a scalar, this rate is assumed for all 0 &#8804; i &#8804; ‘n’. If ‘rates’ is an Iterable, individual rates ‘rates[i]’ are assumed for the states i and ‘rates’ must have size ‘n’ + 1.

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The ratio of the population which is transferred from state i to state i + 1. Here 1 - r is the ratio of the population that is lost during the transition from state i to state i + 1.

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial population distribution. Must be an Iterable of length max(‘n’) + 1. If None, ‘p0’ is set to [1, 0, 0, …, 0].

    - time_resolved (`bool`) – Whether to return the complete history of the result. If True, a 2-tuple similar to (time, population) is returned, were population has shape (time.size, n + 1). time will be an array of equally spaced times, such that numerical integrations can be performed easily.

    - show (`bool`) – Whether to plot the result.

  Returns

    The probability distribution of the states 0 &#8804; i &#8804; ‘n’ after the time ‘t’ for P(t=0, n=i) = p0[i] The normalization condition is sum_n(P(n, t0)) = 1 for every single point in time t0.

`qspec.simulate.``lambda_ge_rec`(t, n, delta, a_ge, a_me, s, f, m, p0=None, dt=None, time_resolved=False, show=False)

  Computes the evolution of Lambda-systems such as the alkali metals or the singly-charged alkaline-earth metals, taking into account photon recoils. The system is driven by a single laser. The state vector is defined as (g0, m0, e0, g1, m1, e1, …, gn, mn, en), where g is the first end of the Lambda, m the second end and e the intermediate state. The photon recoils are modeled using a discrete subspace and not the continuous momentum space. The number of photon recoils increases by one when the system is excited from the g state to the e state. Vice-versa, the number of photon recoils decreases by one when the system is deexcited from the e state to the g state via the process of stimulated emission. When the system decays into the g state via the dissipative mechanism described by the Einstein coefficient ‘a_ge’, the number of photon recoils does not change.

  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The time after which the probability is returned. If all times from 0 to ‘t’ are required, use ‘time_resolved’=True (us).

    - n (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The maximum number of photon recoils to consider.

    - delta (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The detuning of the laser relative to the g->e transition (MHz).

    - a_ge (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein coefficient of the e->g transition (MHz).

    - a_me (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein coefficient of the e->m transition (MHz).

    - s (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The saturation parameter of the g->e transition.

    - f (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The transition frequency of the g->e transition (MHz).

    - m (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The mass number of the element (u).

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial density matrix. Must have shape (6, ), containing the elements [gg, mm, ee, gm, eg, em](0) or be the full density matrix with all the recoil information.

    - dt (`Optional`[`float`]) – The width of the time steps.

    - time_resolved (`bool`) – Whether to return the complete history of the result.

    - show (`bool`) – Whether to plot the result.

  Returns

    The diagonal density matrix elements after the time ‘t’. If time_resolved is True, a 2-tuple similar to (time, density matrix) is returned, were the density matrix has shape (time.size, 3(n+1)). time will be an array of equally spaced times, such that numerical integrations can be performed easily.

`qspec.simulate.``lambda_states`(t, delta_1, delta_2, a_ge, a_me, s_1, s_2, lw_1=0.0, lw_2=0.0, p0=None, time_resolved=False, show=False)

  Computes the evolution of Lambda-systems such as the alkali metals or the singly-charged alkaline-earth metals. The state vector is defined as (g, m, e), where g is the first end of the Lambda, m the second end and e the intermediate state.

  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The time after which the probability is returned. If all times from 0 to ‘t’ are required, use ‘time_resolved’=True (us).

    - delta_1 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The detuning of the first laser relative to the g->e transition.

    - delta_2 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The detuning of the second laser relative to the m->e transition.

    - a_ge (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein coefficient of the e->g transition.

    - a_me (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The Einstein coefficient of the e->m transition.

    - s_1 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The saturation parameter of the g->e transition.

    - s_2 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The saturation parameter of the m->e transition.

    - lw_1 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency width of the first laser.

    - lw_2 (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The frequency width of the second laser.

    - p0 (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The initial density matrix. Must have shape (6, ), containing the elements [gg, mm, ee, gm, eg, em]. If None, initially all population is in the g state.

    - time_resolved (`bool`) – Whether to return the complete history of the result.

    - show (`bool`) – Whether to plot the result.

  Returns

    The density matrix elements after the time ‘t’. If time_resolved is True, a 2-tuple similar to (time, density matrix) is returned, were the density matrix has shape (time.size, 6). time will be an array of equally spaced times, such that numerical integrations can be performed easily.

## qspec.stats module

### qspec.stats

Created on 22.04.2020

@author: Patrick Mueller

Module for doing statistical analysis.

class `qspec.stats.``Observable`(x, std=None, std_2=None, label=None)

  Bases: `float`

  A float object which has a ‘label’ and optionally both a left- and right-sided or a symmetric uncertainty.

  `hist`(size=1000000, n_bins=200)
    Parameters

      - size (`int`) – The defining number of random variates (default is 1,000,000).

      - n_bins (`int`) – The number of bins.

    Returns

      None. Plots a histogram of the observable.

  `pdf`()
    Return type

      `Callable`

    Returns

      The probability distribution function (pdf) of the observable.

  `rvs`(size=1)
    Parameters

      size (`int`) – The defining number of random variates (default is 1).

    Return type

      `ndarray`

    Returns

      Random variates of the observable of given ‘size’. If asymmetric uncertainties are specified, a skew normal distribution is assumed. However, the ratio between the left- and right-sided uncertainty must not exceed 1.5.

  `set_popt`(popt=None)
    Parameters

      popt (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The new value of ‘popt’.

    Returns

      None. Sets the ‘popt’ attribute.

`qspec.stats.``add`(a, b)
  Parameters

    - a – The first summand.

    - b – The second summand.

  Returns

    The sum of the two summands.

`qspec.stats.``average`(a, std=None, cov=None, axis=None)
  Parameters

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The sample data.

    - axis (`Optional`[`int`]) – The axis along which the average is computed.

    - std (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – An array of standard deviations associated with the values in ‘a’. If specified, the weighted average of the uncorrelated sample data and its standard error is returned.

    - cov (`Union`[`ndarray`, `Iterable`, `None`]) – The covariance matrix associated with the values in ‘a’. If specified, it overrides ‘std’ and the weighted average of the correlated sample data and its standard error is returned. If no axis is specified, ‘cov’ must have shape (a.size, a.size) with elements associated with the values in the flattened ‘a’, otherwise cov must have either shape (a.shape[axis], a.shape[axis]) or (…, a.shape[axis - 1], a.shape[axis], a.shape[axis], a.shape[axis + 1], …).

  Return type

    (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

  Returns

    The average and its standard error for a given sample ‘a’ along the specified ‘axis’.

`qspec.stats.``combined_pdf`(z, pdf_1=<bound method rv_continuous.pdf of <scipy.stats._continuous_distns.norm_gen object>>, pdf_2=<bound method rv_continuous.pdf of <scipy.stats._continuous_distns.norm_gen object>>, loc_1=0.0, scale_1=1.0, loc_2=0.0, scale_2=1.0, operator='+', n=10)
  Parameters

    - z (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The quantiles of the combined probability density function (pdf).

    - pdf_1 (`Callable`) – The pdf of the first random variate.

    - pdf_2 (`Callable`) – The pdf of the second random variate.

    - loc_1 (`float`) – The ‘loc’ parameter of the first pdf.

    - scale_1 (`float`) – The ‘scale’ parameter of the first pdf.

    - loc_2 (`float`) – The ‘loc’ parameter of the second pdf.

    - scale_2 (`float`) – The ‘scale’ parameter of the second pdf.

    - operator (`str`) – The operator that defines the new random variate given by Z = X <operator> Y. Currently supported operators are {‘+’, ‘*’}.

    - n (`int`) – The precision of the numerical integration. The integration uses 2 ** n intervals to evaluate the integral.

  Return type

    `ndarray`

  Returns

    The value of the pdf at the given ‘z’ quantiles.

`qspec.stats.``estimate_skewnorm`(med, per_0, per_1)
  Parameters

    - med (`Union`[`int`, `float`]) – The median (0.5-percentile) of a random variable.

    - per_0 (`Union`[`int`, `float`]) – The left-sided 1-sigma percentile (~0.1587-percentile) relative to ‘med’.

    - per_1 (`Union`[`int`, `float`]) – The right-sided 1-sigma percentile (~0.8413-percentile) relative to ‘med’.

  Returns

    A size-3-array of the estimated parameters (alpha, mean, std.) of a skew normal distribution that matches the given percentiles.

  Raises

    ValueError – If the ratio between the left-(right-) and right-(left-)sided uncertainty exceeds 1.5.

`qspec.stats.``info`()

  Plots the 1-sigma percentiles (and their ratio) of a skew normal distribution relative to its median for different values of the parameter alpha. The plot shows that the ratio between the two 1-sigma percentiles cannot exceed 1.5.

  Returns

    None.

`qspec.stats.``median`(a, axis=None)
  Parameters

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The sample data.

    - axis (`Optional`[`int`]) – The axis along which the three percentiles are computed.

  Return type

    (<class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>, <class ‘numpy.ndarray’>)

  Returns

    The median (0.5-percentile) as well as the left- (~0.1587) and right-sided (~0.8413) 1-sigma percentile of a given sample ‘a’ along the specified ‘axis’.

`qspec.stats.``mul`(a, b)
  Parameters

    - a – The first factor.

    - b – The second factor.

  Returns

    The product of the two factors.

`qspec.stats.``propagate`(f, x, x_d=None, cov=None, unc_places=None, sample_size=1000000, rtol=0.001, atol=None, force_sym=False, full_output=False, show=False)
  Parameters

    - f (`Callable`) – The function to compute. ‘f’ needs to be vectorized.

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`, `Observable`]) – The input values. If ‘x_d’ is None, the sample data will be generated with the ‘Observable.rvs’ function which considers asymmetric uncertainties. If an element is not an ‘Observable’, its uncertainty is assumed to be 0.

    - x_d (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The uncertainties of the input values.

    - cov (`Union`[`ndarray`, `Iterable`, `None`]) – The covariance matrix of the x values. If not None, ‘x’ are assumed to be distributed according to a multivariate normal distribution with covariance ‘cov’.

    - unc_places (`Optional`[`int`]) – The number of significant decimal places the result will be rounded to. If None, the result is not rounded.

    - sample_size (`int`) – The number of random variates used for the calculation. The default is 1,000,000.

    - rtol (`float`) – The relative tolerance, with respect to the median of the resulting sample, with which the left- and right-sided uncertainties can deviate before asymmetric uncertainties are used.

    - atol (`Optional`[`float`]) – The absolute tolerance with which the left- and right-sided uncertainties can deviate, before asymmetric uncertainties are used. Overrides ‘rtol’.

    - force_sym (`bool`) – Whether to force symmetric uncertainties. If so, a normal distribution is assumed.

    - full_output (`bool`) – Whether to return the randomly generated data samples.

    - show (`bool`) – Whether to show a histogram and estimated PDFs of the computed sample data.

  Return type

    (<class ‘qspec.stats.Observable’>, <class ‘list’>, <class ‘numpy.ndarray’>)

  Returns

    An ‘Observable’ whose uncertainties result from the propagation of the uncertainties of the input values ‘x’ by function ‘f’. If the uncertainties are asymmetric, the parameters of a skew normal distribution are estimated using least-square fitting and are stored to the observable. The value and the two uncertainties are the median and the left- (~0.1587) and right-sided (~0.8413) 1-sigma percentiles relative to the median, respectively. If the uncertainties are symmetric the observable is assumed to be normally distributed. The value and the single uncertainty is then calculated using the mean and the standard deviation of the sampled data. If ‘full_output’ is True, a list of the input samples as well as the output sample are returned along with the observable.

`qspec.stats.``propagate_fit`(f, x, popt, pcov, sample_size=1000000)
  Parameters

    - f (`Callable`) – The function to compute. \(f\) needs to be vectorized.

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The input values.

    - popt (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – An array of the fitted parameters (compare curve_fit).

    - pcov (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – A 2d-array of the estimated covariances (compare curve_fit).

    - sample_size (`int`) – The number of random variates used for the calculation. The default is 1,000,000.

  Returns

    The median and the \(1\sigma\) percentiles of the sampled function \(f\).

`qspec.stats.``relevant_interval`(dist, *args, show=False, **kwargs)
  Parameters

    - dist (`Callable`) – The probability distribution function (pdf).

    - args – Additional arguments for the pdf.

    - show (`bool`) – Whether to show the pdf in the determined interval.

    - kwargs – Additional keyword arguments for the pdf.

  Returns

    An estimation of the interval where most of the probability lies in.

`qspec.stats.``uniform`(x, width)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The x quantiles.

    - width (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The width of the uniform distribution.

  Return type

    `ndarray`

  Returns

    The probability density at ‘x’.

`qspec.stats.``uniform_pumped`(x, width, gamma_u, depth)
  Parameters

    - x – The x quantiles.

    - width – The width of the uniform distribution.

    - gamma_u – The fwhm of the pump transition.

    - depth – The depth of the pump dip in parts of the height of the underlying uniform distribution.

  Return type

    `ndarray`

  Returns

    A uniform distribution with a Lorentz-shaped dip.

## qspec.tools module

### qspec.tools

Created on 05.05.2020

@author: Patrick Mueller

Module including mathematical and technical methods.

class `qspec.tools.``COLORS`

  Bases: `object`

  `BOLD` = '\x1b[1m'
  `ENDC` = '\x1b[0m'
  `FAIL` = '\x1b[91m'
  `HEADER` = '\x1b[95m'
  `OKBLUE` = '\x1b[94m'
  `OKCYAN` = '\x1b[96m'
  `OKGREEN` = '\x1b[92m'
  `PYPLOT` = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9']
  `UNDERLINE` = '\x1b[4m'
  `WARNING` = '\x1b[93m'

class `qspec.tools.``Rotation`(alpha=0.0, dr=None)

  Bases: `object`

  An object specifying a rotation in 3d-space. The rotation is defined

    through an angle ‘alpha’ and an rotational axis ‘dr’ by the user. Additional instance attributes are the angle in degree ‘alpha_deg’ and the rotational matrix ‘R’.

`qspec.tools.``absolute`(x, axis=- 1)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – A real vector or an array of real vectors.

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The length(s) of the vector(s) x.

`qspec.tools.``absolute_complex`(x, axis=- 1)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – A complex vector or an array of complex vectors.

    - axis – The axis along which the vector components are aligned.

  Returns

    The length(s) of the vector(s) x.

`qspec.tools.``add_nested_key`(a, key_list, val)
  Parameters

    - a (`dict`) – The target dictionary.

    - key_list (`list`) – A list of nested keys of a.

    - val (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The value that is assigned to the last key in key_list.

  Return type

    `dict`

  Returns

    The dictionary a with val assigned to the last key in key_list.

`qspec.tools.``angle`(x, y, axis=- 1)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The first vectors (arb. units).

    - y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The second vectors ([x]).

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The angle between two vectors x and y (rad).

  Raises

    ValueError – The shapes of x and y must be compatible.

`qspec.tools.``angle_d`(x, x_d, y, y_d, axis=- 1)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The first vectors (arb. units).

    - x_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainties of the first vectors ([x]).

    - y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The second vectors ([x]).

    - y_d (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The uncertainties of the second vectors ([x]).

    - axis – The axis along which the vector components are aligned.

  Returns

    The angle between two vectors x and y (rad).

  Raises

    ValueError – The shapes of x and y must be compatible.

`qspec.tools.``asarray_optional`(a, **kwargs)
  Parameters

    - a (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – Input data, see numpy docs.

    - kwargs – The keyword arguments are passed to numpy.asarray.

  Returns

    None if ‘a’ is None else ‘numpy.asarray(a, **kwargs)’.

`qspec.tools.``check_dimension`(dim, axis, *args)
  Parameters

    - dim (`int`) – The number of components the axis ‘axis’ must have.

    - axis (`int`) – The axis which must have ‘dim’ components.

    - args (`ndarray`) – The arguments which must have ‘dim’ components along axis ‘axis’.

  Return type

    `None`

  Returns

    None

  Raises

    ValueError – All specified arguments must have ‘dim’ components along axis ‘axis’.

`qspec.tools.``check_half_integer`(*args)
  Parameters

    args (`Union`[`int`, `float`]) – Scalar arguments.

  Returns

    None. Checks whether the given arguments are multiples of 1/2.

  Raises

    ValueError – If any argument is not a multiple of 1/2.

`qspec.tools.``check_iterable`(arg, dtype=<class 'str'>)
  Parameters

    - arg (`Any`) – The argument that is checked.

    - dtype (`type`) – The type that has to be matched by the elements of arg or arg itself.

  Return type

    `list`

  Returns

    ‘arg’ as a list if it is a ‘list’, ‘tuple’ or ‘set’ of values of type ‘dtype’, a list of the single element ‘arg’ if it is of type ‘dtype’ and else an empty list.

`qspec.tools.``check_shape`(shape, *args, allow_scalar=True, return_mode=False)
  Parameters

    - shape (`tuple`) – The shape which must be matched by the specified arguments.

    - args (`ndarray`) – The arguments which must match the specified shape.

    - allow_scalar – Whether scalar values (shape=()) are seen as compatible with arbitrary shapes.

    - return_mode – Whether to raise a ValueError or return a boolean if any argument does not have shape ‘shape’.

  Return type

    `Optional`[`bool`]

  Returns

    whether the arguments match the specified shape.

  Raises

    ValueError – All specified arguments must match the specified shape.

`qspec.tools.``check_shape_like`(*args, allow_scalar=True)
  Parameters

    - args (`ndarray`) – The arguments which must have shapes that can be broadcast together.

    - allow_scalar – Whether scalar values (shape=()) are seen as compatible with arbitrary shapes.

  Return type

    `None`

  Returns

    None

  Raises

    ValueError – All specified arguments must have shapes that can be broadcast together.

`qspec.tools.``combine_dicts`(dicts, key_lists, operator='+', short_keys=True)
  Parameters

    - dicts (`list`) – A list of dictionaries to be combined.

    - key_lists (`Iterable`) – A list of Iterables of the same lengths which include keys from ‘a’. Must have the same length as ‘dicts’.

    - operator (`str`) – The operator which is used to combine the key_lists.

    - short_keys (`bool`) – Whether to just use the keys of the first key_list or representations of the entire operations as the new keys.

  Return type

    `Union`[`dict`, `ValueError`]

  Returns

    A dictionary of the shape {key_lists[0] + key_lists[1] + … : dicts[0][key_lists[0]] + dicts[1][key_lists[1]] + … } if operator == ‘+’.

`qspec.tools.``convolve_dict`(a, *key_lists, operator='+', short_keys=True)
  Parameters

    - a (`dict`) – A dictionary to be convolved.

    - key_lists (`Iterable`) – An arbitrary number of Iterables of the same length which include keys from ‘a’.

    - operator (`str`) – The operator which is used to combine the key_lists.

    - short_keys (`bool`) – Whether to just use the keys of the first key_list or representations of the entire operations as the new keys.

  Return type

    `Union`[`dict`, `ValueError`]

  Returns

    A dictionary of the shape {key_lists[0] + key_lists[1] + … : a[key_lists[0]] + a[key_lists[1]] + … } if operator == ‘+’.

`qspec.tools.``create_data_dir`(path=None, overwrite=False)
  Parameters

    - path (`Optional`[`str`]) – The path were to create the user folder “PyCLS” (do not include “PyCLS” in ‘path’). If None, the user folder is created in the “Documents” Windows library.

    - overwrite (`bool`) – Whether to overwrite the current “PyCLS” user folder if it exists.

  Returns

    None. Creates the user folder “PyCLS” at the specified ‘path’ or in the “Documents” Windows library if no ‘path’ is specified.

`qspec.tools.``create_doc_link`(env_path=None)
  Parameters

    env_path (`Optional`[`str`]) – The path to the virtual environment where the ‘Lib’ folder resides in. If None, the path is inherited from the currently running Python-executable.

  Returns

    None. Creates an html document redirecting to the API-Documentation inside the PyCLS installation.

`qspec.tools.``dict_to_list`(a)
  Parameters

    a (`dict`) – A dictionary.

  Return type

    (<class ‘list’>, <class ‘list’>)

  Returns

    Two lists with the keys and values of ‘a’, respectively. The lists are in the same order, however, they are not sorted.

`qspec.tools.``e_phi`(theta, phi, axis=- 1)
  Parameters

    - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle theta.

    - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle phi.

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The unit vector ‘e_phi’. Part of an orthonormal system defined by: e_x = e_r(pi/2, .) e_y = e_r(0, pi/2) e_z = e_r(0, 0)

`qspec.tools.``e_r`(theta, phi, axis=- 1)
  Parameters

    - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle theta.

    - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle phi.

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The unit vector ‘e_r’. Part of an orthonormal system defined by: e_x = e_r(pi/2, .) e_y = e_r(0, pi/2) e_z = e_r(0, 0)

`qspec.tools.``e_theta`(theta, phi, axis=- 1)
  Parameters

    - theta (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle theta.

    - phi (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle phi.

    - axis – The axis along which the vector components are aligned.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The unit vector ‘e_theta’. Part of an orthonormal system defined by: e_x = e_r(pi/2, .) e_y = e_r(0, pi/2) e_z = e_r(0, 0)

`qspec.tools.``even`(x)
  Parameters

    x (`float`) – A float value.

  Return type

    `int`

  Returns

    The closest even integer value.

`qspec.tools.``factorial`(n)
  Parameters

    n (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The integer number.

  Returns

    n! (array compatible).

`qspec.tools.``floor_log10`(x)
  Parameters

    x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Scalar values.

  Return type

    `ndarray`

  Returns

    The closest integer values below the logarithm with basis 10 of the absolute value of ‘x’.

`qspec.tools.``floor_log2`(x)
  Parameters

    x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – Scalar values.

  Return type

    `ndarray`

  Returns

    The closest integer values below the logarithm with basis 10 of the absolute value of ‘x’.

`qspec.tools.``fraction`(r)
  Parameters

    r (`Union`[`Rational`, `str`]) – A sympy.Rational or a str with the signature “‘num’/’denom’”.

  Return type

    (<class ‘int’>, <class ‘int’>)

  Returns

    the numerator and denominator of ‘r’.

`qspec.tools.``get_config_dict`()
  Return type

    `dict`

  Returns

    A dictionary containing the content of the currently used config file.

`qspec.tools.``get_decimals`(x)
  Parameters

    x (`float`) – A float value.

  Return type

    `int`

  Returns

    The number of displayed decimals of the float value ‘x’.

`qspec.tools.``get_default_path`()
  Returns

    The absolute path to the “PyCLS user folder.”

`qspec.tools.``get_rgb_print_command`(r, g, b)
  Parameters

    - r – The fraction of red (0-255).

    - g – The fraction of green (0-255).

    - b – The fraction of blue (0-255).

  Returns

    The command str to print rgb colors in the console.

`qspec.tools.``get_val_with_unc`(val_string)
  Parameters

    val_string (`str`) – The str representation of a number with uncertainty of the format ‘1.234(56)’. Decimal separators can be used or spared arbitrarily.

  Return type

    (<class ‘float’>, <class ‘float’>)

  Returns

    The value and its uncertainty.

`qspec.tools.``half_integer_to_fraction`(val)
  Parameters

    val (`Union`[`int`, `float`]) – A scalar value.

  Return type

    (<class ‘int’>, <class ‘int’>)

  Returns

    The numerator and denominator of the half-integer.

`qspec.tools.``half_integer_to_str`(val, symbol='_')
  Parameters

    - val (`Union`[`int`, `float`]) – A scalar value.

    - symbol (`str`) – The symbol to use for the fraction.

  Returns

    A rational str-representation of a half-integer.

`qspec.tools.``import_iso_shifts_tilda`(db, iso_shifts)
  Parameters

    - db (`str`) – Location of a Tilda-compatible database.

    - iso_shifts (`dict`) – A dictionary of isotope shifts with the structure {iso_str: {line_str: [val, stat_err, syst_err]}}.

  Returns

    None. Writes the entries of the given dict to the specified Tilda-compatible database.

`qspec.tools.``in_nested`(a, nested)
  Parameters

    - a – The element to look for.

    - nested (`Iterable`) – The nested list.

  Return type

    `bool`

  Returns

    Whether a is inside the ‘nested’ list.

`qspec.tools.``list_to_dict`(values, keys=None)
  Parameters

    - values (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The values of the dictionary.

    - keys (`Union`[`ndarray`, `Iterable`, `int`, `float`, `None`]) – The keys of the dictionary. If omitted, the keys will be the indices of the values.

  Return type

    `dict`

  Returns

    A dictionary with the given ‘values’ and ‘keys’.

`qspec.tools.``list_to_excel`(*args, save=None, delimiter='\\t', header='', align='top')
  Parameters

    - args (`Union`[`ndarray`, `Iterable`]) – 1- or 2-dimensional iterables to print or save in an excel-compatible format.

    - save (`Optional`[`str`]) – The filepath, either absolute or relative to the working directory. If None, the output is printed.

    - delimiter (`str`) – The delimiter between two columns.

    - header (`str`) – Add a header above the content to the output.

    - align (`str`) – How to align the columns that are smaller than the largest column. Supported alignments are {“top”, “bottom”, else == “top”}.

  Returns

    None. Prints or saves the ‘args’ in an excel-compatible way.

`qspec.tools.``make_str_iterable_unique`(a, identifier=None)
  Parameters

    - a (`Iterable`[`str`]) – An Iterable of str values.

    - identifier (`Optional`[`Iterable`[`str`]]) – An Iterable of str values to append to the values of ‘a’ if they appear more than once. If None, ‘_i’ is used as the identifier for the ith appearance of a value in ‘a’.

  Returns

    ‘a’, but the elements which appear more than once are numerated/attached with the identifiers and bunched. For example: [‘a’, ‘b’, ‘c’, ‘b’, ‘d’] -> [‘a’, ‘b_0’, ‘b_1’, ‘c’, ‘d’] or [‘a’, ‘b’, ‘c’, ‘b’, ‘d’] -> [‘a’, ‘b’ + identifier[0], ‘b’ + identifier[1], ‘c’, ‘d’].

`qspec.tools.``map_corr_coeff_to_color`(val, clip=True)
  Parameters

    - val – A value between -1 and 1.

    - clip – Whether to clip vals outside -1 and 1. If False, raise ValueError.

  Returns

    The RGB values in the range 0-255.

`qspec.tools.``merge_dicts`(a, b, path=None)
  Parameters

    - a (`dict`) – The first dictionary.

    - b (`dict`) – The second dictionary.

    - path – _.

  Return type

    `dict`

  Returns

    b merged into a. Function copied from andrew cooke https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries.

`qspec.tools.``merge_intervals`(intervals)
  Parameters

    intervals (`Union`[`ndarray`, `Iterable`]) – An iterable of intervals. An interval i is itself an iterable of two scalar values. If i[1] < i[0], the interval is reversed.

  Return type

    `ndarray`

  Returns

    An iterable of non-overlapping intervals.

`qspec.tools.``nan_helper`(y)
  Parameters

    y (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – An array like value.

  Return type

    (<class ‘numpy.ndarray’>, typing.Callable)

  Returns

    The mask where y is NaN and a function which returns the nonzero indices of an array.

`qspec.tools.``odd`(x)
  Parameters

    x (`float`) – A float value.

  Return type

    `int`

  Returns

    The closest odd integer value.

`qspec.tools.``orthonormal`(r, axis=- 1)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The first vector of the orthonormal system. Does not have to be normalized.

    - axis – The axis along which the vector components are aligned.

  Return type

    (typing.Union[numpy.ndarray, typing.Iterable, int, float], typing.Union[numpy.ndarray, typing.Iterable, int, float], typing.Union[numpy.ndarray, typing.Iterable, int, float])

  Returns

    Three orthonormal vectors, given the first vector ‘r’.

`qspec.tools.``orthonormal_rtp`(r, axis=- 1)
  Parameters

    - r (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The first vector of the orthonormal system. Does not have to be normalized.

    - axis – The axis along which the vector components are aligned.

  Return type

    (typing.Union[numpy.ndarray, typing.Iterable, int, float], typing.Union[numpy.ndarray, typing.Iterable, int, float], typing.Union[numpy.ndarray, typing.Iterable, int, float])

  Returns

    The three orthonormal vectors ‘e_r’, ‘e_theta’ and ‘e_phi’ given the vector ‘r’ pointing in the ‘e_r’ direction.

`qspec.tools.``print_colored`(specifier, *values, returned=False, **kwargs)

  Print with the specified color.

  Parameters

    - specifier – str of the color name defined in the COLORS class or an RGB-value (0-255, 0-255, 0-255).

    - values – The values to print.

    - returned – Return the str instead of printing it.

    - kwargs – See print().

  Returns

    None.

`qspec.tools.``print_cov`(cov, normalize=False, decimals=2)

  Print a covariance “as is” or as color-coded Pearson correlation coefficients.

  Parameters

    - cov – A covariance matrix.

    - normalize – Whether to normalize the covariance to be the Pearson correlation coefficient.

    - decimals – The number of decimal places to be printed.

  Returns

    None.

`qspec.tools.``printf`(*values, **kwargs)

  Print with the FAIL color (red).

  Parameters

    - values – The values to print.

    - kwargs – See print().

  Returns

    None.

`qspec.tools.``printh`(*values, **kwargs)

  Print with the HEADER color (pink).

  Parameters

    - values – The values to print.

    - kwargs – See print().

  Returns

    None.

`qspec.tools.``printw`(*values, **kwargs)

  Print with the WARNING color (yellow).

  Parameters

    - values – The values to print.

    - kwargs – See print().

  Returns

    None.

`qspec.tools.``roman_to_int`(roman)

  Convert from Roman numerals to an integer [jonrsharpe, https://codereview.stackexchange.com/questions/68297/convert-roman-to-int].

  Parameters

    roman (`str`) – The str representation of a roman number.

  Return type

    `int`

`qspec.tools.``rotation_matrix`(alpha, dr)
  Parameters

    - alpha (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The angle to rotate.

    - dr (`Union`[`ndarray`, `Iterable`]) – The vector to rotate about.

  Returns

    The rotation matrix defined by the angle alpha and the vector dr.

`qspec.tools.``rotation_to_vector`(x, y)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`]) – The first vector.

    - y (`Union`[`ndarray`, `Iterable`]) – The second vector.

  Returns

    A Rotation object which rotates the first vector onto the second.

`qspec.tools.``round_to_n`(x, n)
  Parameters

    - x (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The input data.

    - n (`int`) – The number of significant decimal places to round to.

  Return type

    (typing.Union[int, float], <class ‘int’>)

  Returns

    x rounded to ‘n’ significant decimal places and the corresponding number of decimal places after the decimal point.

`qspec.tools.``transform`(t, vec, axis=- 1)
  Parameters

    - t (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The transformation matrix which must hold t.shape[axis+1] == vec.shape[axis].

    - vec (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The vector to be transformed.

    - axis – The axis along which the vector components of ‘vec’ are aligned and that is summed over.

  Return type

    `Union`[`ndarray`, `Iterable`, `int`, `float`]

  Returns

    The transformed vector vec_new = t * vec.

`qspec.tools.``unit_vector`(indexes, dim, axis=-1, dtype=<class 'float'>)
  Parameters

    - indexes (`Union`[`ndarray`, `Iterable`, `int`, `float`]) – The indexes of the vectors that are filled with a 1.

    - dim (`int`) – The dimension of the unit vectors.

    - axis (`int`) – The axis with the dimension ‘dim’.

    - dtype (`type`) – The data type of the unit vectors.

  Returns

    Unit vectors in the specified ‘indexes’ with dimension ‘dim’ along the specified ‘axis’.