qspec

algebra

qspec.algebra

Module including methods for calculating dipole coefficients.

qspec.algebra.a(i, j_l, f_l, j_u, f_u, as_sympy=False)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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], Union[Integer, Float, Rational, Add, 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)[source]
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:

(Union[Integer, Float, Rational, Add, Mul, float], Union[Integer, Float, Rational, Add, Mul, float], Union[Integer, Float, Rational, Add, 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)[source]
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)[source]
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)[source]
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'>)[source]
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)[source]
\[\langle J_1, m_1, J_2, m_2\, |\, J_3, m_3\rangle\]
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\)

  • m_1 (Union[Integer, Float, Rational, int, float]) – \(m_1\)

  • m_2 (Union[Integer, Float, Rational, int, float]) – \(m_2\)

  • m_3 (Union[Integer, Float, Rational, int, float]) – \(m_3\)

  • 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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
\[\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]) – \(J_1\)

  • j_2 (Union[Integer, Float, Rational, int, float]) – \(J_2\)

  • j_3 (Union[Integer, Float, Rational, int, float]) – \(J_3\)

  • m_1 (Union[Integer, Float, Rational, int, float]) – \(m_1\)

  • m_2 (Union[Integer, Float, Rational, int, float]) – \(m_2\)

  • m_3 (Union[Integer, Float, Rational, int, float]) – \(m_3\)

  • 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)[source]
\[\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.

analyze

qspec.analyze

Module for analyzing/evaluating/fitting data.

Linear regression algorithms (2d):
  • york_fit(); [York et al., Am. J. Phys. 72, 367 (2004)]

  • linear_fit(); 2-dimensional maximum likelihood fit.

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

Linear regression algorithms (nd):
  • linear_nd_fit(); n-dimensional maximum likelihood fit.

  • 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, n_samples=100000, element_label=None)[source]

Bases: object

fit(a, a_ref, x=None, y=None, xy=None, func=<function york_fit>, alpha=0, find_alpha=False, show=True, **kwargs)[source]
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 (Union[str, Callable]) – The fitting routine. Must be one of {‘york_fit’ (default), ‘linear_fit’, ‘linear_monte_carlo’}.

  • 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, optimize_cov=False, func=<function linear_nd_fit>, show=True, **kwargs)[source]
Parameters:
  • a (Union[ndarray, Iterable]) – An Iterable of the mass numbers of the used isotopes with shape (k, ).

  • a_ref (Union[ndarray, Iterable]) – An Iterable of the mass numbers of the used reference isotopes with shape (k, ).

  • x (Union[ndarray, Iterable, None]) – The x data as an iterable of vectors with uncertainties of shape (k, n, 2), where k is the number of data points and n is the number of dimensions of each point.

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

  • optimize_cov (bool) – If True, the origin vector of the straight is optimized to yield the smallest covariances.

  • func (Union[Callable, str]) – The fitting routine. Must be one of {‘linear_nd_fit’, ‘linear_nd_monte_carlo’}.

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

  • kwargs – Additional keyword arguments are passed to ‘func’ and ‘self.plot_nd’.

Returns:

popt, pcov. The optimized parameters and their covariances. The resulting shapes are (2n, ) and (2n, 2n).

get_unmodified(a, a_ref, x, axis=0, show=False, **kwargs)[source]
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.

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

  • axis (int) – The axis of the input values.

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

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

Returns:

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

plot(mode='', sigma2d=1, scale=None, add_xy=None, add_a=None, font_dict=None, show=True, **kwargs)[source]
Parameters:
  • mode (str) – The mode of the King-fit. If mode=’radii’, the x-axis must contain the differences of mean square nuclear charge radii or the Lambda-factor. For every other value, the x-axis is assumed to be an isotope shift such that the slope corresponds to a field-shift ratio F(y_i) / F(x).

  • sigma2d (int) – Whether to draw the actual two-dimensional uncertainty bounds or the classical errorbars. The integer number corresponds to the number of drawn sigma regions.

  • scale (Optional[tuple]) – Factors to scale the x and the y-axis.

  • add_xy (Union[ndarray, Iterable, int, float, None]) – Additional x and y data to plot. Must have shape (n - 1, k, 5), where n is the dimension of the data vectors, k is the number of additional data points and the five entries in the last axis correspond to arrays of the form [x, x_d, y, y_d, corr_xy].

  • add_a (Union[ndarray, Iterable, int, float, None]) – Additional mass numbers for the additional data. Must have shape (k, 2), where each row is a tuple [A, A_ref].

  • font_dict (Optional[dict]) – The font_dict passed to matplotlib.rc(‘font’, font_dict).

  • show (bool) – Whether to show the plot.

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.const(x, a)[source]
Parameters:
  • x (Union[ndarray, Iterable, int, float]) – The x values.

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

