Plotting, I/O & Settings API#

Plotters (pyrate_ta.plot)#

Concentration profiles C(t) of a fitted kinetic model.

One of the few views PyMORGAN has no concept of: its plotters

draw measured quantities against delay, whereas C is the model’s own population of each compartment – dimensionless, never loaded from a file, and meaningful only next to the species spectra it multiplies.

What is not reimplemented here is the delay axis: the scale, limits and tick-label convention come from pymorgan.oneD.plot.apply_delay_axis, and the colours from the same turbo ramp as plot_species_spectra, so component i is the same colour in both figures and the two can be read side by side.

For a parallel model the “profiles” are the bare exponentials of each component; for a sequential or target model they are the populations of the compartments, which is where the plot earns its keep – it shows when each species is present, and therefore which spectrum can be trusted where.

pyrate_ta.plot.concentrations.species_labels_for(fit, labels=None)[source]#

Names for the columns of C.

Taken from the scheme when the fit has one (so a target fit reads ICT, T1, … rather than A, B), and from the model family otherwise.

Return type:

list[str]

pyrate_ta.plot.concentrations.plot_concentrations(fit, ax=None, fig=None, *, labels=None, normalise=False, settings=None, time_axis_scale=None, title=None, **kwargs)[source]#

Plot the population of each species against delay.

Parameters:
  • fit (KineticFit) – A fit (or preview) result carrying C. A result without C is refused rather than drawn empty – there is nothing to show, and a blank axis would look like a fit with no population.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw on; a new figure is created when omitted.

  • labels (sequence of str, optional) – Species names. Defaults to the scheme’s own names.

  • normalise (bool, default False) – Scale each profile to its own maximum. Useful when one compartment never accumulates much; misleading if the relative populations are the point, which is why it is off by default.

  • time_axis_scale ({"symlog", "log", "lin"}, optional) – Delay-axis scale; defaults to the active PyMORGAN setting, i.e. the same axis the contour and the kinetic traces use.

  • **kwargs – Passed to ax.plot.

Return type:

matplotlib.axes.Axes

Compartment (K-matrix) diagrams.

A kinetic scheme is a directed graph: one node per compartment, one arrow per non-zero off-diagonal rate, plus an arrow to the ground state wherever a compartment loses population to it (a column of K summing to a negative number). PyMORGAN has no concept of this, so the plotter lives here.

Drawn with plain Matplotlib patches rather than a graph library: the layouts worth having are simple (a chain, a stack, a ring), and the arrow geometry and label placement need control that a generic spring layout does not give.

Everything aesthetic that PyMORGAN owns – font sizes, the colour cycle – is taken from its style, so a scheme figure sits beside the spectra without looking foreign.

pyrate_ta.plot.scheme.rate_symbols(builder, n_rates, n_species, tol=1e-12)[source]#

Which rate constants sit on which arrow.

Feeding the k -> K builder a unit vector shows where k_i appears, so the diagram can be labelled with the symbols themselves rather than with numbers. This matters for setting up a fit: the arrow tells you which entry of the rate table you are about to bound.

An edge may carry more than one constant – decay to the ground state from a branching compartment is the sum of everything leaving it that goes nowhere else – in which case the label is a sum.

Returns:

(source, target) -> [rate indices], with target = None for the ground state. Indices are zero-based.

Return type:

dict

Parameters:
pyrate_ta.plot.scheme.plot_scheme(obj, taus=None, ax=None, *, labels=None, rate_labels='symbol', show_ground_state=True, node_size=0.22, fontsize=None, title=None)[source]#

Draw the compartment diagram of a kinetic scheme.

Parameters:
  • obj (KineticModel, TargetScheme, fit result or array) – Anything that defines a rate matrix. A model or a bare scheme also needs taus; a fit result already carries them.

  • taus (sequence, optional) – Lifetimes, when obj does not carry them.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; a new figure is created when omitted.

  • labels (sequence of str, optional) – Compartment names. Defaults to A, B, C, …

  • rate_labels ({"symbol", "value", "none"}) – What to write on each arrow. "symbol" (the default) writes the rate constants themselves – k_1, k_2, and a sum such as k_1+k_2 where a compartment branches – which is what tells you which row of the rate table an arrow belongs to when setting values and bounds. "value" writes the lifetime of that step (1/k), which for a branching compartment is not the lifetime with which it is observed to decay: that one is the inverse of the summed rate.

  • show_ground_state (bool) – Draw the ground state as a separate grey node.

  • node_size (float)

  • fontsize (float | None)

  • title (str | None)

Return type:

matplotlib.axes.Axes

pyrate_ta.plot.scheme.scheme_text(obj, taus=None, labels=None)[source]#

The scheme as a one-line string, e.g. A -> B; B <=> C; C ->.

Useful in a log line or a result summary, where a figure cannot go.

Return type:

str

Contour views of a fitted or residual matrix – through PyMORGAN’s plotter.

A fit surface and a residual matrix are not datasets, so PyMORGAN has no method that takes them. What it does have is the whole contour engine (colourmaps, white levels, symmetric scales, axis labels and units), and rewriting any of that here would be redundant duplication.

So this module does not draw anything itself: it wraps the matrix in a pymorgan.Dataset1D carrying the original dataset’s units, and hands it to plot_contour. The fit, the residuals and the data are then rendered by the same code, which is what makes the three views comparable – and it is why a PyMORGAN colourmap identifier such as DkRd/Wh/DkBu works here without this module knowing anything about colourmaps.

pyrate_ta.plot.matrix.as_dataset(t, probe, M, dataset=None)[source]#

Wrap a [Nd, Np] matrix as a pymorgan.Dataset1D.

The units (and hence every axis label) are taken from the dataset the matrix came from, so a residual map is labelled exactly like the data it is the residual of.

pyrate_ta.plot.matrix.as_fit_dataset(fit, dataset=None)[source]#

The fitted surface as a pymorgan.Dataset1D, on the fit’s axes.

