Fitting Engines & Solvers API (pyrate_ta.fit)#

Global, Target & Kinetic Engines (pyrate_ta.fit.engines)#

The three fitting engines, and the result they build.

fit_kinetics

One or a few traces, multi-exponential.

fit_global

Every probe pixel at once with shared lifetimes; DAS or EAS.

fit_target

The same over a compartmental K-matrix scheme; SAS.

All three take either a pymorgan.Dataset1D or plain arrays, run headlessly (no QApplication), and return a result object from pyrate_ta.results carrying the lifetimes with their uncertainties and fixed/free flags.

Component ordering#

Variable projection sees only the column space of C, so permuting the lifetimes fits equally well and the optimiser’s ordering depends on the initial guess. For parallel and sequential models the components are therefore sorted by lifetime on output, the spectra permuted to match, and the fact recorded on the result (sorted_by_lifetime). A target model is left exactly as fitted: its compartments are defined by the scheme, and reordering them would misrepresent it.

pyrate_ta.fit.engines.fit_global(data, t=None, *, n_components=None, model_type=None, taus=None, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False, use_weights=None, detector=0, delay_range=None, probe_range=None, t_min=None, sigma=None, **driver_kwargs)[source]#

Global analysis of a dataset: shared lifetimes, one spectrum per component.

data is either a pymorgan.Dataset1D or the data matrix, in which case the delay axis t is the second argument.

Parameters:
  • n_components (int, optional) – Number of components; defaults to Settings.n_components, or to the length of taus when those are given.

  • model_type (ModelType or str, optional) – "Parallel" (DAS) or "Sequential" (EAS). Defaults to Settings.model_type.

  • taus (sequence, optional) – Initial lifetimes. An entry of inf (or “inf”, “infinity”, …) adds a non-decaying component: the constant offset for signal that outlives the delay window. It is held fixed, since an optimiser cannot vary infinity.

  • coherent_artifact (bool, default False) – Add the IRF and its first two derivatives to the design matrix, so cross-phase modulation and other time-zero artefacts are absorbed by their own amplitudes instead of distorting the shortest lifetime. Needs a Gaussian IRF width.

  • use_weights (bool, optional) – Weight by the per-point noise. Defaults to Settings.use_noise_weights. Requesting weights for data with no noise raises rather than quietly producing an SSR labelled as a chi-squared.

  • fit_t0 (bool)

  • fit_irf (bool)

  • t0 (float)

  • irf_fwhm (float | None)

  • detector (int)

  • t_min (float | None)

Return type:

GlobalFit

pyrate_ta.fit.engines.preview_global(data, t=None, *, taus, model_type=None, scheme=None, t0=0.0, irf_fwhm=None, coherent_artifact=False, use_weights=None, detector=0, delay_range=None, probe_range=None, t_min=None, sigma=None)[source]#

Evaluate a model at the given lifetimes without optimising.

The spectra still follow from the data (they are the least-squares solution for the given C), so a preview shows what those lifetimes actually imply and what the residual would be. Nothing is fitted, so there is no convergence report and no uncertainties – and the result says so rather than presenting a guess as an answer.

Parameters:
Return type:

GlobalFit

pyrate_ta.fit.engines.fit_target(data, t=None, *, scheme, taus=None, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False, use_weights=None, detector=0, delay_range=None, probe_range=None, t_min=None, sigma=None, **driver_kwargs)[source]#

Target analysis over a compartmental scheme; the spectra are SAS.

scheme is a key from pyrate.models.TARGET_SCHEMES or a TargetScheme.

The components are not reordered: a scheme defines which compartment is which. Note also that the rates of a branched scheme are generally not identifiable from a single dataset – the fit can be perfect while the individual rates are not determined; the eigenvalues, which are, are stored on the result.

Parameters:
Return type:

TargetFit

pyrate_ta.fit.engines.fit_kinetics(t, y, *, n_components=None, model_type=None, taus=None, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, sigma=None, use_weights=False, **driver_kwargs)[source]#

Multi-exponential fit of one trace (or a few), by the same machinery.

A single trace is the Np = 1 case of a global fit: the amplitudes are still solved in closed form, so only the lifetimes reach the optimiser.