Return type:

ndarray

Returns:

A constant function with value ‘a’.

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)[source]
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 ((ndarray, 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)[source]
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)[source]
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)[source]
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:

(ndarray, ndarray)

Returns:

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

qspec.analyze.generate_collinear_points_cpp(mean, cov, n_samples=None, n_accepted=None, seed=None, report=None, **kwargs)[source]
Parameters:
  • mean (ndarray) – The data vectors. Must have shape (k, n), where k is the number of data points and n is the number of dimensions of each point.

  • cov (ndarray) – The covariance matrices of the data vectors. Must have shape (k, n, n). Use ‘covariance_matrix’ to construct covariance matrices.

  • n_samples (Optional[int]) – The number of samples generated for each data point.

  • n_accepted (Optional[int]) – The number of samples to be accepted for each data point.

  • seed (Optional[int]) – A seed for the random number generator.

  • report (Optional[bool]) – Whether to report the number of samples.

  • kwargs – Additional keyword arguments.

Returns:

The randomly generated data vectors p with shape (n_accepted, k ,n) aligned along a straight line and the number of accepted and generated samples.

qspec.analyze.generate_collinear_points_py(mean, cov, n_samples=100000, report=False, **kwargs)[source]
Parameters:
  • mean (ndarray) – The data vectors. Must have shape (k, n), where k is the number of data points and n is the number of dimensions of each point.

  • cov (ndarray) – The covariance matrices of the data vectors. Must have shape (k, n, n). Use ‘covariance_matrix’ to construct covariance matrices.

  • n_samples (int) – The number of samples generated for each data point.

  • report (bool) – Whether to report the number of samples.

  • kwargs – Additional keyword arguments.

Returns:

The randomly generated data vectors p with shape (n_accepted, k ,n) aligned along a straight line and the number of accepted and generated samples.

qspec.analyze.linear_alpha_fit(x, y, sigma_x=None, sigma_y=None, corr=None, func=<function york_fit>, alpha=0, find_alpha=True, report=False, show=False, **kwargs)[source]
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 (Union[Callable, str]) – The fitting routine. Supports {‘york_fit’, ‘linear_fit’, ‘linear_monte_carlo’}.

  • 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 too 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:

popt, pcov, alpha. The best y-intercept and slope, their covariance matrix and the used alpha.

qspec.analyze.linear_fit(x, y, sigma_x=None, sigma_y=None, corr=None, report=False, **kwargs)[source]

Maximum likelihood fit for a straight line in 2d. This is a wrapper for the more general ‘linear_nd_fit’ function.

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.

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

  • kwargs – Additional keyword arguments.

Returns:

popt, pcov. The best y-intercept and slope and their covariance matrix.

qspec.analyze.linear_monte_carlo(x, y, sigma_x=None, sigma_y=None, corr=None, optimize_cov=True, n_samples=None, n_accepted=None, optimize_sampling=True, return_samples=False, method='py', report=True, **kwargs)[source]

Wrapper for linear_nd_monte_carlo.

Parameters:
  • x (Union[ndarray, Iterable]) – The x data. Must be a 1-d array.

  • y (Union[ndarray, Iterable]) – The y data. Must be a 1-d array.

  • sigma_x (Union[ndarray, Iterable, None]) – The 1-sigma uncertainties of the x data. Must be a 1-d array.

  • sigma_y (Union[ndarray, Iterable, None]) – The 1-sigma uncertainties of the y data. Must be a 1-d array.

  • corr (Union[ndarray, Iterable, None]) – The correlation coefficients between the x and y data. Must be a 1-d array.

  • optimize_cov (bool) – If True, the origin vector of the straight is optimized to yield the smallest covariances.

  • n_samples (Optional[int]) – Maximum number of generated samples. If None and method == ‘cpp’, samples are generated until ‘n_accepted’ samples get accepted.

  • n_accepted (Optional[int]) – The number of samples to be accepted for each data point. Only available if method == ‘cpp’.

  • optimize_sampling (bool) – Whether to optimize the sampling from the data.

  • return_samples (bool) – Whether to also return the generated points ‘p’. ‘p’ has shape (n_samples, k ,2).

  • method (str) – The method to generate the collinear points. Can be one of {‘py’, ‘cpp’}. The ‘py’ version is faster but only allows to specify ‘n_samples’. The ‘cpp’ version is slower but allows to specify both ‘n_accepted’ and ‘n_samples’.

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

  • kwargs – Additional keyword arguments.

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_nd_fit(x, cov=None, p0=None, axis=None, optimize_cov=False, **kwargs)[source]
Parameters:
  • x (Union[ndarray, Iterable]) – The data vectors. Must have shape (k, n), where k is the number of data points and n is the number of dimensions of each point.

  • cov (Union[ndarray, Iterable, None]) – The covariance matrices of the data vectors. Must have shape (k, n, n). Use ‘covariance_matrix’ to construct covariance matrices.

  • p0 (Union[ndarray, Iterable, None]) – The start parameters for the linear fit. Must have shape (2n, ). The first n elements specify the origin vector of the straight, the second n elements specify the direction of the straight.

  • axis (Optional[int]) – The component of the n-dimensional vectors which are fixed for fitting. This is required since a straight in n dimensions is fully described by 2 (n - 1) parameters. If None, the best axis is determined from the data and the direction vector of the straight is normalized.

  • optimize_cov (bool) – If True, the origin vector of the straight is optimized to yield the smallest covariances.

  • kwargs – Additional keyword arguments.