A fit restricted to part of the spectral range returns spectra on that window only, while the dataset still carries the full probe axis. Handing the full axis to a plotter that expects one point per row of S is a size mismatch at best and a mislabelled spectrum at worst, so anything that draws a fit gets this wrapper instead of the original dataset.

The units, source and data type come from the dataset, so the axes still read like the data’s.

pyrate_ta.plot.matrix.plot_matrix(t, probe, M, ax=None, *, title=None, dataset=None, **contour_kwargs)[source]#

Contour a fit surface or residual matrix using PyMORGAN’s plotter.

Parameters:
  • t (array_like) – Delay and probe axes of M.

  • probe (array_like) – Delay and probe axes of M.

  • M (array_like (Nd, Np)) – Fit surface or residual matrix, in mOD.

  • dataset (pymorgan.Dataset1D, optional) – Source of the units, so the axes read like the data’s.

  • **contour_kwargs – Passed straight to Dataset1D.plot_contour (Zmin/Zmax, Nlevels, cmap_ID, white_levels, Yscale, …), so the plot-controls panel drives this view exactly as it drives the data.

Return type:

matplotlib.axes.Axes

pyrate_ta.plot.matrix.plot_data_fit_residuals(fit, dataset, *, ax=None, fig=None, zscale_factor=10.0, **contour_kwargs)[source]#

Plot 3-column side-by-side contour maps of (a) Data, (b) Fit, and (c) Residuals.

The Data and Fit panels share the exact same Z contour scale (Zmin, Zmax derived from Data). The Residuals panel uses a Z contour scale zoomed in by zscale_factor (default 10x, i.e. Zmax_res = Zmax_data / 10.0).

Parameters:
  • fit (FitResult) – The fit result carrying .C, .S, .R, .t, .probe.

  • dataset (pymorgan.Dataset1D) – The measured dataset.

  • ax (sequence of 3 Axes, optional) – 3 subplot axes to render into.

  • fig (matplotlib.figure.Figure, optional) – Parent figure.

  • zscale_factor (float, default 10.0) – Scale factor for the residual panel Z contour range relative to Data and Fit.

  • **contour_kwargs – Passed to PyMORGAN’s plot_contour.

Returns:

Tuple of 3 matplotlib axes.

Return type:

(ax_data, ax_fit, ax_res)

Plotting routines for Lifetime Density Analysis (LDA).

pyrate_ta.plot.lda.plot_lda_map(result, ax=None, ax_int=None, cmap=None, discrete_taus=None, discrete_tau_color='#27ae60', title='Lifetime Density Map', show_integrated=True, metric='abs', annotate_centroids=True, asinh=False, Asinh=None, asinh_pct=None)[source]#

Plot 2D heatmap of lifetime amplitudes S(tau, probe) and integrated dynamics.

Parameters:
  • result (LDAResult) – The LDA result.

  • ax (matplotlib.axes.Axes or tuple of (Axes, Axes), optional) – If None, creates a 2-panel figure with synced Y-axis (Map + Integrated Dynamics). Can also be passed as a tuple (ax_map, ax_int).

  • ax_int (matplotlib.axes.Axes, optional) – Dedicated axis for the integrated dynamics panel when ax is the map axis.

  • cmap (str, optional) – Colourmap (defaults to PyMORGAN’s active 2D colormap setting).

  • discrete_taus (sequence of float, optional) – Discrete fit lifetimes to overlay as horizontal dashed lines.

  • title (str) – Plot title.

  • show_integrated (bool, default True) – Include the synced vertical panel of integrated absolute dynamics or dynamical content.

  • metric ({"abs", "dynamical_content", "sqrt_sq"}) –

    • "abs": absolute integral \(A(\tau) = \int |S(\lambda, \tau)| d\lambda\).

    • "dynamical_content" / "sqrt_sq": dynamical content \(D(\tau) = \sqrt{\int S(\lambda, \tau)^2 d\lambda}\).

  • annotate_centroids (bool, default True) – Annotate detected lifetime peak centroids with their lifetime text.

  • asinh (bool, default False) – Apply arcsinh color scaling (compressing large amplitudes while keeping linear zero).

  • Asinh (bool, default False) – Apply arcsinh color scaling (compressing large amplitudes while keeping linear zero).

  • asinh_pct (float, optional) – Linear threshold for arcsinh color scaling as percentage of vmax (defaults to settings.asinh_pct).

  • discrete_tau_color (str)

Return type:

matplotlib.axes.Axes or tuple of (Axes, Axes)

pyrate_ta.plot.lda.plot_l_curve(result, ax=None, title='L-Curve Corner Detection')[source]#

Plot the L-curve (log residual vs log solution norm) and corner choice.

Parameters:
Return type:

matplotlib.axes.Axes

Kinetic and spectral trace plots with optional fitted overlay and linked residuals panel.

pyrate_ta.plot.traces.setup_trace_legend(ax_trace, *, fig=None, fit_lines=None, legend_loc=None, settings=None)[source]#

Build a clean, readable legend on ax_trace following PyMORGAN styling.

By default, places the draggable legend outside the trace axis to the right (matching PyMORGAN’s default legend_location="outside right") with a readable font size, clear combined data+fit handles (marker + line), and semi-transparent frame, without clipping off the figure boundary. Any matplotlib loc (e.g. 'best', 'upper left') places the legend inside the trace panel instead.

Parameters:
  • ax_trace (matplotlib.axes.Axes) – The primary trace axis where the legend is placed.

  • fig (matplotlib.figure.Figure, optional) – Figure owning the axes.

  • fit_lines (list of matplotlib.lines.Line2D, optional) – Fitted curve lines corresponding to the data curves.

  • legend_loc (str, optional) – Target location for the legend. Defaults to PyMORGAN’s legend_location ("outside right").

  • settings (Settings, optional) – PyRATE-TA settings object.

Returns:

The created Legend object (or None) and a tight_layout rect tuple (or None if inside layout is used).

Return type:

(legend, layout_rect)

pyrate_ta.plot.traces.plot_kinetics_with_residuals(dataset, cuts, fit=None, *, incl_residuals=True, ax=None, fig=None, normY=False, doSmooth=0, height_ratio=None, hspace=None, legend_loc=None, settings=None, **kwargs)[source]#

