Kinetic Models API (pyrate_ta.models)#

Base Models (pyrate_ta.models.base)#

Kinetic models: parameter layout, bounds, and the map to C(t).

A model owns the parameter vector and the rate matrix; it does not own the spectra. The data matrix is D ~ C @ S.T and solving for S is the fitters’ job (pyrate_ta.fit), which is what makes variable projection possible.

The non-linear parameter vector is, in this order:

[tau_1, ..., tau_m]  (+ t0)  (+ irf_fwhm)

with t0 and irf_fwhm appended only when they are being fitted. The lifetimes are in the dataset’s own time unit and are never converted here.

class pyrate_ta.models.base.KineticModel(n_components, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False)[source]#

Bases: object

Base class: a rate matrix plus the parameter bookkeeping around it.

Subclasses implement rate_matrix(); everything else – parameter names, bounds, initial guesses, and the concentration matrix – follows from it.

Variables:
  • n_components (int) – Number of compartments, i.e. the number of columns of C and hence of species spectra.

  • fit_irf (fit_t0,) – Whether time zero and the IRF width are free parameters. They are appended to the parameter vector in that order when free.

  • irf_fwhm (t0,) – Values used when the corresponding flag is False. irf_fwhm = 0 (or None) means no IRF convolution at all.

Parameters:
n_components: int#
fit_t0: bool = False#
fit_irf: bool = False#
t0: float = 0.0#
irf_fwhm: float | None = None#
coherent_artifact: bool = False#

Add the IRF and its first two derivatives to the design matrix, to absorb cross-phase modulation and other time-zero artefacts.

model_type: ModelType = 'Parallel'#

Family, which decides whether the spectra are DAS, EAS or SAS.

property n_lifetimes: int#

Number of independent lifetimes (not necessarily n_components).

lifetime_names()[source]#
Return type:

list[str]

param_names()[source]#

Names of the free parameters, in vector order.

Return type:

list[str]

property n_params: int#
pack(taus, t0=None, irf_fwhm=None)[source]#

Assemble the parameter vector from named pieces.

Parameters:
unpack(params)[source]#

Split a parameter vector into (taus, t0, irf_fwhm).

Values that are not being fitted come from the model’s own attributes, so a caller never has to remember which are free.

Return type:

tuple[ndarray, float, float | None]

default_bounds(t=None)[source]#

(lower, upper) arrays for the free parameters.

Lifetimes are bounded below by zero and unbounded above. When a delay axis is given, t0 is restricted to its range and the IRF width to the span of the data – an IRF wider than the measurement is never a physical answer, and leaving it unbounded is how a fit runs away.

initial_guess(t)[source]#

Lifetimes spread logarithmically over the measured delay range.

The shortest guess is the smallest positive delay step and the longest is the last delay, which brackets everything the data can resolve.

property c0#

Initial concentrations at t0.

rate_matrix(taus)[source]#

Rate matrix K for the given lifetimes.

rate_builder()[source]#

The raw k -> K callable, in terms of rates rather than lifetimes.

Used to work out which rate constant sits on which arrow of the scheme diagram: feeding it a unit vector shows where k_i appears.

concentrations(t, params=None, **kwargs)[source]#

Concentration matrix C(t), shape [Nd, n_components].

params is the packed parameter vector; alternatively pass taus=, t0= and irf_fwhm= by keyword.

property n_artifact: int#

Number of artefact columns appended to C (0 when switched off).

artifact_basis(t, t0=None, irf_fwhm=None)[source]#

The artefact columns for this model’s IRF (see coherent_artifact_basis()).

Parameters:
column_labels()[source]#

Labels of every column of C: the species, then the artefact.

Return type:

list[str]

species_labels()[source]#

Compartment labels: A, B, … then S1, S2, …

Return type:

list[str]

class pyrate_ta.models.base.ParallelModel(n_components, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False)[source]#

Bases: KineticModel

Independent exponential decays; the spectra are DAS.

Parameters:
rate_matrix(taus)[source]#

Rate matrix K for the given lifetimes.

rate_builder()[source]#

The raw k -> K callable, in terms of rates rather than lifetimes.

Used to work out which rate constant sits on which arrow of the scheme diagram: feeding it a unit vector shows where k_i appears.

class pyrate_ta.models.base.SequentialModel(n_components, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False)[source]#

Bases: KineticModel

A -> B -> C -> ..., one branch; the spectra are EAS.