Returns:

popt, pcov. The optimized parameters and their covariances. The resulting shapes are (2n, ) and (2n, 2n).

qspec.analyze.linear_nd_monte_carlo(x, cov=None, axis=None, optimize_cov=False, n_samples=None, n_accepted=None, optimize_sampling=True, return_samples=False, method='py', report=False, **kwargs)[source]

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

Parameters:
  • x (Union[ndarray, Iterable]) – The data vectors. Must have shape (k, n), where k is the number of data points and n is the number of dimensions of each point.

  • cov (Union[ndarray, Iterable, None]) – The covariance matrices of the data vectors. Must have shape (k, n, n). Use ‘covariance_matrix’ to construct covariance matrices. If None, samples are generated until n samples get accepted.

  • axis (Optional[int]) – The component of the n-dimensional vectors which are fixed for fitting. This is required since a straight in n dimensions is fully described by 2 (n - 1) parameters.

  • optimize_cov (bool) – If True, the origin vector of the straight is optimized to yield the smallest covariances.

  • n_samples (Optional[int]) – Maximum number of generated samples. If None and method == ‘cpp’, samples are generated until ‘n_accepted’ samples get accepted.

  • n_accepted (Optional[int]) – The number of samples to be accepted for each data point. Only available if method == ‘cpp’.

  • optimize_sampling (bool) – Whether to optimize the sampling from the data.

  • return_samples (bool) – Whether to also return the generated points ‘p’. ‘p’ has shape (n_samples, k ,n).

  • method (str) – The method to generate the collinear points. Can be one of {‘py’, ‘cpp’}. The ‘py’ version is faster but only allows to specify ‘n_samples’. The ‘cpp’ version is slower but allows to specify both ‘n_accepted’ and ‘n_samples’.

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

  • kwargs – Additional keyword arguments to be passed to the chosen method. ‘py’: {}. ‘cpp’: {seed=None}.

Returns:

popt, pcov (, p). The optimized parameters and their covariances. If ‘return_samples’ is True, also returns the generated points ‘p’. The resulting shapes are (2n, ), (2n, 2n) and (n_samples, k ,n).

qspec.analyze.odr_fit(f, x, y, sigma_x=None, sigma_y=None, p0=None, p0_d=None, p0_fixed=None, report=False, **kwargs)[source]
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 – Additional keyword arguments are passed to odr.ODR.

Return type:

(ndarray, ndarray)

Returns:

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

qspec.analyze.poly(x, *args)[source]
Parameters:
  • x – The x values.

  • args – The coefficients of the polynomial.

Returns:

args[0] + args[1] * x + args[2] / 2 * x ** 2 + args[3] / 6 * x ** 3 + …

qspec.analyze.straight(x, a, b)[source]
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_direction(p_0, p_1, axis=-1)[source]
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 direction of a straight line in n dimensions.

qspec.analyze.straight_std(x, sigma_a, sigma_b, corr_ab)[source]
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)[source]
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)[source]
Parameters:

sigma – The 1-sigma uncertainty.

Returns:

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

qspec.analyze.york_fit(x, y, sigma_x=None, sigma_y=None, corr=None, iter_max=200, report=False, show=False, **kwargs)[source]

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:

popt, pcov. The best y-intercept and slope, their covariance matrix and the used alpha.

models

qspec.models

Module for constructing lineshape models.

class qspec.models.Amplifier(order=None)[source]

Bases: Model

A polynomial of order ‘order’.

property dx

A hint for an x-axis step size for a smooth display of the model.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.Convolved(model_0, model_1)[source]

Bases: Model