Plot kinetic traces at selected positions with fit overlay and linked residuals.

Parameters:
  • dataset (pymorgan.Dataset1D) – The dataset containing measured kinetic data.

  • cuts (sequence of float) – Probe positions to cut at.

  • fit (FitResult, optional) – Fitted model result object carrying .C, .S, .R, .t, .probe. If provided, fitted curves are overlaid as solid lines.

  • incl_residuals (bool, default True) – Whether to include a linked residuals panel below when fit is provided.

  • ax (matplotlib.axes.Axes or sequence of Axes, optional) – Existing axis (or top trace axis / pair of subplots). If fit is provided and residuals are plotted, a 2x1 subplot figure with linked x-axis is created when ax is None.

  • fig (matplotlib.figure.Figure, optional) – Figure owning the axes.

  • normY (bool, default False) – Normalise each trace to its peak amplitude.

  • doSmooth (int, default 0) – Smoothing width in points.

  • height_ratio (float, optional) – Aspect ratio of trace axis height to residual axis height (e.g. 4.0 for 4:1, 3.0 for 3:1). Defaults to Settings.residuals_height_ratio.

  • hspace (float, optional) – Vertical spacing between trace panel and residual panel. Defaults to Settings.residuals_hspace.

  • legend_loc (str, optional) – Location for the legend. Defaults to 'best' (inside the trace panel).

  • settings (Settings, optional) – PyRATE-TA settings object.

Returns:

The main trace axis (and residual axis if created).

Return type:

(ax_trace, ax_res) or ax_trace

pyrate_ta.plot.traces.plot_spectra_with_residuals(dataset, cuts, fit=None, *, incl_residuals=True, ax=None, fig=None, normY=False, doSmooth=0, height_ratio=None, hspace=None, legend_loc=None, settings=None, Abs=None, Em=None, **kwargs)[source]#

Plot transient spectra at selected positions with fit overlay and linked residuals.

Parameters:
  • dataset (pymorgan.Dataset1D) – The dataset containing measured spectral data.

  • cuts (sequence of float) – Delay times to cut at.

  • fit (FitResult, optional) – Fitted model result object carrying .C, .S, .R, .t, .probe. If provided, fitted curves are overlaid as solid lines.

  • incl_residuals (bool, default True) – Whether to include a linked residuals panel below when fit is provided.

  • ax (matplotlib.axes.Axes or sequence of Axes, optional) – Existing axis (or top trace axis / pair of subplots). If fit is provided and residuals are plotted, a 2x1 subplot figure with linked x-axis is created when ax is None.

  • fig (matplotlib.figure.Figure, optional) – Figure owning the axes.

  • normY (bool, default False) – Normalise each trace to its peak amplitude.

  • doSmooth (int, default 0) – Smoothing width in points.

  • height_ratio (float, optional) – Aspect ratio of trace axis height to residual axis height (e.g. 4.0 for 4:1, 3.0 for 3:1). Defaults to Settings.residuals_height_ratio.

  • hspace (float, optional) – Vertical spacing between trace panel and residual panel. Defaults to Settings.residuals_hspace.

  • legend_loc (str, optional) – Location for the legend. Defaults to 'best' (inside the trace panel).

  • settings (Settings, optional) – PyRATE-TA settings object.

  • Abs (dict or pymorgan.steadyState.Spectrum, optional) – Steady-state absorption overlay with {"X": x, "Y": y} or a Spectrum.

  • Em (dict or pymorgan.steadyState.Spectrum, optional) – Steady-state emission overlay with {"X": x, "Y": y} or a Spectrum. Stimulated-emission factor (\(\lambda^4\)) is applied automatically.

Returns:

The main trace axis (and residual axis if created).

Return type:

(ax_trace, ax_res) or ax_trace

The live view of a fit: where each parameter stands, right now.

A bar per free parameter, its current value written above it and its name below. Deliberately not a convergence plot of the cost: what one wants to see while a global fit grinds is whether a lifetime is running away to the edge of the delay window, whether two components are collapsing onto each other, or whether time zero is drifting – all of which are visible in the parameters themselves and none of which show in the cost.

Qt-free on purpose: this draws into a Matplotlib axis and nothing else, so it can be exercised headlessly and reused for a static “how did the fit get there” figure. The window that hosts it lives in pyrate_ta.gui.monitor.

pyrate_ta.plot.monitor.plot_parameter_bars(values, names=None, ax=None, *, fixed=None, scale='symlog', title=None, value_format='%.4g')[source]#

Draw one labelled bar per parameter.

Parameters:
  • values (array_like) – Current parameter values, in the model’s own units.

  • names (sequence of str, optional) – Parameter names, used as the tick labels. Defaults to p1, p2…

  • fixed (sequence of bool, optional) – Which parameters are held fixed; those bars are drawn greyed, since a bar that never moves would otherwise look like a parameter that has converged.

  • scale ({"symlog", "log", "linear"}) – Height scale. symlog is the default because lifetimes span decades while t0 sits at zero and may be negative.

  • title (str, optional) – Title line, e.g. the iteration count and cost.

  • value_format (str)

Return type:

matplotlib.axes.Axes

pyrate_ta.plot.monitor.plot_parameter_history(history, names=None, ax=None, *, scale='symlog', title=None)[source]#

Every parameter against the evaluation number: the path the fit took.

The companion to plot_parameter_bars() – bars answer “where is it now?”, this answers “how did it get here?”, which is what tells a slow fit from a stuck one.

Parameters:

scale (str)

Session, Tabular Export & Reference I/O (pyrate_ta.io)#

Tabular and 2D surface export of fitted spectra, concentrations, surfaces, and reports.