Parameters:
  • t (array_like (Nd,))

  • y (array_like (Nd,) or (Nd, Ncuts)) – One trace, or several sharing the same lifetimes.

  • n_components (int | None)

  • fit_t0 (bool)

  • fit_irf (bool)

  • t0 (float)

  • irf_fwhm (float | None)

  • use_weights (bool)

Return type:

KineticFit

Variable Projection & Cost (pyrate_ta.fit.varpro, pyrate_ta.fit.cost, pyrate_ta.fit.driver)#

Variable projection: the linear amplitudes, in closed form.

With the bilinear model D ~ C @ S.T, the spectra S enter linearly. For any fixed set of non-linear parameters the best-fit spectra are therefore available without an optimiser,

\[\mathbf{S}^{\mathsf{T}} = \arg\min_{\mathbf{S}} \lVert \mathbf{W} \odot (\mathbf{D} - \mathbf{C}\mathbf{S}^{\mathsf{T}}) \rVert^2 ,\]

and only the lifetimes (plus t0 and the IRF width) go to the non-linear solver. For a 500-pixel three-component fit that is three free parameters instead of about 1500, and it is far better conditioned than fitting both together. Amplitudes must never be placed in the optimiser’s parameter vector.

Three solve paths, chosen from the weights:

weights

path

None

one least-squares solve for all pixels at once

constant per delay

rows scaled once, then a single solve

per point

batched QR, one small system per pixel

The per-point case cannot share a factorisation: each pixel has its own weight profile down the delay axis, so each has its own normal system. It is solved by a batched QR rather than by forming C.T W C explicitly, which would square the condition number of C.

Reference: van Stokkum, Larsen and van Grondelle (2004); see pyrate_ta.cite.

pyrate_ta.fit.varpro.solve_amplitudes(C, D, weights=None)[source]#

Least-squares component spectra S of shape [Np, Nc].

Parameters:
  • C (array_like, shape (Nd, Nc)) – Concentration matrix.

  • D (array_like, shape (Nd, Np)) – Data for one detector, in mOD.

  • weights (array_like, optional) – 1/sigma weights, either (Nd, Np) per point, (Nd,) per delay, or None for an unweighted solve. Zero weights drop a point from the fit without changing the matrix shapes.

Return type:

numpy.ndarray, shape (Np, Nc)

Raises:

ValueError – On inconsistent shapes, or if weights contains negative or non-finite values (a weight is 1/sigma; a negative one is a bug in the caller, not a datum to be silently repaired).

pyrate_ta.fit.varpro.project(C, D, weights=None)[source]#

Amplitudes and residuals in one step.

Returns:

(S, R) – S [Np, Nc] and the unweighted residual matrix R = D - C @ S.T [Nd, Np]. Residuals are returned unweighted so the caller decides whether the weights belong in the cost function or only in the statistic; pyrate_ta.fit.cost applies them.

Return type:

tuple of numpy.ndarray

Weights, the residual vector, and the fit statistic.

The weighting rules are the ones agreed in todo_fitting_routines.md §3:

  • weights are 1/sigma with sigma the per-point noise PyMORGAN supplies (pymorgan.Dataset1D.noise_array()); PyRATE-TA never estimates noise;

  • sigma is clipped from below at noise_floor_fraction of its median, so one near-zero value cannot dominate the cost function;

  • points with non-finite or non-positive sigma, or non-finite data, get zero weight and are excluded from the point count;

  • requesting weights for a dataset that has no noise raises. Falling back to an unweighted fit while still calling the statistic a reduced chi-squared would misreport it, which is worse than a refusal.

The statistic follows from whether weights were used:

  • weighted: \(\chi^2_\nu = \sum (R/\sigma)^2 / (N - p)\)

  • unweighted: \(\mathrm{SSR} = \sum R^2\)

SSR is not comparable between datasets and carries no “close to 1” reading, so the two are never given the same name.

exception pyrate_ta.fit.cost.NoiseUnavailableError[source]#

Bases: ValueError

Weighted fit requested for data that carries no noise estimate.

class pyrate_ta.fit.cost.Weights(w, mask, n_points, n_masked=0, floor=None, n_floored=0, source=None)[source]#

Bases: object