A general numerical convolution model.

property dx

A hint for an x-axis step size for a smooth display of the model.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

gen_x_int(*args)[source]

Generates x-axis arrays for numerical integration.

Parameters:

args – The function parameters.

Returns:

None.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

set_val(i, val, force=False)[source]

Set a specific parameter value.

Parameters:
  • i – The index of the parameter.

  • val – The new parameter value.

  • force – Force the parameter to take exactly the new value. If False, the parameter is converted to the correct format.

Returns:

None.

class qspec.models.Custom(model=None, parameters=None)[source]

Bases: Model

A model with custom parameters. Without a submodel, Custom returns the user-specified parameters as an array regardless of the input x. Otherwise, simply the submodel is called and the custom parameters can be connected to other parameters by the user.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

class qspec.models.Empty[source]

Bases: Model

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

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

class qspec.models.Gauss[source]

Bases: Spectrum

A Gaussian peak function.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.GaussChi2[source]

Bases: Spectrum

An analytical convolution of a Gaussian with a Boltzmann distribution.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.GaussChi2Convolved(model)[source]

Bases: Convolved

A GaussChi2 convolution kernel.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

class qspec.models.GaussConvolved(model)[source]

Bases: Convolved

A Gaussian convolution kernel.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

class qspec.models.Hyperfine(model, i, j_l, j_u, label=None)[source]

Bases: Splitter

A standard hyperfine structure model.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

racah()[source]

Set the intensity values to the Racah intensities.

Returns:

None.

class qspec.models.HyperfineMixed(model, i, j_l, j_u, name, config)[source]

Bases: Splitter

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

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

racah()[source]

Set the intensity values to the Racah intensities.

Returns:

None.

x0(*args)[source]
Parameters:

args – The function parameters.

Returns:

The peak positions.

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

Bases: Splitter

A perturbative quantum interference (QI) hyperfine structure model based on https://doi.org/10.1103/PhysRevA.87.032504.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

racah()[source]

Set the intensity values to the Racah intensities.

Returns:

None.

class qspec.models.Linked(models)[source]

Bases: Listed

A model linking all “link=True” parameters of the submodels.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

set_fix(i, fix, force=False)[source]

Set a specific parameter fix state.

Parameters:
  • i – The index of the parameter.

  • fix – The new parameter value.

  • force – Force the parameter to take exactly the new fix state. If False, the parameter is converted to the correct format.

Returns:

None.

Set a specific parameter link state.

Parameters:
  • i – The index of the parameter.

  • link – The new parameter link state.

  • force – Force the parameter to take exactly the new link state. If False, the parameter is converted to the correct format.

Returns:

None.

class qspec.models.Listed(models, labels=None)[source]

Bases: Model

An abstract class for models with multiple submodels.

inherit_fixes(force=False)[source]

Inherit the parameter fixes of the submodels.

Parameters:

force – The ‘force’ parameter of ‘self.set_fix’.

Returns:

None

Inherit the parameter links of the submodels.

Parameters:

force – The ‘force’ parameter of ‘self.set_link’.

Returns:

None

inherit_vals(force=False)[source]

Inherit the parameter values of the submodels.

Parameters:

force – The ‘force’ parameter of ‘self.set_val’.

Returns:

None

set_fix(i, fix, force=False)[source]

Set a specific parameter fix state.

Parameters:
  • i – The index of the parameter.

  • fix – The new parameter value.

  • force – Force the parameter to take exactly the new fix state. If False, the parameter is converted to the correct format.

Returns:

None.

Set a specific parameter link state.

Parameters:
  • i – The index of the parameter.

  • link – The new parameter link state.

  • force – Force the parameter to take exactly the new link state. If False, the parameter is converted to the correct format.

Returns:

None.

set_val(i, val, force=False)[source]

Set a specific parameter value.

Parameters:
  • i – The index of the parameter.

  • val – The new parameter value.

  • force – Force the parameter to take exactly the new value. If False, the parameter is converted to the correct format.

Returns:

None.

class qspec.models.Lorentz[source]

Bases: Spectrum

A Lorentzian peak function.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.LorentzConvolved(model)[source]

Bases: Convolved

A Lorentzian convolution kernel.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

class qspec.models.LorentzQI[source]

Bases: Spectrum

A Lorentzian peak function including a dispersive term for consideration of quantum interference (QI) effects.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

