skultrafast.dataset

Module Contents

Classes

Functions

delegator(→ Callable[Ellipsis, Optional[PolTRSpec]])

Helper function to delegate methods calls from PolTRSpec to

Attributes

skultrafast.dataset.ndarray: Type[numpy.ndarray][source]
skultrafast.dataset.EstDispResult[source]
class skultrafast.dataset.FitExpResult[source]
lmfit_mini: lmfit.Minimizer[source]
lmfit_res: lmfit.minimizer.MinimizerResult[source]
fitter: FitExpResult.fitter[source]
pol_resolved: bool = False[source]
std_errs: numpy.ndarray | None[source]
var: numpy.ndarray | None[source]
r2: numpy.ndarray | None[source]
calculate_stats()[source]
make_sas(model: skultrafast.kinetic_model.Model, QYs: Dict[str, float] = {}, y0: numpy.ndarray | None = None)[source]

Generate the species associated spectra from a given model using the current das.

Parameters:
  • model (Model) – Model describing the kinetics. The number of transition rates should be identical to the number of DAS-rates. Currtenly, the function assumes that the transitions are added in a sorted way, e.g. fastest rates first.

  • QYs (dict) – Values for the yields.

  • y0 (ndarray) – Starting concentrations. If none, y0 = [1, 0, 0, …].

Return type:

ndarry

class skultrafast.dataset.LDMResult[source]
skmodel: object[source]
coefs: numpy.ndarray[source]
fit: numpy.ndarray[source]
alpha: numpy.ndarray[source]
class skultrafast.dataset.TimeResSpec(wl, t, data, err=None, name=None, freq_unit='nm', disp_freq_unit=None, auto_plot=True)[source]
property wavelengths[source]
property wavenumbers[source]
__iter__()[source]

For compatibility with dv.tup

wl_d(wl: float)[source]

Returns the nearest transient for given wavelength.

wn_i(wn1, wn2, method='trapz')[source]

Integrates the signal from wn1 to wn2

Parameters:
  • wn1 – Wavenumber of the first edge

  • float – Wavenumber of the first edge

  • wn2 – Wavenumber of the second edge

  • float – Wavenumber of the second edge

  • method – Method used to integrate.

  • ('trapz' – Method used to integrate.

  • 'spline') – Method used to integrate.

wn_d(wn: float)[source]

Returns the nearest transient for given wavenumber.

t_d(t)[source]

Returns the nearest spectrum for given delaytime.

copy() TimeResSpec[source]

Returns a copy of the TimeResSpec.

classmethod from_txt(fname, freq_unit='nm', time_div=1.0, transpose=False, disp_freq_unit=None, loadtxt_kws=None)[source]

Directly create a dataset from a text file.

Parameters:
  • fname (str) – Name of the file. This function assumes the data is given by a (n+1, m+1) table. Excludig the [0, 0] value, the first row gives the frequencies and the first column gives the delay-times.

  • freq_unit ({'nm', 'cm'}) – Unit of the frequencies.

  • time_div (float) – Since skultrafast prefers to work with picoseconds and programs may use different units, it divides the time-values by time_div. Use 1, the default, to not change the time values.

  • transpose (bool) – Transposes the loaded array.

  • disp_freq_unit (Optional[str]) – See class documentation.

  • loadtxt_kws (dict) – Dict containing keyword arguments to np.loadtxt.

save_txt(fname, freq_unit='wl')[source]

Saves the dataset as a text file.

Parameters:
  • fname (str) – Filename (can include path)

  • freq_unit ('nm' or 'cm' (default 'nm')) – Which frequency unit is used.

cut_freq(lower=-np.inf, upper=np.inf, invert_sel=False, freq_unit=None) TimeResSpec[source]

Removes channels inside (or outside ) of given frequency ranges.

Parameters:
  • lower (float) – Lower bound of the region

  • upper (float) – Upper bound of the region

  • invert_sel (bool) – Invert the final selection.

  • freq_unit ('nm', 'cm' or None) – Unit of the given edges.

Returns:

TimeResSpec containing only the listed regions.

Return type:

TimeResSpec

mask_freq_idx(idx)[source]

Masks given freq idx array

Parameters:

idx (array) – Boolean array, same shape as the freqs. Where it is True, the freqs will be masked.

mask_freqs(freq_ranges, invert_sel=False, freq_unit=None)[source]

Mask channels inside of given frequency ranges.

Parameters:
  • freq_ranges (list of (float, float)) – List containing the edges (lower, upper) of the frequencies to keep.

  • invert_sel (bool) – When True, it inverts the selection. Can be used mark everything outside selected ranges.

  • freq_unit ('nm', 'cm' or None) – Unit of the given edges.

Return type:

None

cut_time(lower=-np.inf, upper=np.inf, invert_sel=False) TimeResSpec[source]

Remove spectra inside (or outside) of given time-ranges.

Parameters:
  • lower (float) – Lower bound of the region

  • upper (float) – Upper bound of the region

  • invert_sel (bool) – Inverts the final selection.

Returns:

TimeResSpec containing only the requested regions.

Return type:

TimeResSpec

scale_and_shift(scale: float = 1, t_shift: float = 0, wl_shift: float = 0) TimeResSpec[source]

Return a dataset which is scaled and/or has shifted times and frequencies.

scalefloat

Scales the whole dataset by given factor.

t_shiftfloat

Shifts the time-axis of an dataset.

wl_shiftfloat

Shifts the wavelengths axis and updates the wavenumbers too.

Returns:

A modified new dataset

Return type:

TimeResSpec

mask_times(time_ranges, invert_sel=False)[source]

Mask spectra inside (or outside) of given time-ranges.

Parameters:
  • time_ranges (list of (float, float)) – List containing the edges of the time-regions to keep.

  • invert_sel (bool) – Invert the selection.

Return type:

None

subtract_background(n: int = 10)[source]

Subtracts the first n-spectra from the dataset

bin_freqs(n: int, freq_unit=None, use_err: bool = True) TimeResSpec[source]

Bins down the dataset by averaging over several transients.

Parameters:
  • n (int) – The number of bins. The edges are calculated by np.linspace(freq.min(), freq.max(), n+1).

  • freq_unit ('nm', 'cm' or None) – Whether to calculate the bin-borders in frequency- of wavelength space. If None, it defaults to self.disp_freq_unit.

  • use_err (bool) – If true, use error for weighting.

Returns:

Binned down TimeResSpec

Return type:

TimeResSpec

bin_times(n, start_index=0) TimeResSpec[source]

Bins down the dataset by binning n sequential spectra together.

Parameters:
  • n (int) – How many spectra are binned together.

  • start_index (int) – Determines the starting index of the binning

Returns:

Binned down TimeResSpec

Return type:

TimeResSpec

estimate_dispersion(heuristic='abs', heuristic_args=(), deg: int = 2, shift_result: float = 0, t_parameter: float = 1.3)[source]

Estimates the dispersion from a dataset by first applying a heuristic to each channel. The results are than robustly fitted with a polynomial of given order.