Per-point weights and the bookkeeping that goes with them.

Variables:
  • w (numpy.ndarray or None) – 1/sigma [Nd, Np], or None for an unweighted fit.

  • mask (numpy.ndarray) – Boolean [Nd, Np], True where a point takes part in the fit.

  • n_points (int) – Number of points actually fitted, i.e. mask.sum().

  • n_masked (int) – Points excluded (bad sigma or bad data); part of the reproducibility payload, since they change what the fit saw.

  • floor (float or None) – The absolute value sigma was clipped at.

  • n_floored (int) – How many sigma values that clip touched. A large number means the noise estimate, not the floor, is the thing to look at.

  • source (str or None) – Where the noise came from, e.g. "pdatn" / "single_scans".

Parameters:
w: ndarray | None#
mask: ndarray#
n_points: int#
n_masked: int = 0#
floor: float | None = None#
n_floored: int = 0#
source: str | None = None#
property weighted: bool#
pyrate_ta.fit.cost.build_weights(D, sigma=None, *, use_weights=False, floor_fraction=None, source=None)[source]#

Build the weights (or the plain mask) for one detector’s data.

Parameters:
  • D (array_like, shape (Nd, Np)) – Data, in mOD. Non-finite entries are masked out either way.

  • sigma (array_like, optional) – Per-point standard deviation, same shape as D.

  • use_weights (bool) – Whether the fit is to be weighted. True without sigma raises.

  • floor_fraction (float, optional) – Clip sigma at this fraction of its median. Defaults to Settings.noise_floor_fraction.

  • source (str, optional) – Provenance of the noise, recorded on the result.

Raises:

NoiseUnavailableError – If use_weights is set but no usable sigma was given.

Return type:

Weights

pyrate_ta.fit.cost.residual_vector(R, weights)[source]#

Flatten the residual matrix into the vector the optimiser wants.

Weighted residuals are R/sigma; masked points contribute zero, which is what a zero weight already gives, so no reshaping is needed and the vector length stays constant across iterations (scipy.optimize.least_squares requires that).

Parameters:

weights (Weights)

class pyrate_ta.fit.cost.FitStatistic(kind, value, n_points, n_nonlinear, n_amplitudes, dof, weighted, value_nonlinear_dof=None, noise_source=None, extra=<factory>)[source]#

Bases: object

The goodness-of-fit number, and everything needed to read it.

Variables:
  • kind (str) – "chi2_red" or "ssr".

  • value (float) – The statistic itself. For a weighted fit this is the reduced chi-squared with the linear amplitudes counted as parameters.

  • value_nonlinear_dof (float or None) – The same chi-squared counting only the non-linear parameters, which is the convention many programs report. Kept alongside because the choice of denominator changes the number by a large factor and should never be implicit.

  • n_amplitudes (n_points, n_nonlinear,) – Points fitted and parameters spent (the amplitudes are Np * Nc).

  • dof (int) – n_points - n_nonlinear - n_amplitudes.

  • weighted (bool)

  • noise_source (str or None)

Parameters:
kind: str#
value: float#
n_points: int#
n_nonlinear: int#
n_amplitudes: int#
dof: int#
weighted: bool#
value_nonlinear_dof: float | None = None#
noise_source: str | None = None#
extra: dict#
pyrate_ta.fit.cost.fit_statistic(R, weights, *, n_nonlinear, n_amplitudes)[source]#

Compute the statistic for a converged (or trial) residual matrix.

n_amplitudes is Np * Nc: variable projection solves the amplitudes in closed form, but it still spends those degrees of freedom, so they are counted in the default reduced chi-squared. The value with only the non-linear parameters counted is reported alongside.

Parameters:
Return type:

FitStatistic

The shared fit driver: packing, masks, bounds, solver, convergence report.

One driver serves every engine. It owns:

  • the free/fixed split – fixed parameters never reach the optimiser, and come back flagged rather than with a small uncertainty that could be mistaken for precision;

  • the bounds, and the method that can honour them;

  • the variable-projection cost function (pyrate_ta.fit.varpro) with the weights and statistic from pyrate_ta.fit.cost;

  • the convergence report. Exceeding the iteration cap is a non-convergence, never a result: the outcome carries converged = False and a warning is logged, so nothing downstream can mistake it for a fit.