evaluate_qi(x, x_qi, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • x_qi – The x value of the interfering Lorentzian.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results of the dispersive Lorentzian at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.Model(model=None)[source]

Bases: object

Base class for all models.

property description

A description of the model hierarchy.

property dx

A hint for an x-axis step size for a smooth display of the model.

property error

An error message if there is an issue with the model parameters (not implemented).

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fit_prepare()[source]
Returns:

fixed, bounds. A list of bool values which parameters are not varied in a fit and a list of bounds for the fit parameters. See parameters ‘p0_fixed’ and ‘bounds’ of ‘qspec.curve_fit’.

get_pars()[source]
Returns:

A zip-iterator over (names, vals, fixes, links).

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

property model

The submodel.

set_fix(i, fix, force=False)[source]

Set a specific parameter fix state.

Parameters:
  • i – The index of the parameter.

  • fix – The new parameter value.

  • force – Force the parameter to take exactly the new fix state. If False, the parameter is converted to the correct format.

Returns:

None.

set_fixes(fixes, force=False)[source]

Set all fixes with one list.

Parameters:
  • fixes – A list of shape (self.size, ).

  • force – The ‘force’ parameter of the ‘set_fix’ function.

Returns:

None.

Set a specific parameter link state.

Parameters:
  • i – The index of the parameter.

  • link – The new parameter link state.

  • force – Force the parameter to take exactly the new link state. If False, the parameter is converted to the correct format.

Returns:

None.

Set all links with one list.

Parameters:
  • links – A list of shape (self.size, ).

  • force – The ‘force’ parameter of the ‘set_link’ function.

Returns:

None.

set_pars(pars, force=False)[source]

Set all vals, fixes and links with one nested list.

Parameters:
  • pars – A nested list of shape (self.size, 3).

  • force – The ‘force’ parameter of the ‘set_val’, ‘set_fix’ and ‘set_link’ functions.

Returns:

None.

set_val(i, val, force=False)[source]

Set a specific parameter value.

Parameters:
  • i – The index of the parameter.

  • val – The new parameter value.

  • force – Force the parameter to take exactly the new value. If False, the parameter is converted to the correct format.

Returns:

None.

set_vals(vals, force=False)[source]

Set all vals with one list.

Parameters:
  • vals – A list of shape (self.size, ).

  • force – The ‘force’ parameter of the ‘set_val’ function.

Returns:

None.

property size

The number of parameters required by the model.

update()[source]

Updates self.vals with updated parameters, see self.update_args.

Returns:

None.

update_args(args)[source]
Parameters:

args – The parameters.

Returns:

the parameters updated with the parameter expressions.

x()[source]
Returns:

An array of x values for a complete and smooth display of the model.

class qspec.models.NPeak(model, n_peaks=1)[source]

Bases: Model

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

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.Offset(model=None, x_cuts=None, offsets=None)[source]

Bases: Model

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

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

gen_offset_map()[source]

Generate the offset parameters and a map of the interval and polynomial order to the parameter index space.

Returns:

None.

gen_offset_masks(x)[source]

Generate the array masks corresponding to the ‘x_cuts’.

Parameters:

x – The input values.

Returns:

None.

guess_offset(x, y)[source]

Guess the first two polynomial orders for a given data set.

Parameters:
  • x – The input values.

  • y – The y data.

Returns:

None.

set_x_cuts(x_cuts)[source]

Set the values where to cut the x-axis into intervals with individual offset parameters.

Parameters:

x_cuts – A list of x values.

Returns:

None.

class qspec.models.Spectrum[source]

Bases: Model

property dx

A hint for an x-axis step size for a smooth display of the model.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.Splitter(model, i, j_l, j_u, label=None)[source]

Bases: Model

The abstract base class for Hyperfine structure models.

racah()[source]

Set the intensity values to the Racah intensities.

Returns:

None.

class qspec.models.SplitterSummed(splitter_models)[source]

Bases: Summed

A sum of ‘Splitter’ models.

racah()[source]
class qspec.models.Summed(models, labels=None)[source]

Bases: Listed

A model summing over all submodels.

property dx

A hint for an x-axis step size for a smooth display of the model.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

intervals()[source]
Returns:

A list of x-axis intervals for a complete display of the model.

max()[source]
Returns:

A hint for an x-axis maximum for a complete display of the model.

min()[source]
Returns:

A hint for an x-axis minimum for a complete display of the model.

class qspec.models.Voigt[source]

Bases: Spectrum

A Voigt peak function.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

class qspec.models.VoigtAsy[source]

Bases: Spectrum

An asymmetric Voigt peak function.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

class qspec.models.VoigtCEC[source]

Bases: Spectrum

A series of Voigt peak functions.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

class qspec.models.VoigtDerivative[source]

Bases: Spectrum

A differential Voigt peak function.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

fwhm()[source]
Returns:

The full width at half maximum (FWHM) of a spectrum.

class qspec.models.YPars(model)[source]

Bases: Model

Concatenates the parameters of the submodel with uncertainties as fix states with the y-axis array resulting

from calling the submodel. This is used internally in ‘qspec.models.fit’.

evaluate(x, *args, **kwargs)[source]
Parameters:
  • x – The input values.

  • args – The function parameters. Must have length self.size.

  • kwargs – Additional keyword arguments.

Returns:

The function results at the input values ‘x’.

qspec.models.find_model(model, sub_model)[source]
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)[source]
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)[source]
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)[source]
Parameters:
  • gamma – The FWHM of the Lorentzian.

  • sigma – The standard deviation of the Gaussian.