Exports use a single uncommented header row by default (no # preamble lines), so every CSV opens cleanly in Excel, OriginPro, pandas.read_csv, numpy.loadtxt(..., delimiter=",", skiprows=1), and numpy.genfromtxt(..., delimiter=",", names=True). Two-dimensional Data, Fit, and Residual surfaces always follow the PyMORGAN .pdat orientation (rows = delays, columns = probe; never transposed) and can be written either as clean single-header .csv/.tsv matrices or as native .pdat files via pymorgan.write_pdat(). Full run provenance, fitted parameters with 1-sigma uncertainties, solver diagnostics, target rate matrices, GSB/SE scale factors, and literature citations are written to a companion human-readable .txt summary sharing the same YYYYMMDD-HHMMSS timestamp, with optional single-file .zip bundling.

class pyrate_ta.io.export.ExportedSurfacePaths(data, fit, residuals, summary, timestamp, archive=None)[source]#

Bases: NamedTuple

Paths written by export_surfaces(), plus their shared timestamp.

Parameters:
data: Path#

Alias for field number 0

fit: Path#

Alias for field number 1

residuals: Path#

Alias for field number 2

summary: Path#

Alias for field number 3

timestamp: str#

Alias for field number 4

archive: Path | None#

Alias for field number 5

class pyrate_ta.io.export.ExportedFitPaths(spectra, concentrations, summary, timestamp, data=None, fit=None, residuals=None, archive=None)[source]#

Bases: NamedTuple

Paths written by export_fit_results(), plus their shared timestamp.

Parameters:
spectra: Path#

Alias for field number 0

concentrations: Path#

Alias for field number 1

summary: Path#

Alias for field number 2

timestamp: str#

Alias for field number 3

data: Path | None#

Alias for field number 4

fit: Path | None#

Alias for field number 5

residuals: Path | None#

Alias for field number 6

archive: Path | None#

Alias for field number 7

pyrate_ta.io.export.make_timestamp(dt=None)[source]#

Return a filesystem-safe YYYYMMDD-HHMMSS timestamp string.

Parameters:

dt (datetime | None)

Return type:

str

pyrate_ta.io.export.format_fit_report(fit, *, dataset=None, timestamp=None, bleach_result=None)[source]#

Format a complete terminal-style human-readable report for a fit result.

Covers the run banner, dataset and fitted window provenance, noise weighting, solver convergence diagnostics, fitted lifetimes with 1-sigma uncertainties and corresponding rate constants k = 1/tau, IRF/time-zero and coherent-artefact settings, fit statistics, target scheme & K matrix + eigenvalues (for TargetFit), GSB/SE scale factors (when applicable), and relevant literature citations.

Parameters:
  • fit (Any)

  • dataset (Any)

  • timestamp (str | None)

  • bleach_result (Any)

Return type:

str

pyrate_ta.io.export.export_fit_summary(fit_or_path=None, path_or_fit=None, *, fit=None, path=None, dataset=None, timestamp=None, bleach_result=None, directory=None)[source]#

Write the companion human-readable .txt fit report to disk.

Accepts either export_fit_summary(fit, path=None) or export_fit_summary(path, fit). When path is omitted, writes <stem>_fit_summary_<YYYYMMDD-HHMMSS>.txt beside fit.source (or in directory / the current working directory).

Parameters:
Return type:

Path

pyrate_ta.io.export.export_spectra(fit_or_path=None, path_or_fit=None, *, fit=None, path=None, dataset=None, recover_gsb=False, S_abs=None, bleach_result=None, gs_spectrum=None, em_spectrum=None, include_artifact=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export fitted species-associated spectra (DAS, EAS, or SAS) to CSV.

Parameters:
  • fit_or_path (Any) – The fit result (KineticFit or LoadedFit) and optional destination path, in either order. When no path is supplied, defaults to <stem>_<DAS|EAS|SAS>_<YYYYMMDD-HHMMSS>.csv.

  • path_or_fit (Any) – The fit result (KineticFit or LoadedFit) and optional destination path, in either order. When no path is supplied, defaults to <stem>_<DAS|EAS|SAS>_<YYYYMMDD-HHMMSS>.csv.

  • dataset (pymorgan.Dataset1D, optional) – Dataset providing axis units and steady-state reference spectra (gs_spectrum / em_spectrum) when GSB/SE recovery is enabled.

  • recover_gsb (bool, default False) – When True (or when S_abs is supplied), append pure-positive GSB/SE-recovered columns <KIND>_<species>_abs side by side after the differential <KIND>_<species> columns in the same CSV.

  • S_abs (array_like, optional) – Pre-computed pure-positive spectra (Np, n_kinetic).

  • gs_spectrum (array_like, optional) – Explicit steady-state absorption / emission reference spectra on the dataset or fitted probe grid.

  • em_spectrum (array_like, optional) – Explicit steady-state absorption / emission reference spectra on the dataset or fitted probe grid.

  • include_artifact (bool, default False) – Append coherent-artefact amplitude spectra (Art_IRF, Art_dIRF/dt, Art_d2IRF/dt2) when present on fit.

  • metadata (bool, default False) – Keep False (default) for a single uncommented header row with zero # lines. Set True only if # provenance comments are wanted at the top of the file.

  • timestamp (str, optional) – Shared YYYYMMDD-HHMMSS timestamp; defaults to fit.timestamp.

  • write_summary (bool, default False) – Also write <stem>_fit_summary_<timestamp>.txt in the same folder.

  • directory (str or Path, optional) – Output folder used when path is omitted.

  • fmt (str, default "%.12g") – Numeric format string passed to numpy.savetxt().

  • fit (Any)

  • path (str | PathLike[str] | None)

  • bleach_result (Any)

Returns:

Path to the written CSV/TSV file.

Return type:

pathlib.Path

pyrate_ta.io.export.export_concentrations(fit_or_path=None, path_or_fit=None, *, fit=None, path=None, dataset=None, normalise=False, include_irf=True, include_artifact=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export fitted concentration / population profiles C(t) to CSV.

Parameters:
  • fit_or_path (Any) – The fit result (KineticFit or LoadedFit) and optional destination path, in either order. When no path is supplied, defaults to <stem>_concentrations_<YYYYMMDD-HHMMSS>.csv.

  • path_or_fit (Any) – The fit result (KineticFit or LoadedFit) and optional destination path, in either order. When no path is supplied, defaults to <stem>_concentrations_<YYYYMMDD-HHMMSS>.csv.

  • dataset (pymorgan.Dataset1D, optional) – Dataset providing the time-axis unit when not already stored on fit.

  • normalise (bool, default False) – Scale each species column to unit peak magnitude, matching plot_concentrations(..., normalise=True).

  • include_irf (bool, default True) – Append an IRF Gaussian response column (matching the grey shaded IRF envelope in plot_concentrations()) whenever fit.irf_fwhm is finite and positive.

  • include_artifact (bool, default False) – Append the coherent-artefact design basis columns (Art_IRF, Art_dIRF/dt, Art_d2IRF/dt2) when present in fit.C.

  • metadata (bool, default False) – Keep False (default) for a single uncommented header row with zero # lines.

  • timestamp (str, optional) – Shared YYYYMMDD-HHMMSS timestamp; defaults to fit.timestamp.

  • write_summary (bool, default False) – Also write <stem>_fit_summary_<timestamp>.txt in the same folder.

  • directory (str or Path, optional) – Output folder used when path is omitted.

  • fmt (str, default "%.12g") – Numeric format string passed to numpy.savetxt().

  • fit (Any)

  • path (str | PathLike[str] | None)

Returns:

Path to the written CSV/TSV file.

Return type:

pathlib.Path

pyrate_ta.io.export.compute_surface_matrix(fit, kind='fit', *, include_artifact=True, weighted_residuals=False)[source]#

Return (canonical_kind, Z) on the (Nd, Np) PDAT grid (delays x probe).

  • "fit": C @ S.T (includes coherent-artefact columns when include_artifact=True so data - fit == residuals holds identically).

  • "residuals": unweighted R = D - C @ S.T on fit.R (or scaled by 1/sigma when weighted_residuals=True and weights are active).

  • "data": C_full @ S_full.T + R on the exact fitted (t, probe) window, so all three surfaces share identical (Nd, Np) axes even when reconstructed from a reopened .prfit session without the raw file.

Parameters:
  • fit (Any)

  • kind (str)

  • include_artifact (bool)

  • weighted_residuals (bool)

Return type:

tuple[str, ndarray]

pyrate_ta.io.export.export_surface(fit_or_path=None, path_or_fit=None, *, kind='fit', fit=None, path=None, dataset=None, surface_format='csv', include_artifact=True, weighted_residuals=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export one 2D surface (data, fit, or residuals) in .csv, .tsv, or .pdat.

Surfaces always follow the PyMORGAN .pdat convention (never transposed): rows correspond to delays t (Nd) and columns correspond to probe coordinates probe (Np).

  • For .csv / .tsv: writes a single header row Delay (ps) \ Wavelength (nm), <probe_1>, <probe_2>, ... with zero # comment lines by default, followed by [t | Z].

  • For .pdat: delegates directly to pymorgan.write_pdat() so the exported surface loads straight back into PyMORGAN or PyRATE-TA via pymorgan.load_1D(...).

Parameters:
Return type:

Path

pyrate_ta.io.export.export_surfaces(fit_or_dir=None, dir_or_fit=None, *, fit=None, directory=None, dataset=None, surface_format='csv', as_zip=False, zip_path=None, keep_files=False, stem_override=None, include_artifact=True, weighted_residuals=False, metadata=False, timestamp=None, bleach_result=None, fmt='%.12g')[source]#

Export all 3 surfaces (data, fit, residuals) + .txt summary at once.

All files share the same YYYYMMDD-HHMMSS timestamp and .pdat orientation (rows = delays, columns = probe; never transposed). Pass as_zip=True (or a .zip path as directory / zip_path) to bundle everything into a single .zip archive.

Parameters:
Return type:

ExportedSurfacePaths

pyrate_ta.io.export.export_fit_results(fit_or_dir=None, dir_or_fit=None, *, fit=None, directory=None, dataset=None, recover_gsb=False, S_abs=None, bleach_result=None, gs_spectrum=None, em_spectrum=None, normalise_concentrations=False, include_irf=True, include_artifact=False, include_surfaces=True, surface_format='csv', include_artifact_in_surfaces=True, weighted_residuals=False, as_zip=False, zip_path=None, keep_files=False, stem_override=None, metadata=False, timestamp=None, fmt='%.12g')[source]#

Export DAS/EAS/SAS, concentrations, 2D surfaces, and .txt summary together.

Accepts export_fit_results(fit, directory=None) or export_fit_results(directory, fit) (including a .zip path). Every output file shares the same YYYYMMDD-HHMMSS timestamp:

  • <stem>_<DAS|EAS|SAS>_<timestamp>.csv

  • <stem>_concentrations_<timestamp>.csv

  • <stem>_data_<timestamp>.<csv|tsv|pdat> (when include_surfaces=True)

  • <stem>_fit_<timestamp>.<csv|tsv|pdat> (when include_surfaces=True)

  • <stem>_residuals_<timestamp>.<csv|tsv|pdat> (when include_surfaces=True)

  • <stem>_fit_summary_<timestamp>.txt

Set as_zip=True (or pass a .zip destination path) to bundle all files into a single <stem>_fit_results_<timestamp>.zip archive.

Parameters:
Return type:

ExportedFitPaths

Saving and reopening a fit session.

One file, .prfit, holding both halves of a result: the arrays (spectra, concentration profiles, residuals, axes) as a compressed .npz, and the reproducibility payload as a JSON string inside it. Keeping them together means a saved fit cannot lose its provenance – a spectra file with no record of the model, the window fitted or the noise weighting is not reproducible, and the whole point of the payload is that it travels with the numbers.

What is written#

  • model identity: family, component count, and the scheme in its own notation when there is one, so a target fit reopens as editable text;

  • the parameters, their uncertainties, the fixed/free mask and the bounds;

  • what the fit actually saw: delay and probe ranges, clipping, detector, source file, and where the noise came from;

  • the solver’s report and the statistic, including which kind it is.

The format is PyRATE’s own and deliberately simple: numpy and a JSON document, no third-party dependency and nothing that needs this package’s version to read.

pyrate_ta.io.session.FORMAT_VERSION = 1#

Bumped when the layout of the JSON payload changes incompatibly.

pyrate_ta.io.session.save_fit(path, fit)[source]#

Write a fit result to a .prfit file.

Parameters:
  • path (str or Path) – Destination. The .prfit suffix is added when missing.

  • fit (KineticFit) – Any result from pyrate_ta.fit.

Returns:

The file actually written.

Return type:

pathlib.Path

class pyrate_ta.io.session.LoadedFit(meta, arrays)[source]#

Bases: object

A reopened fit: the arrays as attributes, the payload as meta.

Deliberately not a live KineticFit. A reopened session has no dataset behind it and cannot be refitted as it stands, and returning something that looks like a fresh result would invite exactly that. Everything needed to set the fit up again is in meta.

Parameters:
property converged: bool#
property spectra_kind: str#

DAS, EAS or SAS.

Type:

What this reopened fit’s amplitude spectra are called

property n_kinetic: int#

Columns of C/S that are kinetic components, artefact aside.

species_labels()[source]#

Names of the species/compartments for DAS/EAS/SAS plots and exports.

Return type:

list[str]

summary()[source]#

The same shape of summary a live result prints.

Return type:

str

format_report(*, dataset=None, timestamp=None, bleach_result=None)[source]#

Format a detailed terminal-style fit report string.

Parameters:

timestamp (str | None)

Return type:

str

export_spectra(path=None, *, dataset=None, recover_gsb=False, S_abs=None, bleach_result=None, gs_spectrum=None, em_spectrum=None, include_artifact=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export DAS/EAS/SAS spectra to a single-header CSV file.

Parameters:
  • recover_gsb (bool)

  • include_artifact (bool)

  • metadata (bool)

  • timestamp (str | None)

  • write_summary (bool)

  • fmt (str)

Return type:

Path

export_concentrations(path=None, *, dataset=None, normalise=False, include_irf=True, include_artifact=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export concentration profiles C(t) to a single-header CSV file.

Parameters:
  • normalise (bool)

  • include_irf (bool)

  • include_artifact (bool)

  • metadata (bool)

  • timestamp (str | None)

  • write_summary (bool)

  • fmt (str)

Return type:

Path

property fitted_surface: ndarray#

Reconstructed 2D fitted surface C @ S.T of shape (Nd, Np).

property data_surface: ndarray#

Fitted-window 2D data surface C @ S.T + R of shape (Nd, Np).

export_surface(path=None, *, kind='fit', dataset=None, surface_format='csv', include_artifact=True, weighted_residuals=False, metadata=False, timestamp=None, write_summary=False, directory=None, fmt='%.12g')[source]#

Export one 2D surface (data, fit, or residuals) as CSV/TSV or PDAT.

Parameters:
  • kind (str)

  • surface_format (str)

  • include_artifact (bool)

  • weighted_residuals (bool)

  • metadata (bool)

  • timestamp (str | None)

  • write_summary (bool)

  • fmt (str)

Return type:

Path

export_surfaces(directory=None, *, dataset=None, surface_format='csv', as_zip=False, zip_path=None, keep_files=False, stem_override=None, include_artifact=True, weighted_residuals=False, metadata=False, timestamp=None, bleach_result=None, fmt='%.12g')[source]#

Export all 3 surfaces (data, fit, residuals) + .txt summary.

Parameters:
  • surface_format (str)

  • as_zip (bool)

  • keep_files (bool)

  • stem_override (str | None)

  • include_artifact (bool)

  • weighted_residuals (bool)

  • metadata (bool)

  • timestamp (str | None)

  • fmt (str)

export_summary(path=None, *, dataset=None, timestamp=None, bleach_result=None, directory=None)[source]#

Export the companion human-readable .txt fit report.

Parameters:

timestamp (str | None)

Return type:

Path

export_results(directory=None, *, dataset=None, recover_gsb=False, S_abs=None, bleach_result=None, gs_spectrum=None, em_spectrum=None, normalise_concentrations=False, include_irf=True, include_artifact=False, include_surfaces=True, surface_format='csv', include_artifact_in_surfaces=True, weighted_residuals=False, as_zip=False, zip_path=None, keep_files=False, stem_override=None, metadata=False, timestamp=None, fmt='%.12g')[source]#

Export spectra, concentrations, 2D surfaces, and summary TXT (or single .zip).

Parameters:
  • recover_gsb (bool)

  • normalise_concentrations (bool)

  • include_irf (bool)

  • include_artifact (bool)

  • include_surfaces (bool)

  • surface_format (str)

  • include_artifact_in_surfaces (bool)

  • weighted_residuals (bool)

  • as_zip (bool)

  • keep_files (bool)

  • stem_override (str | None)

  • metadata (bool)

  • timestamp (str | None)

  • fmt (str)

pyrate_ta.io.session.load_fit(path)[source]#

Reopen a .prfit file.

Raises:

ValueError – If the file was written by a newer, incompatible format version. A silently mis-read session would be worse than a refusal.

Return type:

LoadedFit

pyrate_ta.io.session.default_session_path(fit, directory=None)[source]#

Where a session is written when nobody chooses: beside the dataset.

scan.pdat gives scan_fit.prfit. With no source (an array fit) the name falls back to pyrate_fit.prfit in directory or the working directory.

Return type:

Path

Steady-state reference spectra (absorption and emission) I/O and processing.

pyrate_ta.io.reference.load_reference_spectrum(source)[source]#

Robustly load a 1D reference spectrum from a file or text buffer.

Handles arbitrary comment markers (#, %, ;, //, *), header lines, multiple delimiter types (comma, tab, whitespace, semicolon), duplicate coordinates, and arbitrary probe axis orientation (ascending or descending).

Parameters:

source (str, Path, or StringIO) – Path to file or file-like buffer containing tabular numeric data.

Returns:

(x, y) – Sorted ascending probe coordinates and corresponding spectral amplitudes.

Return type:

tuple of numpy.ndarray

Raises:

ValueError – If no valid 2-column numeric data can be parsed.

pyrate_ta.io.reference.interpolate_reference_spectrum(x_raw, y_raw, probe_grid, *, left=0.0, right=0.0, clip_non_negative=True)[source]#

Interpolate a reference spectrum onto the dataset’s probe grid.

Parameters:
  • x_raw (numpy.ndarray) – Raw reference probe coordinates (sorted ascending).

  • y_raw (numpy.ndarray) – Raw reference intensities.

  • probe_grid (numpy.ndarray) – Target probe grid of the transient dataset.

  • left (float, default 0.0) – Values assigned outside the raw spectrum’s spectral coverage window.

  • right (float, default 0.0) – Values assigned outside the raw spectrum’s spectral coverage window.

  • clip_non_negative (bool, default True) – Clamp negative baseline values to zero (physical for absorption and emission).

Returns:

Interpolated spectrum matching probe_grid.shape.

Return type:

numpy.ndarray

Raises:

ValueError – If the raw spectrum does not overlap with the target probe window at all.

Settings & Citations (pyrate_ta.settings, pyrate_ta.cite)#

Analysis settings for PyRATE.

Aesthetics are not duplicated here. Label style, colourmap, time-axis convention and figure sizes belong to PyMORGAN’s pymorgan.Settings; call pymorgan.apply_style() and read pymorgan.get_settings() for those. This module holds only what is genuinely analysis-specific: solver tolerances, iteration limits, defaults for new fits and how the instrument response is treated.

Design follows PyMORGAN exactly, so the two feel the same and the GUI panels can share code:

  • Settings is a dataclass and the dataclass field is the single source of truth. __post_init__ (enum coercion), Settings.to_dict(), Settings.from_dict() and update_settings() are all derived from dataclasses.fields() plus the resolved annotations, so a new setting needs only the field – no serialisation edits.

  • Settings.field_specs() drives the GUI settings panel and is derived from the fields, their annotations and Settings.field_comments(), so a new setting is editable in the interface as soon as it exists. A small override table refines labels and ranges.

  • Enums are enum.StrEnum (3.11+): str(member) is the value, so they serialise and compare as plain strings while staying type-checked.

  • settings.toml is read and written with tomlkit, so user comments survive a save.

This module never imports Qt.

class pyrate_ta.settings.IRFMode(*values)[source]#

Bases: StrEnum

How the instrument response is handled in a fit.

NONE = 'None'#
GAUSSIAN = 'Gaussian'#
CLIP = 'Clip'#
class pyrate_ta.settings.Regularisation(*values)[source]#

Bases: StrEnum

How the LDA regularisation strength is chosen.

LCURVE = 'L-curve'#
GCV = 'GCV'#
FIXED = 'Fixed'#
class pyrate_ta.settings.ModelType(*values)[source]#

Bases: StrEnum

Kinetic model family, which decides what the species spectra mean.

PARALLEL = 'Parallel'#
SEQUENTIAL = 'Sequential'#
TARGET = 'Target'#
class pyrate_ta.settings.Settings(n_components=2, model_type=ModelType.SEQUENTIAL, time_limits=(0.2, None), ftol=1e-08, xtol=1e-08, max_iterations=2000, variable_projection=True, irf_mode=IRFMode.GAUSSIAN, irf_fwhm=None, t_min=None, use_noise_weights=False, noise_floor_fraction=0.001, degeneracy_warn_ratio=1.2, lda_n_lifetimes=100, lda_tau_min=None, lda_tau_max=None, lda_regularisation=Regularisation.LCURVE, lda_alpha=0.001, lda_non_negative=False, data_marker='o', data_alpha=0.5, data_markersize=3.0, fit_linestyle='-', fit_linewidth=1.0, fit_alpha=1.0, residuals_height_ratio=4.0, residuals_hspace=0.05, panel_left=0.09, panel_right=0.975, panel_top=0.95, panel_bottom=0.14, panel_hspace=0.66, panel_wspace=0.32, fit_monitor_every=0, fit_monitor_scale='symlog', window_width=1010, window_height=860, restore_window_size=True, table_default_lb=0.0, table_default_ub=inf, table_decimals=4, new_rows_fixed=False, plot_species_after_fit=True, plot_profiles_after_fit=True, plot_trio_after_fit=True, open_scheme_after_fit=False, autosave_session=False, default_datadir=None, schemes_dir=None)[source]#

Bases: object

Analysis-only settings. Presentation lives in pymorgan.Settings.

Parameters:
n_components: int = 2#
model_type: ModelType = 'Sequential'#
time_limits: tuple[float | None, float | None] = (0.2, None)#
ftol: float = 1e-08#
xtol: float = 1e-08#
max_iterations: int = 2000#
variable_projection: bool = True#
irf_mode: IRFMode = 'Gaussian'#
irf_fwhm: float | None = None#
t_min: float | None = None#
use_noise_weights: bool = False#
noise_floor_fraction: float = 0.001#
degeneracy_warn_ratio: float = 1.2#
lda_n_lifetimes: int = 100#
lda_tau_min: float | None = None#
lda_tau_max: float | None = None#
lda_regularisation: Regularisation = 'L-curve'#
lda_alpha: float = 0.001#
lda_non_negative: bool = False#
data_marker: str = 'o'#
data_alpha: float = 0.5#
data_markersize: float = 3.0#
fit_linestyle: str = '-'#
fit_linewidth: float = 1.0#
fit_alpha: float = 1.0#
residuals_height_ratio: float = 4.0#
residuals_hspace: float = 0.05#
panel_left: float = 0.09#
panel_right: float = 0.975#
panel_top: float = 0.95#
panel_bottom: float = 0.14#
panel_hspace: float = 0.66#
panel_wspace: float = 0.32#
fit_monitor_every: int = 0#
fit_monitor_scale: str = 'symlog'#
window_width: int = 1010#
window_height: int = 860#
restore_window_size: bool = True#
table_default_lb: float = 0.0#
table_default_ub: float = inf#
table_decimals: int = 4#
new_rows_fixed: bool = False#
plot_species_after_fit: bool = True#
plot_profiles_after_fit: bool = True#
plot_trio_after_fit: bool = True#
open_scheme_after_fit: bool = False#
autosave_session: bool = False#
property plot_data_fit_residuals_after_fit: bool#
property asinh_pct: float#
property show_uncertainties: bool#
property round_uncertainties: bool#
property gui_theme: str#
default_datadir: Path | None = None#
schemes_dir: Path | None = None#
to_dict()[source]#

Plain mapping, with enums as their string values.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]#

Build from a mapping, ignoring unknown keys.

Parameters:

data (dict[str, Any])

Return type:

Settings

save(path)[source]#

Write the settings to path as TOML, preserving any comments.

Parameters:

path (str | Path)

Return type:

None

classmethod load(path=None)[source]#

Read a Settings from a TOML file.

Parameters:

path (str | Path | None)

Return type:

Settings

static field_sections()[source]#

Which settings.toml section each field is written to.

Every field must appear here: a field with no section would be written at the top level and read back inconsistently, so save_settings() refuses rather than guessing.

Return type:

dict[str, str]

static section_titles()[source]#

One-line description written above each section of the TOML file.

Return type:

dict[str, str]

static field_comments()[source]#

Comment written above each key, so the file explains itself.

Return type:

dict[str, str]

static field_specs()[source]#

Specs driving the GUI settings panel – derived, then refined.

Every field gets an entry automatically: the widget kind from its annotation, the page from field_sections() and the tooltip from field_comments(). A new setting therefore reaches the panel as soon as it exists, which is the point – a setting the interface cannot reach is a setting the user does not really have.

_SPEC_OVERRIDES refines the derived entry where the annotation cannot say enough (sensible ranges, a shorter label) and can drop a field from the panel with "skip": True.

Return type:

dict[str, dict[str, Any]]

pyrate_ta.settings.get_settings()[source]#

The active PyRATE-TA settings object.

Return type:

Settings

pyrate_ta.settings.set_settings(settings)[source]#

Replace the active settings wholesale.

Parameters:

settings (Settings)

Return type:

Settings

pyrate_ta.settings.update_settings(**kwargs)[source]#

Update named fields on the active settings, rejecting unknown names.

Parameters:

kwargs (Any)

Return type:

Settings

pyrate_ta.settings.get_default_settings_text()[source]#

Return the raw text of the canonical default settings template.

Return type:

str

pyrate_ta.settings.get_default_settings_doc()[source]#

Parse and return the canonical default settings template as a tomlkit document.

pyrate_ta.settings.settings_path(start=None)[source]#

Where settings.toml is looked for: working directory, then the root.

The same lookup order PyMORGAN uses, so a project directory can override the defaults for both packages in the same way.

Parameters:

start (str | Path | None)

Return type:

Path

pyrate_ta.settings.ensure_settings_file(path=None)[source]#

Ensure that path (defaulting to settings_path()) exists and is up to date.

If the file does not exist, it is generated from settings.default.toml. If the file exists, it is checked for any newly introduced settings from the default template. If missing keys are found, they are merged into the file along with their section comments while preserving all existing user modifications.

Parameters:

path (str | Path | None)

Return type:

Path

pyrate_ta.settings.load_settings(path=None)[source]#

Load settings from a TOML file and make them active.

Ensures the settings file exists (creating from defaults if absent) and merges any newly introduced settings while keeping user modifications.

Parameters:

path (str | Path | None)

Return type:

Settings

pyrate_ta.settings.save_settings(path, settings=None)[source]#

Write the settings to path as TOML, preserving comments.

Parameters:
Return type:

None

Literature references and the “please cite” notice.

Two mechanisms, both going through the pyrate logger rather than print (the console entry points are the exception; see print_citations()):

  • citation_notice() – the start-up banner listing what to cite when results obtained with PyRATE-TA are published.

  • cite() – the per-method citation a routine records when it finishes, so the formalism actually used is traceable. It goes to the debug log: the start-up banner already says what to cite, and a reference printed in the middle of every fit only buries the result. Each key is recorded once per session in any case.

Every entry was checked against Crossref. The forthcoming PyRATE-TA / PyMORGAN paper is listed with its DOI missing on purpose – an invented DOI is worse than a visible gap – and must be completed when it appears.

class pyrate_ta.cite.Reference(key, citation, doi, what)[source]#

Bases: object

One literature reference.

Variables:
  • key (str) – Short identifier used by cite().

  • citation (str) – Human-readable citation, author-year style.

  • doi (str or None) – DOI, or None while a paper is still unpublished.

  • what (str) – What in PyRATE-TA this reference covers, so a log line explains itself.

Parameters:
key: str#
citation: str#
doi: str | None#
what: str#
pyrate_ta.cite.get_reference(key)[source]#

Look up one reference, listing the alternatives on failure.

Parameters:

key (str)

Return type:

Reference

pyrate_ta.cite.cite(*keys, once=True)[source]#

Log the reference(s) for a method that has just run.

Parameters:
  • *keys (str) – Reference keys, e.g. "vanstokkum2004".

  • once (bool) – Skip keys already logged in this session (the default). Pass False to log unconditionally.

Returns:

The references actually logged, so a caller can attach them to a fit result.

Return type:

list of Reference

pyrate_ta.cite.reset_citations()[source]#

Forget which references have been logged (used by the tests).

Return type:

None

pyrate_ta.cite.citation_text(keys=None)[source]#

The “please cite” block, as a plain multi-line string.

keys defaults to every reference: the software paper, then the paper describing the framework, then the two method references.

Parameters:

keys (tuple[str, ...] | list[str] | None)

Return type:

str

pyrate_ta.cite.citation_notice(keys=None)[source]#

Log the citation block through the pyrate logger and return it.

Called by the console entry points at start-up. It goes to logger.info rather than print so that a host application which has configured logging keeps control of where it appears.

Parameters:

keys (tuple[str, ...] | list[str] | None)

Return type:

str

pyrate_ta.cite.print_citations(keys=None)[source]#

Print the citation block to the console.

One of the few sanctioned uses of print: this is an explicit print_* helper for interactive use (python -m pyrate.cite).

Parameters:

keys (tuple[str, ...] | list[str] | None)

Return type:

None