The driver is headless: no Qt, no widgets. Progress is reported through a plain callback, which the GUI adapts to a progress dialog.

class pyrate_ta.fit.driver.FitReport(converged, status, message, n_evaluations, n_jacobian, cost, optimality, method, max_iterations, at_bounds=<factory>)[source]#

Bases: object

What the optimiser did, in enough detail to judge the result.

Parameters:
converged: bool#
status: int#
message: str#
n_evaluations: int#
n_jacobian: int#
cost: float#
optimality: float#
method: str#
max_iterations: int#
at_bounds: list[str]#
class pyrate_ta.fit.driver.FitOutcome(params, param_names, fixed, S, R, statistic, report, weights, jacobian=None, initial_params=None, bounds=None)[source]#

Bases: object

Raw output of one driver run.

Phase 4 wraps this in the public result objects (GlobalFit and friends) together with the reproducibility payload; it is kept separate so the driver stays independent of the result classes.

Parameters:
params: ndarray#
param_names: list[str]#
fixed: ndarray#
S: ndarray#
R: ndarray#
statistic: FitStatistic#
report: FitReport#
weights: Weights#
jacobian: ndarray | None = None#
initial_params: ndarray | None = None#
bounds: tuple[ndarray, ndarray] | None = None#
property converged: bool#
pyrate_ta.fit.driver.run_fit(model, t, D, *, sigma=None, use_weights=False, noise_source=None, p0=None, fixed=None, bounds=None, method=None, max_iterations=None, ftol=None, xtol=None, callback=None, **model_kwargs)[source]#

Fit one detector’s data with variable projection.

Parameters:
  • model (KineticModel) – Supplies C(t), the parameter layout, the bounds and the initial guess.

  • t (array_like, shape (Nd,)) – Delays, in the dataset’s time unit.

  • D (array_like, shape (Nd, Np)) – Data for one detector, in mOD.

  • sigma (array_like, optional) – Per-point noise, same shape as D.

  • use_weights (bool) – Weight the residuals by 1/sigma; raises when no sigma is available (see pyrate_ta.fit.cost).

  • p0 (array_like, optional) – Initial parameter vector. Defaults to model.initial_guess(t).

  • fixed (array_like of bool or str, optional) – Parameters held at their initial value, by mask or by name.

  • bounds (tuple, optional) – (lower, upper); defaults to model.default_bounds(t).

  • method (str, optional) – "trf" (default), "dogbox" or "lm". lm ignores bounds and is refused when finite bounds are present, rather than silently dropping them.

  • max_iterations (optional) – Solver limits; default to the active pyrate.Settings.

  • ftol (optional) – Solver limits; default to the active pyrate.Settings.

  • xtol (optional) – Solver limits; default to the active pyrate.Settings.

  • callback (callable, optional) – callback(n_eval, params, cost), called on each residual evaluation. Progress reporting never touches widgets from here.

  • noise_source (str | None)

  • model_kwargs (Any)

Return type:

FitOutcome

Constrained Amplitudes & Pure Positive Spectra (pyrate_ta.fit.constrained, pyrate_ta.fit.groundstate)#

Constrained amplitude solver for sign-constrained and bounded species spectra.

When physical constraints are imposed on species spectra (e.g. non-negative absorption for real excited states/products, or non-positive sign for bleach contributions), variable projection solves a bounded linear least-squares problem per pixel rather than an unconstrained linear solve:

\[\min_{\mathbf{S}_p} \lVert \mathbf{C}_w \mathbf{S}_p - \mathbf{d}_{w, p} \rVert^2 \quad \text{subject to } \mathbf{l} \le \mathbf{S}_p \le \mathbf{u}\]

Used by Phase 6 (Absolute species spectra and sign-constrained fitting).

pyrate_ta.fit.constrained.solve_amplitudes_constrained(C, D, weights=None, bounds=None, sign_mask=None)[source]#

Bounded least-squares component spectra S of shape [Np, Nc].