Returns:

The FWHM of a Voigt profile.

qspec.models.fwhm_voigt_d(gamma, gamma_d, sigma, sigma_d)[source]
Parameters:
  • gamma – The FWHM of the Lorentzian.

  • gamma_d – The uncertainty of ‘gamma’.

  • sigma – The standard deviation of the Gaussian.

  • sigma_d – The uncertainty of ‘sigma’.

Returns:

The uncertainty of the FWHM of a Voigt profile.

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

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)[source]
Parameters:
  • qi (bool) – Whether to consider QI effects.

  • hf_mixing (bool) – Whether to consider HF mixing.

Returns:

The appropriate ‘Splitter’ model.

qspec.models.get_all_f(i, j)[source]
Parameters:
  • i – The nuclear spin.

  • j – The total electron angular momentum.

Returns:

All possible F quantum numbers of an electronic finestructure state.

qspec.models.hf_coeff(i, j, f)[source]
Parameters:
  • i – The nuclear spin.

  • j – The total electron angular momentum.

  • f – The total angular momentum.

Returns:

The tuple of hyperfine coefficients for A and B-factors of a given quantum state

qspec.models.hf_int(i, j_l, j_u, transitions)[source]
Parameters:
  • i – The nuclear spin.

  • j_l – The total lower state electron angular momentum.

  • j_u – The total upper state electron angular momentum.

  • transitions – A list of electronic transition properties. The first two properties of each entry should be f_l and f_u the total angular momenta of lower and upper state.

Returns:

The relative line intensities.

qspec.models.hf_shift(hyper_l, hyper_u, coeff_l, coeff_u)[source]
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)[source]

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)[source]
qspec.models.residuals(model, x, y)[source]
qspec.models.sigma_poisson(x, y, y_model, *params)[source]

physics

qspec.physics

Module for physical functions useful for CLS.

qspec.physics.a_hyper_mu(i, j, mu, b)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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')[source]
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)[source]
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')[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
Parameters:

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

Returns:

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

qspec.physics.freq_to_wavelength(freq)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
Parameters:

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

Returns:

The frequency corresponding to the wavenumber k (MHz).

qspec.physics.inv_cm_to_wavelength(k)[source]
Parameters:

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

Returns:

The wavelength corresponding to the wavenumber k (um).

qspec.physics.inverse_doppler(f_atom, f_lab, alpha, mode='raise-raise', return_mask=False)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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:

(ndarray, 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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
qspec.physics.sellmeier(w, a, b)[source]
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)[source]
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.t_xi(xi, f, u, q, m)[source]
Parameters:
  • xi – The acceleration/bunching parameter xi (MHz).

  • f – The rest-frame transition frequency (MHz).

  • u – The acceleration voltage (V).

  • q – The charge of the ions (e).

  • m – The mass of the ensembles bodies (u).

Returns:

The temperature of an ensemble of ions with acceleration/bunching parameter xi (K).

qspec.physics.thermal_e_pdf(e, t)[source]
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)[source]
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)[source]
Parameters:
  • v (Union[ndarray, Iterable, int, float]) – velocity quantiles (m/s).

  • m (Union[ndarray, Iterable, int, float]) – The mass of the ensembles bodies (u).

  • 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)[source]
Parameters:
  • m (Union[ndarray, Iterable, int, float]) – The mass of the ensembles bodies (u).

  • 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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
Parameters:

lam (Union[ndarray, Iterable, int, float]) – The wavelength lambda of a transition (um)

Returns:

The wavenumber k corresponding to the wavelength lam (1/cm).

qspec.physics.zeeman(m, b, g, as_freq=True)[source]
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).

simulate

qspec.simulate

Module for simulations of laser-atom interactions.

class qspec.simulate.Atom(states=None, decay_map=None, mass=0, instance=None)[source]

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)[source]
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)[source]
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.

get_y0_mc(n_samples=None, ground_state_labels=None)[source]
Parameters:
  • n_samples (Optional[int]) – The number of samples to create.

  • 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 for the Monte-Carlo master equation solver.