Parameters:
rate_matrix(taus)[source]#

Rate matrix K for the given lifetimes.

rate_builder()[source]#

The raw k -> K callable, in terms of rates rather than lifetimes.

Used to work out which rate constant sits on which arrow of the scheme diagram: feeding it a unit vector shows where k_i appears.

class pyrate_ta.models.base.TargetModel(n_components, fit_t0=False, fit_irf=False, t0=0.0, irf_fwhm=None, coherent_artifact=False, scheme='A_eq_B')[source]#

Bases: KineticModel

General compartmental scheme with branching; the spectra are SAS.

The scheme fixes both the number of compartments and the number of rate constants, which need not be equal – an equilibrium A <=> B has two compartments and two rates, while A <=> B; A ->; B -> has two compartments and four.

Parameters:
scheme: TargetScheme | str = 'A_eq_B'#
property n_lifetimes: int#

Number of independent lifetimes (not necessarily n_components).

property c0#

the scheme’s own, when it declares them.

Type:

Initial populations

species_labels()[source]#

Compartment labels: A, B, … then S1, S2, …

Return type:

list[str]

lifetime_names()[source]#

Named after the rate constants, so the table reads as the scheme does.

Return type:

list[str]

rate_matrix(taus)[source]#

Rate matrix K for the given lifetimes.

rate_builder()[source]#

The raw k -> K callable, in terms of rates rather than lifetimes.

Used to work out which rate constant sits on which arrow of the scheme diagram: feeding it a unit vector shows where k_i appears.

pyrate_ta.models.base.make_model(model_type, n_components=2, *, scheme=None, **kwargs)[source]#

Build the model for a ModelType (or its string value).

Parameters:
  • model_type (ModelType or str) – "Parallel", "Sequential" or "Target".

  • n_components (int) – Number of compartments. Ignored for a target model, where the scheme decides.

  • scheme (str or TargetScheme, optional) – Required for a target model; see pyrate.models.TARGET_SCHEMES.

  • **kwargs – Passed to the model (fit_t0, fit_irf, t0, irf_fwhm).

Return type:

KineticModel

Predefined Target Schemes (pyrate_ta.models.schemes)#

Rate-matrix builders and the library of predefined target schemes.

Convention:

  • dc/dt = K c; off-diagonal K[i, j] is the rate from compartment j to compartment i, and K[i, i] is minus the sum of every rate leaving compartment i.

  • Rates are k = 1 / tau, with tau in the dataset’s own time unit.

  • A compartment whose column sums to a negative number decays to the ground state (which is not itself a compartment).

Parallel and sequential schemes are built directly; branched schemes come from TARGET_SCHEMES, keyed by a short identifier.

pyrate_ta.models.schemes.rates_from_lifetimes(taus)[source]#

k = 1/tau, with an infinite lifetime meaning a zero rate.

A component entered as inf does not decay: it is the constant offset that accounts for signal outliving the measured delay window, and its rate is exactly zero. Every other lifetime must be finite and positive; zero and negative values are refused rather than clamped, since neither has a meaning here.

pyrate_ta.models.schemes.parallel_K(rates)[source]#

K for independent parallel decays: diag(-k).

pyrate_ta.models.schemes.sequential_K(rates)[source]#

K for A -> B -> ... -> Z ->, one branch, no back reactions.

Compartment i decays with rate k[i] and feeds compartment i+1; the last one decays to the ground state.

pyrate_ta.models.schemes.default_c0(n_components, model_type)[source]#

Initial concentrations for a family: all excited, or only the first.

A parallel model starts every component at 1 (they are independent); a sequential or target model puts all the population in the first compartment.

Parameters:
  • n_components (int)

  • model_type (str)

class pyrate_ta.models.schemes.TargetScheme(key, label, n_species, n_rates, build, species=(), rate_names=(), c0=(), source_text='')[source]#

Bases: object

One predefined compartmental scheme.

Variables:
  • key (str) – Short identifier, used in settings and in a saved fit session.

  • label (str) – Reaction scheme in the notation used in the GUI and in publications.

  • n_species (int) – Number of compartments, i.e. the size of K and the number of SAS.

  • n_rates (int) – Number of independent rate constants (the fitted parameters).

  • build (callable) – build(k) -> K with k the rate vector, length n_rates.

  • species (tuple of str) – Compartment names. Empty for the predefined schemes, which use A, B, …; a scheme written in the text notation carries the user’s own names, and they travel to the diagram and the result.

  • rate_names (tuple of str) – Names of the rate constants, in parameter order. Empty means k1, k2, …

  • c0 (tuple of float) – Initial populations. Empty means all population in the first species.

  • source_text (str) – The notation this scheme was parsed from, so a session round-trips.