Parameters:
  • C (array_like, shape (Nd, Nc)) – Concentration matrix.

  • D (array_like, shape (Nd, Np)) – Data for one detector, in mOD.

  • weights (array_like, optional) – 1/sigma weights, either (Nd, Np), (Nd,), or None.

  • bounds (tuple of (lb, ub), optional) – Lower and upper bounds for each component amplitude, either floats or arrays of shape (Nc,).

  • sign_mask (array_like of int, optional) – Array of length Nc specifying sign constraints per component: +1 for non-negative (>= 0), -1 for non-positive (<= 0), 0 for unconstrained.

Return type:

numpy.ndarray, shape (Np, Nc)

Ground-state bleach (GSB) and stimulated emission (SE) recovery for pure positive component spectra.

Transient absorption data are difference spectra:

S_diff(lambda) = S_ESA(lambda) - a * sigma_A(lambda) - b * F(lambda)
where:
  • S_ESA(lambda) >= 0 is the pure excited-state absorption (ESA) spectrum.

  • sigma_A(lambda) >= 0 is the steady-state ground-state absorption spectrum (producing GSB).

  • F(lambda) >= 0 is the steady-state emission spectrum (producing stimulated emission SE).

  • a >= 0 and b >= 0 are the bleach and emission amplitudes per component.

Adding back the scaled reference spectra converts difference spectra to absolute, pure positive (non-negative) component spectra:

S_abs[:, i] = S_diff[:, i] + a_i * sigma_A + b_i * F >= 0
class pyrate_ta.fit.groundstate.BleachRecoveryResult(S_abs, gs_scale, em_scale, bleach_spectra=None, a_max=None)[source]#

Bases: object

Container for ground-state bleach & stimulated emission recovery results.

Supports attribute access (.S_abs, .gs_scale, .em_scale, .bleach_spectra, .a_max) as well as 3-item unpacking: S_abs, a, a_max = compute_absolute_spectra(...) or S_abs, gs_scale, em_scale = compute_absolute_spectra(...).

Parameters:
  • S_abs (np.ndarray)

  • gs_scale (np.ndarray | float)

  • em_scale (np.ndarray | float)

  • bleach_spectra (np.ndarray | None)

  • a_max (float | None)

pyrate_ta.fit.groundstate.recover_component_bleach(s_diff, basis_matrix, *, clip_negative=True, robust_margin=0.9)[source]#

Recover the minimal non-negative basis coefficients to eliminate negative dips in a spectrum.

Parameters:
  • s_diff (numpy.ndarray of shape (Np,)) – One component difference spectrum (carrying negative GSB and/or SE dips).

  • basis_matrix (numpy.ndarray of shape (Np, K)) – Reference basis spectra (e.g. [sigma_A, F]).

  • clip_negative (bool, default True) – Clamp any remaining negative residuals (e.g. noise fluctuations) to zero.

  • robust_margin (float, default 0.90) – Quantile used to scale basis profile over the active bleach region, avoiding sensitivity to single-pixel noise outliers.

Returns:

(coeffs, s_recovered) – Fitted coefficients of shape (K,) and the recovered non-negative spectrum of shape (Np,).

Return type:

tuple

pyrate_ta.fit.groundstate.compute_max_gs_scale(S_diff, gs_spectrum, f=None)[source]#

Calculate the maximum physical scale factor a_max for ground state.

Parameters:
  • S_diff (array_like, shape (Np, Nc)) – Difference species spectra.

  • gs_spectrum (array_like, shape (Np,)) – Ground-state absorption spectrum on the same probe grid.

  • f (array_like or float, optional) – Ground state bleach fraction per species (defaults to 1.0 for all).

Returns:

Maximum allowable scale factor a_max >= 0.

Return type:

float

pyrate_ta.fit.groundstate.compute_absolute_spectra(S_diff, gs_spectrum=None, f=None, gs_scale='auto', *, em_spectrum=None, em_scale='auto')[source]#

Convert difference species spectra to pure positive absolute spectra.

Accounts for ground-state bleach (GSB) using gs_spectrum and stimulated emission (SE) using em_spectrum.