property gs: 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)[source]

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)[source]

Scattering rate of the atom into the direction

e_r = (sin(theta), cos(theta) * sin(phi), cos(theta) * cos(phi))

where the z-axis is the quantization axis, which is either (0, 0, 1) or the B-field axis.

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 relative to the quantization axis.

  • phi (Union[ndarray, Iterable, int, float, None]) – The azimuthal angle of detection relative to the quantization axis.

  • 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()[source]

Update the atom.

Returns:

None.

class qspec.simulate.DecayMap(labels=None, a=None, instance=None)[source]

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)[source]
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)[source]

Bases: object

Class representing an electromagnetic environment.

property B
property E
class qspec.simulate.Geometry[source]

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)[source]
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:

(list, 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)[source]

Shows a 3d plot of the angular range covered by the geometry object. :returns: The axes object.

set_intervals(theta, phi)[source]
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)[source]
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)[source]
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)[source]
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=True, instance=None)[source]

Bases: object

Class representing an Interaction between lasers and an atom.

property atol
Returns:

The absolute error tolerance of controlled solver.

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 dense
Returns:

Whether the ODE solver uses an error controlled dense output stepper. If True, this overrides the controlled flag. 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 dt
Returns:

The (initial) step size of (controlled) solvers.

property dt_max
Returns:

The maximum step size of controlled solvers.

property environment
Returns:

The environment of the interaction.

get_delta()[source]
get_rabi(m=None)[source]
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’).

hamiltonian(t, delta=None, m=0, v=None)[source]
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.

Returns:

The integrated master equation as a complex-valued array of shape (n, #states, #states, #times).

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)[source]

Solver for the master equation. Solutions for n samples can be calculated in parallel.

Parameters:
  • t (Union[ndarray, Iterable, int, float]) – The times when to compute the solution (us).

  • delta (Union[ndarray, Iterable, int, float, None]) – An array of frequency shifts for the laser(s) (MHz). ‘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 (m/s). Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) is(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, ), (n or 1, #states) or (n or 1, #states, #states). If #states == n, it is interpreted as (n, #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, as_density_matrix=False)[source]

Solver for the Monte-Carlo master equation. Solutions for n samples can be calculated in parallel.

Parameters:
  • t (Union[ndarray, Iterable, int, float]) – The times when to compute the solution (us).

  • delta (Union[ndarray, Iterable, int, float, None]) – An array of frequency shifts for the laser(s) (MHz). ‘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 (m/s). Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) is(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’.

  • as_density_matrix (bool) – Whether the result is returned as density matrices or as state vectors.

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)[source]

Solver for the rate equations. Solutions for n samples can be calculated in parallel.

Parameters:
  • t (Union[ndarray, Iterable, int, float]) – The times when to compute the solution (us).

  • delta (Union[ndarray, Iterable, int, float, None]) – An array of frequency shifts for the laser(s) (MHz). ‘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 (m/s). Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) is(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 (#states, ) or (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()[source]

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.

property rtol
Returns:

The relative error tolerance of controlled solver.

scattering_rate(rho, theta=None, phi=None, as_density_matrix=True, i=None, j=None, axis=1)[source]

Scattering rate of the atom into the direction

e_r = (sin(theta), cos(theta) * sin(phi), cos(theta) * cos(phi))

where the z-axis is the quantization axis, which is either (0, 0, 1) or the B-field axis.

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 relative to the quantization axis.

  • phi (Union[ndarray, Iterable, int, float, None]) – The azimuthal angle of detection relative to the quantization axis.

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

schroedinger(t, delta=None, m=0, v=None, y0=None)[source]

Solver for the Schroedinger equation. Solutions for n samples can be calculated in parallel.

Parameters:
  • t (Union[ndarray, Iterable, int, float]) – The times when to compute the solution (us).

  • delta (Union[ndarray, Iterable, int, float, None]) – An array of frequency shifts for the laser(s) (MHz). ‘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 (m/s). Must be a scalar or have shape (n, ) or (n, 3). In the first two cases, the velocity vector(s) is(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()[source]

Updates the Interaction.

Returns:

None.

class qspec.simulate.Laser(freq, intensity=1.0, polarization=None, k=None, instance=None)[source]

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)[source]

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)[source]

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: ndarray
Returns:

The complex polarization in spherical coordinates ( sigma-, pi, sigma+ ).

property q_axis: ndarray
Returns:

The complex polarization in spherical coordinates ( sigma-, pi, sigma+ ).

property x: ndarray
Returns:

The complex polarization in cartesian coordinates ( x, y, z ).

class qspec.simulate.ScatteringRate(atom, laser=None, i_decay=0, geometry=None, b=None)[source]

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()[source]

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()[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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()[source]
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)[source]
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)[source]
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)[source]
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_laser(laser=None)[source]
set_polarization(polarization=None)[source]
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()[source]