Parameters:
key: str#
label: str#
n_species: int#
n_rates: int#
build: Callable[[ndarray], ndarray]#
species: tuple[str, ...] = ()#
rate_names: tuple[str, ...] = ()#
c0: tuple[float, ...] = ()#
source_text: str = ''#
species_labels()[source]#

Compartment names, defaulting to A, B, …

Return type:

list[str]

parameter_names()[source]#

Rate-constant names, defaulting to k1, k2, …

Return type:

list[str]

rate_matrix(rates)[source]#

Validate the rate vector and build K.

Return type:

ndarray

pyrate_ta.models.schemes.get_scheme(key)[source]#

Look up a target scheme by key (built-in first, then saved user schemes).

Parameters:

key (str)

Return type:

TargetScheme

Text Reaction Scheme Parser (pyrate_ta.models.scheme_text)#

A text notation for kinetic schemes, and its parser.

Instead of typing a rate matrix – where a sign error or a missing diagonal term is invisible until the fit misbehaves – a scheme is written as the reactions themselves, one per line:

A  ->  B   : k1        # A decays into B with rate k1
B <->  C   : k2, k3     # equilibrium: forward k2, backward k3
C  ->      : k4         # decay to the ground state (no product)
B  ->      : k5         # a second channel out of B: B branches

init A = 1              # optional; the default is all population in the
                        # first species mentioned

The matrix is then derived, so it is correct by construction: every reaction contributes +k to the product’s row and -k to the reactant’s diagonal, and the ground state is simply the absence of a product.

Why this notation#

  • Species are named, not numbered. ICT, T1, GS_hot all work, and the names appear on the diagram and in the result, so a scheme reads as chemistry rather than as indices.

  • Rates are named, so they can be shared. Writing k1 on two arrows makes it one fitted parameter used twice – the natural way to impose “these two channels have the same rate”, which a matrix cannot express without a bespoke builder.

  • Any topology. Chains, branches, equilibria, cycles, disconnected pools and non-decaying products are all just lines; nothing is special-cased.

  • It round-trips. scheme_to_text() regenerates the notation from a parsed scheme, so a session can be saved, edited and reloaded as text.

Errors carry the line number and the offending text: a scheme that does not parse is refused, never half-built.

exception pyrate_ta.models.scheme_text.SchemeSyntaxError[source]#

Bases: ValueError

A scheme could not be parsed; the message names the line.

class pyrate_ta.models.scheme_text.ParsedReaction(source, target, rate, line)[source]#

Bases: object

One arrow: source -> target at rate rate.

target is None for decay to the ground state, which is not a compartment and therefore never a column of K.

Parameters:
source: str#
target: str | None#
rate: str#
line: int#
pyrate_ta.models.scheme_text.parse_scheme_text(text)[source]#

Parse the notation into (reactions, species, rate_names, c0).

Raises:

SchemeSyntaxError – On any malformed line, with the line number. Nothing partial is returned: a scheme either parses or it does not.

Parameters:

text (str)

pyrate_ta.models.scheme_text.build_rate_matrix(reactions, species, rate_names, k)[source]#

Assemble K from parsed reactions and a rate vector.

Each reaction moves population out of its source (-k on the diagonal) and, unless it decays to the ground state, into its target (+k off the diagonal). Building it this way makes the matrix consistent by construction: the columns cannot fail to balance.

Return type:

ndarray

pyrate_ta.models.scheme_text.scheme_from_text(text, key='custom')[source]#

Build a TargetScheme from the notation.

The returned scheme carries the species and rate names, so the diagram, the lifetime table and the result all speak the user’s own vocabulary.

Parameters:
pyrate_ta.models.scheme_text.scheme_to_text(reactions, compact=False)[source]#

Render parsed reactions back into the notation.

Opposed pairs sharing the same two species are folded into a single <-> line, so a scheme that was written as an equilibrium reads back as one.

Parameters:

compact (bool)

Return type:

str

pyrate_ta.models.scheme_text.check_scheme_text(text)[source]#

Validate without raising: (ok, message) for a GUI to display.