Parameters:
  • heuristic ({'abs', 'diff', 'gauss_diff', 'max'} or func) – Determines which heuristic to use on each channel. Can also be a function which follows func(t, y, *args) and returns a `t0-value. The heuristics are described in zero_finding.

  • heuristic_args (tuple) – Arguments which are given to the heuristic.

  • deg (int (optional)) – Degree of the polynomial used to fit the dispersion (defaults to 2).

  • shift_result (float) – The resulting dispersion curve is shifted by this value. Default 0.

  • t_parameter (float) – Determines the robustness of the fit. See statsmodels documentation for more info.

Returns:

Tuple containing the dispersion corrected version of the dataset, an array with time-zeros from the heuristic, and the polynomial function resulting from the robust fit.

Return type:

EstDispResult

interpolate_disp(polyfunc: Callable | Iterable) TimeResSpec[source]

Correct for dispersion by linear interpolation .

Parameters:

polyfunc (Union[Callable, Iterable]) – Function which takes wavenumbers and returns time-zeros.

Returns:

New TimeResSpec where the data is interpolated so that all channels have the same delay point.

Return type:

TimeResSpec

fit_exp(x0, fix_sigma=True, fix_t0=True, fix_last_decay=True, model_coh=False, lower_bound=0.1, verbose=True, use_error=False, fixed_names=None, from_t=None)[source]

Fit a sum of exponentials to the dataset. This function assumes the dataset is already corrected for dispersion.

Parameters:
  • x0 (list of floats or array) – Starting values of the fit. The first value is the estimate of the system response time omega. If fit_t0 is true, the second float is the guess of the time-zero. All other floats are interpreted as the guessing values for exponential decays.

  • fix_sigma (bool (optional)) – If to fix the IRF duration sigma.

  • fix_t0 (bool (optional)) – If to fix the the time-zero.

  • fix_last_decay (bool (optional)) – Fixes the value of the last tau of the initial guess. It can be used to add a constant by setting the last tau to a large value and fix it.

  • model_coh (bool (optional)) – If coherent contributions should by modeled. If True a gaussian with a width equal the system response time and its derivatives are added to the linear model.

  • lower_bound (float (optional)) – Lower bound for decay-constants.

  • verbose (bool) – Prints the results out if True.

  • use_error (bool) – If the errors are used in the fit.

  • fixed_names (list of str) – Can be used to fix time-constants

  • from_t (float or None) – Can be used to cut of early times.

lifetime_density_map(taus=None, alpha=0.0001, cv=True, maxiter=30000, **kwargs)[source]

Calculates the LDM from a dataset by regularized regression.

Parameters:
  • taus (array or None) – List with potential decays for building the basis. If None, use automatic determination.

  • alpha (float) – The regularization factor.

  • cv (bool) – If to apply cross-validation, by default True.

concat_datasets(other_ds)[source]

Merge the dataset with another dataset. The other dataset need to have the same time axis.

Parameters:

other_ds (TimeResSpec) – The dataset to merge with

Returns:

The merged dataset.

Return type:

TimeResSpec

merge_nearby_channels(distance: float = 8, use_err: bool = False) TimeResSpec[source]

Merges sequetential channels together if their distance is smaller than given.

Parameters:
  • distance (float, optional) – The minimal distance allowed between two channels. If smaller, they will be merged together, by default 8.

  • use_err (bool)

Returns:

The merged dataset.

Return type:

TimeResSpec

apply_filter(kind, args) TimeResSpec[source]

Apply a filter to the data. Will always return a copy of the data.

Returns:

  • kind (callable or in (‘svd’, ‘uniform’, ‘gaussian’)) – What kind of filter to use. Either a string indicating a inbuild filter or a callable.

  • args (any) – Argument to the filter. Depends on the kind.

class skultrafast.dataset.PolTRSpec(para: TimeResSpec, perp: TimeResSpec, iso: TimeResSpec | None = None)[source]
copy() PolTRSpec[source]
wl_d(wl)[source]
wn_d(wn)[source]
t_d(t)[source]
fit_exp(x0, fix_sigma=True, fix_t0=True, fix_last_decay=True, from_t=None, model_coh=False, lower_bound=0.1, use_error=False, fixed_names=None) FitExpResult[source]

Fit a sum of exponentials to the dataset. This function assumes the two datasets is already corrected for dispersion.

Parameters:
  • x0 (list of floats or array) –

    Starting values of the fit. The first value is the guess of the time-zero. The second value is the estimate of the system response time omega. If fit_t0 is true, All other floats are interpreted as the guessing values

    for exponential decays.

  • fix_sigma (bool (optional)) – If to fix the IRF duration sigma.

  • fix_t0 (bool (optional)) – If to fix the the time-zero.

  • fix_last_decay (bool (optional)) – Fixes the value of the last tau of the initial guess. It can be used to add a constant by setting the last tau to a large value and fix it.

  • from_t (float or None) – If not None, data with t<from_t will be ignored for the fit.

  • model_coh (bool (optional)) – If coherent contributions should by modeled. If True a gaussian with a width equal the system response time and its derivatives are added to the linear model.

  • lower_bound (float (optional)) – Lower bound for decay-constants.

  • use_error (bool) – Wether to use the error to weight the residuals

  • fixed_names (list of str) – Can be used to fix names.

save_txt(fname, freq_unit='wl')[source]

Saves the dataset as a text file.

Parameters:
  • fname (str) – Filename (can include path). This functions adds _para.txt and ‘_perp.txt’ for the corresponding dataset to the fname.

  • freq_unit ('nm' or 'cm' (default 'nm')) – Which frequency unit is used.

concat_datasets(other_ds: PolTRSpec)[source]
skultrafast.dataset.delegator(pol_tr: PolTRSpec, method: Callable) Callable[Ellipsis, PolTRSpec | None][source]

Helper function to delegate methods calls from PolTRSpec to the methods of TimeResSpec.

Parameters:
  • pol_tr (PolTRSpec)

  • method (method of TimeResSpec) – The method to wrap. Uses function annotations to check if the method returns a new TimeResSpec.

class skultrafast.dataset.PlotterMixin[source]
property x[source]
lbl_spec(ax=None, add_legend=True)[source]
upsample_spec(y, kind='cubic', factor=4)[source]
univariate_spline(y)[source]
class skultrafast.dataset.TimeResSpecPlotter(dataset: TimeResSpec, disp_freq_unit='nm')[source]

Bases: PlotterMixin

_ds_name = 'self.pol_ds.para'[source]
_get_wl()[source]
_get_wn()[source]
map(symlog=True, equal_limits=True, plot_con=True, con_step=None, con_filter=None, ax=None, **kwargs)[source]

Plot a colormap of the dataset with optional contour lines.

Parameters:
  • symlog (bool) – Determines if the yscale is symmetric logarithmic.

  • equal_limits (bool) – If true, it makes to colors symmetric around zeros. Note this also sets the middle of the colormap to zero. Default is True.

  • plot_con (bool) – Plot additional contour lines if True (default).

  • con_step (float, array or None) – Controls the contour-levels. If con_step is a float, it is used as the step size between two levels. If it is an array, its elements are the levels. If None, it defaults to 20 levels.

  • con_filter (None, int or TimeResSpec.) – Since contours are strongly affected by noise, it can be prefered to filter the dataset before calculating the contours. If con_filter is a dataset, the data of that set will be used for the contours. If it is a tuple of int, the data will be filtered with an uniform filter before calculation the contours. If None, no data prepossessing will be applied.

  • ax (plt.Axis or None) – Takes a matplotlib axis. If none, it uses plt.gca() to get the current axes. The lines are plotted in this axis.

spec(*args, norm=False, ax=None, n_average=0, upsample=1, use_weights=False, offset=0.0, add_legend=False, **kwargs)[source]

Plot spectra at given times.

Parameters:
  • *args (list or ndarray) – List of the times where the spectra are plotted.

  • norm (bool or float) – If true, each spectral will be normalized. If given a float, each spectrum will be normalized to given position.

  • ax (plt.Axis or None.) – Axis where the spectra are plotted. If none, the current axis will be used.

  • n_average (int) – For noisy data it may be preferred to average multiple spectra together. This function plots the average of n_average spectra around the specific time-points.

  • upsample (int,) – If upsample is >1, it will plot an upsampled version of the spectrum using cubic spline interplotation.

  • use_weights (bool) – If given a tuple, the function will plot the average of the given range. use_weights determines if error weights are in calculating the average.

  • offset (float or 'auto') – If non-zero, each spectrum will be shifted by ‘offset’ relatively to the last one. ‘auto’ is not yet implemented.

  • add_offset (bool) – Weather to add an legend

Returns:

List containing the Line2D objects belonging to the spectra.

Return type:

list of Lines2D

trans_integrals(*args, symlog: bool = True, norm=False, ax=None, **kwargs) List[matplotlib.pyplot.Line2D][source]

Plot the transients of integrated region. The integration will use np.trapz in wavenumber-space.

Parameters:
  • args (tuples of floats) – Tuple of wavenumbers determining the region to be integrated.

  • symlog (bool) – If to use a symlog scale for the delay-time.

  • norm (bool or float) – If true, normalize to transients. If it is a float, the transients are normalzied to value at the delaytime norm.

  • ax (plt.Axes or None) – Takes a matplotlib axes. If none, it uses plt.gca() to get the current axes. The lines are plotted in this ax

  • kwargs (Further arguments passed to plt.plot)

Returns:

List containing the plotted lines.

Return type:

list of Line2D

trans(*args, symlog=True, norm=False, ax=None, freq_unit='auto', linscale=1, add_legend=True, **kwargs)[source]

Plot the nearest transients for given frequencies.

Parameters:
  • *args (list or ndarray) – Spectral positions, should be given in the same unit as self.freq_unit.

  • symlog (bool) – Determines if the x-scale is symlog.

  • norm (bool or float) – If False, no normalization is used. If True, each transient is divided by the maximum absolute value. If norm is a float, all transient are normalized by their signal at the time norm.

  • ax (plt.Axes or None) – Takes a matplotlib axes. If none, it uses plt.gca() to get the current axes. The lines are plotted in this axis.

  • freq_unit ('auto', 'cm' or 'nm') – How to interpret the given frequencies. If ‘auto’ it defaults to the plotters freq_unit.

  • linscale (float) – If symlog is True, determines the ratio of linear to log-space.

  • add_legend (bool) – If to add the legend automatically.

  • function. (All other kwargs are forwarded to the plot)

Returns:

List containing the plotted lines.

Return type:

list of Line2D

trans_fit(*args, symlog=True, freq_unit='auto', add_legend=True, ax=None, **kwargs)[source]

Plot the nearest transients for given frequencies.

Parameters:
  • *args (list or ndarray) – Spectral positions, should be given in the same unit as self.freq_unit.

  • symlog (bool) – Determines if the x-scale is symlog.

  • ax (plt.Axes or None) – Takes a matplotlib axes. If none, it uses plt.gca() to get the current axes. The lines are plotted in this axis.

  • freq_unit ('auto', 'cm' or 'nm') – How to interpret the given frequencies. If ‘auto’ it defaults to the plotters freq_unit.

  • add_legend (bool) – If to add the legend automatically.

overview()[source]

Plots an overview figure.

svd(n=5)[source]

Plot the SVD-components of the dataset.

Parameters:

n (int or list of int) – Determines the plotted SVD-components. If n is an int, it plots the first n components. If n is a list of ints, then every number is a SVD-component to be plotted.

das(first_comp=0, ax=None, add_legend=True, **kwargs)[source]

Plot a DAS, if available.

Parameters:
  • fist_comp (int) – Index of the first shown component, useful if fast components model coherent artefact and should not be shown

  • ax (plt.Axes or None) – Axes to plot.

  • kwargs (dict) – Keyword args given to the plot function

  • add_legend (bool) – If true, add legend automatically.

Return type:

Tuple of (List of Lines2D)

edas(ax=None, legend=True, **kwargs)[source]

Plot a EDAS, if expontial fit is available.

Parameters:
  • ax (plt.Axes or None) – Axes to plot.

  • kwargs (dict) – Keyword args given to the plot function

Return type:

Tuple of (List of Lines2D)

interactive()[source]

Generates a jupyter widgets UI for exploring a spectra.

plot_disp_result(result: EstDispResult)[source]

Visualize the result of a dispersion correction, creates a figure

class skultrafast.dataset.PolTRSpecPlotter(pol_dataset: PolTRSpec, disp_freq_unit=None)[source]

Bases: PlotterMixin

perp_ls[source]
para_ls[source]
_get_wl()[source]
_get_wn()[source]
spec(*times, norm=False, ax=None, n_average=0, add_legend=True, **kwargs)[source]

Plot spectra at given times.

Parameters:
  • *times (list or ndarray) – List of the times where the spectra are plotted.

  • norm (bool) – If true, each spectral will be normalized.

  • ax (plt.Axis or None.) – Axis where the spectra are plotted. If none, the current axis will be used.

  • n_average (int) – For noisy data it may be prefered to average multiple spectra together. This function plots the average of n_average spectra around the specific time-points.

  • upsample (int) – If >1, upsample the spectrum using cubic interpolation.

  • add_legend (bool) – Add legend automatically

Returns:

List containing the Line2D objects belonging to the spectra.

Return type:

tuple of (List of Lines2D)

trans(*args, symlog=True, norm=False, ax=None, add_legend=True, **kwargs)[source]

Plot the nearest transients for given frequencies.

Parameters:
  • wls (list or ndarray) – Spectral positions, should be given in the same unit as self.freq_unit.

  • symlog (bool) – Determines if the x-scale is symlog.

  • norm (bool or float) – If False, no normalization is used. If True, each transient is divided by the maximum absolute value. If norm is a float, all transient are normalized by their signal at the time norm.

  • ax (plt.Axes or None) – Takes a matplotlib axes. If none, it uses plt.gca() to get the current axes. The lines are plotted in this axis.

  • add_legend (bool) – If true, it will add the legend automatically.

  • function. (All other kwargs are forwarded to the plot)

Returns:

Tuple of lists containing the plotted lines.

Return type:

list of Line2D

das(ax=None, plot_first_das=True, **kwargs)[source]

Plot a DAS, if available.

Parameters:
  • ax (plt.Axes or None) – Axes to plot.

  • plot_first_das (bool) – If true, the first DAS is omitted. This is useful, when the first component is very fast and only modeles coherent contributions.

  • kwargs (dict) – Keyword args given to the plot function

Return type:

Tuple of (List of Lines2D)

edas(ax=None, *, add_legend=True, **kwargs)[source]

Plots a SAS (also called EDAS), if available.

Parameters:
  • ax (plt.Axes or None) – Axes to plot.

  • kwargs (dict) – Keyword args given to the plot function

Return type:

Tuple of (List of Lines2D)

sas(model: skultrafast.kinetic_model.Model, QYs: Dict[str, float] = {}, y0: numpy.ndarray | None = None, ax=None, *, add_legend=True, **kwargs)[source]

Plots a SAS (also called EDAS), if available.

Parameters:
  • mode (Model) – Kinetic model

  • yield – Dict with the yields

  • ax (plt.Axes or None) – Axes to plot.

  • kwargs (dict) – Keyword args given to the plot function

Return type:

Tuple of (List of Lines2D)

trans_anisotropy(*wls: float, symlog: bool = True, ax: matplotlib.pyplot.Axes | None = None, freq_unit=typing.Literal['auto', 'nm', 'cm'], mode: Literal[PolTRSpecPlotter.trans_anisotropy.aniso, PolTRSpecPlotter.trans_anisotropy.dichro])[source]

Plots the anisotropy over time for given frequencies. :param wls: Which frequencies are plotted. :type wls: floats :param symlog: Use symlog scale :type symlog: bool :param ax: Matplotlib Axes, if None, defaults to plt.gca(). :type ax: plt.Axes or None :param freq_unit: Unit of the frequecies. :type freq_unit: [‘auto’, ‘nm’, ‘cm’] :param mode: Plot anisotropy or dichroism. :type mode: [‘aniso’, ‘dichro’]

Returns:

List with the line objects.

Return type:

list of Line2D

class skultrafast.dataset.DataSetInteractiveViewer(dataset, fig_kws=None)[source]
init_events()[source]

Connect mpl events

update_lines(event)[source]

If the mouse cursor is over the 2D image, update the dynamic transient and spectrum

class skultrafast.dataset.SasViewer[source]
fit_result: FitExpResult[source]
model: skultrafast.kinetic_model.Model[source]
fig: matplotlib.pyplot.Figure[source]
lines: List[matplotlib.lines.Line2D][source]