Parameters:
  • S_diff (array_like, shape (Np, Nc)) – Difference species spectra from global / target fit.

  • gs_spectrum (array_like, shape (Np,), optional) – Ground-state steady-state absorption spectrum.

  • f (array_like or float, optional) – Relative bleach fraction per compartment (default 1.0).

  • gs_scale (float or "auto", default "auto") – Absorption scale factor. If “auto”, determines the optimal non-negative scale per species to eliminate bleach dips.

  • em_spectrum (array_like, shape (Np,), optional) – Steady-state emission / fluorescence spectrum.

  • em_scale (float or "auto", default "auto") – Emission scale factor. If “auto”, determines the optimal non-negative scale per species to eliminate stimulated emission dips.

Returns:

Container with .S_abs, .gs_scale, .em_scale, .bleach_spectra, and .a_max, supporting 3-tuple unpacking for backward compatibility.

Return type:

BleachRecoveryResult

Lifetime Density Analysis (pyrate_ta.fit.lda)#

Lifetime Density Analysis (LDA) solver module.

Instead of fitting N discrete lifetimes, LDA solves for a continuous distribution of amplitudes over a dense, logarithmically spaced grid of fixed lifetimes:

\[\min_{\mathbf{S}^{\mathsf{T}}} \lVert \mathbf{W} \odot (\mathbf{D} - \mathbf{C}(\boldsymbol{\tau}_{grid}) \mathbf{S}^{\mathsf{T}}) \rVert^2 + \alpha^2 \lVert \mathbf{L} \mathbf{S}^{\mathsf{T}} \rVert^2\]

Supports Tikhonov (ridge L=I), 1st-derivative (L=D1), and 2nd-derivative (L=D2) smoothness penalties, with L-curve corner detection and GCV alpha selection.

pyrate_ta.fit.lda.build_penalty_matrix(M, penalty='d2')[source]#

Build regularisation penalty matrix L of shape (K, M).

Parameters:
  • M (int) – Number of grid points in the lifetime axis.

  • penalty ({"ridge", "identity", "d1", "d2"}) – Penalty type.

Return type:

numpy.ndarray

pyrate_ta.fit.lda.solve_lda(data, t=None, *, n_taus=100, tau_range=None, irf_fwhm=None, t0=0.0, penalty='d2', alpha='auto', alpha_method='lcurve', alphas=None, detector=0, coherent_artifact=False, svd_components=0, non_negative=False, n_bootstraps=0, find_peaks=False, delay_range=None, probe_range=None, callback=None)[source]#

Run Lifetime Density Analysis (LDA) on time-resolved data.

Parameters:
  • data (Dataset1D or array_like (Nd, Np)) – Data matrix or PyMORGAN dataset.

  • t (array_like, optional) – Delay axis if data is plain arrays.

  • n_taus (int, default 100) – Number of log-spaced lifetimes in grid.

  • tau_range (tuple of (tau_min, tau_max), optional) – Grid range. Defaults to [min_t/2, 5*max_t].

  • irf_fwhm (float, optional) – Gaussian IRF width.

  • t0 (float, default 0.0) – Time zero offset.

  • penalty ({"d2", "d1", "ridge"}, default "d2") – Regularisation operator.

  • alpha (float or "auto") – Regularisation parameter. If “auto”, selected via alpha_method.

  • alpha_method ({"lcurve", "gcv", "morozov"}, default "lcurve") – Method for auto-selecting alpha.

  • alphas (array_like, optional) – Array of candidate alpha values to scan.

  • detector (int, default 0) – Detector index if data has multiple detectors.

  • coherent_artifact (bool, default False) – Include IRF and derivative basis columns at t0 to absorb solvent artefact.

  • svd_components (int, default 0) – Pre-filter raw data matrix using top K SVD components to suppress noise (0 = Off).

  • non_negative (bool, default False) – Enforce non-negative amplitudes S >= 0 via regularised Non-Negative Least Squares (NNLS).

  • n_bootstraps (int, default 0) – Number of Monte Carlo bootstrap iterations for confidence intervals on A(tau) (0 = Off).

  • find_peaks (bool, default False) – Automatically locate major lifetime peak centroids from A(tau).

  • delay_range (tuple of (float, float), optional) – Restricted delay window to fit.

  • probe_range (tuple of (float, float), optional) – Restricted probe window to fit.

  • callback (callable, optional) – Progress callback callback(current_step, total_steps, message).

Return type:

LDAResult