The message is the reason on failure, and a short summary of what was understood on success – species, rate constants, and which compartments decay to the ground state.

Parameters:

text (str)

Return type:

tuple[bool, str]

Rate-Matrix Propagator & IRF (pyrate_ta.models.propagator, pyrate_ta.models.irf)#

Propagation of a first-order kinetic system, with or without an IRF.

One propagator serves every model family. Given a rate matrix K and initial concentrations c0, the populations obey

\[\frac{\mathrm{d}\mathbf{c}}{\mathrm{d}t} = \mathbf{K}\mathbf{c}, \qquad \mathbf{c}(t) = e^{\mathbf{K}t}\,\mathbf{c}_0 .\]

The eigenvalue route (Berberan-Santos and Martinho) is used where K is diagonalisable: with \(\mathbf{K} = \mathbf{V}\Lambda\mathbf{V}^{-1}\) and \(\mathbf{a} = \mathbf{V}^{-1}\mathbf{c}_0\),

\[\mathbf{c}(t) = \mathbf{V}\left(\mathbf{a} \odot e^{\Lambda t}\right),\]

which is what makes the analytic IRF convolution possible at all: each exponential is convolved separately (pyrate_ta.models.irf) and the same linear combination is taken afterwards. Where K is defective or its eigenvector matrix is ill-conditioned, the unconvolved case falls back to a matrix-exponential propagator.

Reference: M. N. Berberan-Santos and J. M. G. Martinho, J. Chem. Educ. 67 (1990) 375 – the eigenvector solution of coupled first-order systems.

pyrate_ta.models.propagator.eigen_decomposition(K)[source]#

Eigenvalues and eigenvectors of K, with the conditioning reported.

Returns:

(lam, V, cond) – Eigenvalues lam [Nc], eigenvectors V [Nc, Nc] in columns, and the 2-norm condition number of V. Complex results are returned as-is; the caller decides when to take the real part.

Return type:

tuple

pyrate_ta.models.propagator.check_degeneracy(lifetimes, warn_ratio=None)[source]#

Report pairs of lifetimes closer together than warn_ratio.

Two lifetimes within a small factor of each other make the eigenvector matrix ill-conditioned; the symptom in a fit is a pair of amplitudes of opposite sign that grow without bound while the residual barely improves. The pairs are logged at info level – the user should see them – and returned so a fit result can carry them.

Parameters:

warn_ratio (float | None)

Return type:

list[tuple[int, int]]

pyrate_ta.models.propagator.concentrations(K, c0, t, *, t0=0.0, irf_fwhm=None, check_degenerate=True)[source]#

Concentration matrix C(t) of shape [Nd, Nc].

Parameters:
  • K (array_like, shape (Nc, Nc)) – Rate matrix, dc/dt = K c. Off-diagonal K[i, j] is the rate from compartment j to compartment i; the diagonal is minus the sum of every rate leaving that compartment.

  • c0 (array_like, shape (Nc,)) – Initial concentrations at t0.

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

  • t0 (float) – Time zero.

  • irf_fwhm (float or None) – Gaussian IRF width. None (or 0) gives the unconvolved solution, zero before t0.

  • check_degenerate (bool) – Run check_degeneracy() on the eigenvalue lifetimes and log any near-degenerate pair.

Return type:

numpy.ndarray, shape (Nd, Nc)

Raises:

ValueError – If the shapes are inconsistent, or if an IRF is requested for a matrix whose eigendecomposition is unusable (there is no analytic convolution in that case, and silently returning the unconvolved solution would be a wrong result rather than a slow one).

Instrument-response handling for exponential kinetic models.

The response is convolved into the concentration matrix, never into the data, and analytically rather than numerically: the convolution of a normalised Gaussian with a decaying exponential is an exponentially modified Gaussian (EMG), which is both faster and better conditioned than a numerical convolution on a non-uniform delay axis.

The IRF is specified by its FWHM (w) and its centre (t0), and the Gaussian is area-normalised,

\[g(t) = \frac{2}{w}\sqrt{\frac{\ln 2}{\pi}} \exp\!\left[-4\ln 2\left(\frac{t-t_0}{w}\right)^2\right].\]

Times are in the dataset’s own unit throughout; nothing here converts.

pyrate_ta.models.irf.fwhm_to_sigma(fwhm)[source]#

Gaussian standard deviation from its full width at half maximum.

Parameters:

fwhm (float)

Return type:

float

pyrate_ta.models.irf.sigma_to_fwhm(sigma)[source]#

Full width at half maximum from the Gaussian standard deviation.

Parameters:

sigma (float)

Return type:

float

pyrate_ta.models.irf.gaussian_irf(t, t0=0.0, fwhm=1.0)[source]#

Area-normalised Gaussian instrument response evaluated at t.

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

  • t0 (float) – Centre of the response (time zero).

  • fwhm (float) – Full width at half maximum, same unit as t. Must be positive.

Returns:

The response, normalised so that its integral over t is 1.

Return type:

numpy.ndarray

pyrate_ta.models.irf.convolved_exponential(t, rate, t0=0.0, sigma=0.0)[source]#

Gaussian-convolved exponential \(e^{\lambda (t-t_0)}\).

This is the EMG

\[f(t) = \tfrac{1}{2} \exp\!\left[\lambda (t-t_0) + \tfrac{1}{2}\lambda^2\sigma^2\right] \left[1 + \operatorname{erf} \left(\frac{t-t_0+\lambda\sigma^2}{\sigma\sqrt 2}\right)\right],\]

with rate the eigenvalue \(\lambda\) (negative for a decay).

Parameters:
  • t (array_like, shape (Nd,)) – Delays.

  • rate (array_like, shape (Nc,) or scalar) – Exponential rate(s) \(\lambda\). Complex values are accepted, so that eigenvalues of a non-symmetric rate matrix can be passed straight through.

  • t0 (float) – Time zero.

  • sigma (float) – Gaussian standard deviation. 0 returns the unconvolved exponential multiplied by the Heaviside step, i.e. the sigma -> 0 limit.

Returns:

One column per rate.

Return type:

numpy.ndarray, shape (Nd, Nc)

Notes

The naive expression overflows for early delays, where the prefactor \(\exp(\lambda(t-t_0)+\lambda^2\sigma^2/2)\) is huge and the bracket is vanishing. Using \(z^2 - \left[\lambda(t-t_0)+\lambda^2\sigma^2/2\right] = (t-t_0)^2/2\sigma^2\) the product can be rewritten with the scaled complementary error function,

\[f(t) = \tfrac{1}{2} e^{-(t-t_0)^2/2\sigma^2}\,\operatorname{erfcx}(-z),\]

which is evaluated wherever \(-z \ge 0\); the direct form is used elsewhere, where it is the stable one. Both branches are computed and selected with numpy.where(), so the result is free of overflow warnings for the whole delay axis.

pyrate_ta.models.irf.ARTIFACT_LABELS: tuple[str, ...] = ('IRF', 'dIRF/dt', 'd2IRF/dt2')#

Labels of the coherent-artefact columns, in the order they are built.

pyrate_ta.models.irf.coherent_artifact_basis(t, t0=0.0, fwhm=None, orders=2)[source]#

Gaussian and its first orders derivatives, as extra design columns.

Around time zero a transient carries signal the kinetic model cannot describe: cross-phase modulation and two-photon absorption in the solvent and the cell windows. Their time profile is, to a good approximation, the instrument response itself and its first two derivatives, so adding those three columns to the design matrix lets the fit absorb the artefact into amplitudes of its own instead of distorting the shortest lifetime – which is what happens when it is left in.

The columns are the shape only: each is scaled to unit maximum absolute value, since its amplitude is solved for per probe pixel like any other spectrum. Scaling also keeps the design matrix conditioned – the second derivative is otherwise larger than the Gaussian by 1/sigma**2.

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

  • t0 (float) – Centre of the response.

  • fwhm (float) – Width of the response. Required: without a width there is no artefact shape to build, and guessing one would invent a component.

  • orders (int, default 2) – Highest derivative included; 2 gives the usual three columns.

Returns:

[Nd, orders + 1], columns ordered g, g', g''.

Return type:

numpy.ndarray

Notes

The Gaussian-and-derivatives description follows Kovalenko et al., Phys. Rev. A 59, 2369 (1999).

pyrate_ta.models.irf.clip_delays(t, t_min)[source]#

Boolean mask of the delays kept when clipping at t_min.

Clipping is the alternative to modelling the IRF (IRFMode.CLIP): the early delays, where the coherent artefact lives, are dropped instead. It changes which data the fit saw, so the caller must record t_min in the result’s reproducibility payload.

Parameters:

t_min (float | None)