Define lower and upper states.

Returns:

None.

set_x0()[source]
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)[source]

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()[source]
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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.

stats

qspec.stats

Module for doing statistical analysis.

class qspec.stats.Observable(x, std=None, std_2=None, label=None)[source]

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)[source]
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()[source]
Return type:

Callable

Returns:

The probability distribution function (pdf) of the observable.

rvs(size=1)[source]
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)[source]
Parameters:

popt (Union[ndarray, Iterable, int, float, None]) – The new value of ‘popt’.

Returns:

None. Sets the ‘popt’ attribute.

qspec.stats.add(a, b)[source]
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)[source]
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:

(ndarray, 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)[source]
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)[source]
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()[source]

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)[source]
Parameters:
  • a (Union[ndarray, Iterable, int, float]) – The sample data.

  • axis (Optional[int]) – The axis along which the three percentiles are computed.

Return type:

(ndarray, ndarray, 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.mode_lognormal(x, bins=100)[source]
qspec.stats.mul(a, b)[source]
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)[source]
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:

(Observable, list, 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)[source]
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)[source]
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)[source]
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)[source]
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.

tools

qspec.tools

Module including mathematical and technical methods.

class qspec.tools.COLORS[source]

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)[source]

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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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'>)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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.

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)[source]
Parameters:

a (dict) – A dictionary.

Return type:

(list, 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)[source]
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)[source]
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)[source]
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)[source]
Parameters:

x (float) – A float value.

Return type:

int

Returns:

The closest even integer value.

qspec.tools.factorial(n)[source]
Parameters:

n (Union[ndarray, Iterable, int, float]) – The integer number.

Returns:

n! (array compatible).

qspec.tools.floor_log10(x)[source]
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)[source]
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)[source]
Parameters:

r (Union[Rational, str]) – A sympy.Rational or a str with the signature “‘num’/’denom’”.

Return type:

(int, int)

Returns:

the numerator and denominator of ‘r’.

qspec.tools.get_config_dict()[source]
Return type:

dict

Returns:

A dictionary containing the content of the currently used config file.

qspec.tools.get_decimals(x)[source]
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()[source]
Returns:

The absolute path to the “PyCLS user folder.”

qspec.tools.get_rgb_print_command(r, g, b)[source]
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)[source]
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:

(float, float)

Returns:

The value and its uncertainty.

qspec.tools.half_integer_to_fraction(val)[source]
Parameters:

val (Union[int, float]) – A scalar value.

Return type:

(int, int)

Returns:

The numerator and denominator of the half-integer.

qspec.tools.half_integer_to_str(val, symbol='_')[source]
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)[source]
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)[source]
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)[source]
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')[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
Parameters:

y (Union[ndarray, Iterable, int, float]) – An array like value.

Return type:

(ndarray, Callable)

Returns:

The mask where y is NaN and a function which returns the nonzero indices of an array.

qspec.tools.odd(x)[source]
Parameters:

x (float) – A float value.

Return type:

int

Returns:

The closest odd integer value.

qspec.tools.orthonormal(r, axis=-1)[source]
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:

(Union[ndarray, Iterable, int, float], Union[ndarray, Iterable, int, float], Union[ndarray, Iterable, int, float])

Returns:

Three orthonormal vectors, given the first vector ‘r’.

qspec.tools.orthonormal_rtp(r, axis=-1)[source]
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:

(Union[ndarray, Iterable, int, float], Union[ndarray, Iterable, int, float], Union[ndarray, 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)[source]

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)[source]

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)[source]

Print with the FAIL color (red).

Parameters:
  • values – The values to print.

  • kwargs – See print().

Returns:

None.

qspec.tools.printh(*values, **kwargs)[source]

Print with the HEADER color (pink).

Parameters:
  • values – The values to print.

  • kwargs – See print().

Returns:

None.

qspec.tools.printw(*values, **kwargs)[source]

Print with the WARNING color (yellow).

Parameters:
  • values – The values to print.

  • kwargs – See print().

Returns:

None.

qspec.tools.roman_to_int(roman)[source]

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)[source]
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)[source]
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)[source]
Parameters:
  • x (Union[ndarray, Iterable, int, float]) – The input data.

  • n (int) – The number of significant decimal places to round to.

Return type:

(Union[int, float], 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)[source]
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'>)[source]
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’.