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 thanA,B), and from the model family otherwise.
- 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 withoutCis 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:
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 -> Kbuilder a unit vector shows wherek_iappears, 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.
- 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
objdoes 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 ask_1+k_2where 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:
- 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:
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 apymorgan.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
Sis 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:
- 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
axis 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:
result (LDAResult) – The LDA result.
ax (matplotlib.axes.Axes, optional)
title (str)
- Return type:
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_tracefollowing 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 matplotlibloc(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
fitis provided.ax (matplotlib.axes.Axes or sequence of Axes, optional) – Existing axis (or top trace axis / pair of subplots). If
fitis provided and residuals are plotted, a 2x1 subplot figure with linked x-axis is created whenaxis 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
fitis provided.ax (matplotlib.axes.Axes or sequence of Axes, optional) – Existing axis (or top trace axis / pair of subplots). If
fitis provided and residuals are plotted, a 2x1 subplot figure with linked x-axis is created whenaxis 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 aSpectrum.Em (dict or pymorgan.steadyState.Spectrum, optional) – Steady-state emission overlay with
{"X": x, "Y": y}or aSpectrum. 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.
symlogis the default because lifetimes span decades whilet0sits at zero and may be negative.title (str, optional) – Title line, e.g. the iteration count and cost.
value_format (str)
- Return type:
- 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:
NamedTuplePaths written by
export_surfaces(), plus their shared timestamp.- Parameters:
- class pyrate_ta.io.export.ExportedFitPaths(spectra, concentrations, summary, timestamp, data=None, fit=None, residuals=None, archive=None)[source]#
Bases:
NamedTuplePaths written by
export_fit_results(), plus their shared timestamp.- Parameters:
- pyrate_ta.io.export.make_timestamp(dt=None)[source]#
Return a filesystem-safe
YYYYMMDD-HHMMSStimestamp string.
- 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 &Kmatrix + eigenvalues (forTargetFit), GSB/SE scale factors (when applicable), and relevant literature citations.
- 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
.txtfit report to disk.Accepts either
export_fit_summary(fit, path=None)orexport_fit_summary(path, fit). Whenpathis omitted, writes<stem>_fit_summary_<YYYYMMDD-HHMMSS>.txtbesidefit.source(or indirectory/ the current working directory).
- 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 (
KineticFitorLoadedFit) 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 (
KineticFitorLoadedFit) 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 whenS_absis supplied), append pure-positive GSB/SE-recovered columns<KIND>_<species>_absside 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 onfit.metadata (bool, default False) – Keep
False(default) for a single uncommented header row with zero#lines. SetTrueonly if#provenance comments are wanted at the top of the file.timestamp (str, optional) – Shared
YYYYMMDD-HHMMSStimestamp; defaults tofit.timestamp.write_summary (bool, default False) – Also write
<stem>_fit_summary_<timestamp>.txtin the same folder.directory (str or Path, optional) – Output folder used when
pathis omitted.fmt (str, default
"%.12g") – Numeric format string passed tonumpy.savetxt().fit (Any)
bleach_result (Any)
- Returns:
Path to the written CSV/TSV file.
- Return type:
- 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 (
KineticFitorLoadedFit) 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 (
KineticFitorLoadedFit) 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
IRFGaussian response column (matching the grey shaded IRF envelope inplot_concentrations()) wheneverfit.irf_fwhmis 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 infit.C.metadata (bool, default False) – Keep
False(default) for a single uncommented header row with zero#lines.timestamp (str, optional) – Shared
YYYYMMDD-HHMMSStimestamp; defaults tofit.timestamp.write_summary (bool, default False) – Also write
<stem>_fit_summary_<timestamp>.txtin the same folder.directory (str or Path, optional) – Output folder used when
pathis omitted.fmt (str, default
"%.12g") – Numeric format string passed tonumpy.savetxt().fit (Any)
- Returns:
Path to the written CSV/TSV file.
- Return type:
- 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 wheninclude_artifact=Truesodata - fit == residualsholds identically)."residuals": unweightedR = D - C @ S.Tonfit.R(or scaled by1/sigmawhenweighted_residuals=Trueand weights are active)."data":C_full @ S_full.T + Ron the exact fitted(t, probe)window, so all three surfaces share identical(Nd, Np)axes even when reconstructed from a reopened.prfitsession without the raw file.
- 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, orresiduals) in.csv,.tsv, or.pdat.Surfaces always follow the PyMORGAN
.pdatconvention (never transposed): rows correspond to delayst(Nd) and columns correspond to probe coordinatesprobe(Np).For
.csv/.tsv: writes a single header rowDelay (ps) \ Wavelength (nm), <probe_1>, <probe_2>, ...with zero#comment lines by default, followed by[t | Z].For
.pdat: delegates directly topymorgan.write_pdat()so the exported surface loads straight back into PyMORGAN or PyRATE-TA viapymorgan.load_1D(...).
- Parameters:
- Return type:
- 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) +.txtsummary at once.All files share the same
YYYYMMDD-HHMMSStimestamp and.pdatorientation (rows = delays, columns = probe; never transposed). Passas_zip=True(or a.zippath asdirectory/zip_path) to bundle everything into a single.ziparchive.
- 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
.txtsummary together.Accepts
export_fit_results(fit, directory=None)orexport_fit_results(directory, fit)(including a.zippath). Every output file shares the sameYYYYMMDD-HHMMSStimestamp:<stem>_<DAS|EAS|SAS>_<timestamp>.csv<stem>_concentrations_<timestamp>.csv<stem>_data_<timestamp>.<csv|tsv|pdat>(wheninclude_surfaces=True)<stem>_fit_<timestamp>.<csv|tsv|pdat>(wheninclude_surfaces=True)<stem>_residuals_<timestamp>.<csv|tsv|pdat>(wheninclude_surfaces=True)<stem>_fit_summary_<timestamp>.txt
Set
as_zip=True(or pass a.zipdestination path) to bundle all files into a single<stem>_fit_results_<timestamp>.ziparchive.- Parameters:
fit_or_dir (Any)
dir_or_fit (Any)
fit (Any)
dataset (Any)
recover_gsb (bool)
S_abs (Any)
bleach_result (Any)
gs_spectrum (Any)
em_spectrum (Any)
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)
- Return type:
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
.prfitfile.- Parameters:
path (str or Path) – Destination. The
.prfitsuffix is added when missing.fit (KineticFit) – Any result from
pyrate_ta.fit.
- Returns:
The file actually written.
- Return type:
- class pyrate_ta.io.session.LoadedFit(meta, arrays)[source]#
Bases:
objectA 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 inmeta.- property spectra_kind: str#
DAS, EAS or SAS.
- Type:
What this reopened fit’s amplitude spectra are called
- format_report(*, dataset=None, timestamp=None, bleach_result=None)[source]#
Format a detailed terminal-style fit report string.
- 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.
- 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.
- 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, orresiduals) as CSV/TSV or PDAT.
- 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) +.txtsummary.
- export_summary(path=None, *, dataset=None, timestamp=None, bleach_result=None, directory=None)[source]#
Export the companion human-readable
.txtfit report.
- 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
.prfitfile.- 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:
- pyrate_ta.io.session.default_session_path(fit, directory=None)[source]#
Where a session is written when nobody chooses: beside the dataset.
scan.pdatgivesscan_fit.prfit. With no source (an array fit) the name falls back topyrate_fit.prfitindirectoryor the working directory.- Return type:
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:
- 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:
- 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:
Settingsis a dataclass and the dataclass field is the single source of truth.__post_init__(enum coercion),Settings.to_dict(),Settings.from_dict()andupdate_settings()are all derived fromdataclasses.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 andSettings.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.tomlis read and written withtomlkit, so user comments survive a save.
This module never imports Qt.
- class pyrate_ta.settings.IRFMode(*values)[source]#
Bases:
StrEnumHow the instrument response is handled in a fit.
- NONE = 'None'#
- GAUSSIAN = 'Gaussian'#
- CLIP = 'Clip'#
- class pyrate_ta.settings.Regularisation(*values)[source]#
Bases:
StrEnumHow the LDA regularisation strength is chosen.
- LCURVE = 'L-curve'#
- GCV = 'GCV'#
- FIXED = 'Fixed'#
- class pyrate_ta.settings.ModelType(*values)[source]#
Bases:
StrEnumKinetic 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:
objectAnalysis-only settings. Presentation lives in
pymorgan.Settings.- Parameters:
n_components (int)
model_type (ModelType)
ftol (float)
xtol (float)
max_iterations (int)
variable_projection (bool)
irf_mode (IRFMode)
irf_fwhm (float | None)
t_min (float | None)
use_noise_weights (bool)
noise_floor_fraction (float)
degeneracy_warn_ratio (float)
lda_n_lifetimes (int)
lda_tau_min (float | None)
lda_tau_max (float | None)
lda_regularisation (Regularisation)
lda_alpha (float)
lda_non_negative (bool)
data_marker (str)
data_alpha (float)
data_markersize (float)
fit_linestyle (str)
fit_linewidth (float)
fit_alpha (float)
residuals_height_ratio (float)
residuals_hspace (float)
panel_left (float)
panel_right (float)
panel_top (float)
panel_bottom (float)
panel_hspace (float)
panel_wspace (float)
fit_monitor_every (int)
fit_monitor_scale (str)
window_width (int)
window_height (int)
restore_window_size (bool)
table_default_lb (float)
table_default_ub (float)
table_decimals (int)
new_rows_fixed (bool)
plot_species_after_fit (bool)
plot_profiles_after_fit (bool)
plot_trio_after_fit (bool)
open_scheme_after_fit (bool)
autosave_session (bool)
default_datadir (Path | None)
schemes_dir (Path | None)
- lda_regularisation: Regularisation = 'L-curve'#
- static field_sections()[source]#
Which
settings.tomlsection 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.
- 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 fromfield_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_OVERRIDESrefines 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.
- pyrate_ta.settings.update_settings(**kwargs)[source]#
Update named fields on the active settings, rejecting unknown names.
- pyrate_ta.settings.get_default_settings_text()[source]#
Return the raw text of the canonical default settings template.
- Return type:
- 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.tomlis 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.
- pyrate_ta.settings.ensure_settings_file(path=None)[source]#
Ensure that
path(defaulting tosettings_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.
- 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.
- pyrate_ta.settings.save_settings(path, settings=None)[source]#
Write the settings to
pathas TOML, preserving comments.
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:
objectOne literature reference.
- Variables:
- Parameters:
- pyrate_ta.cite.get_reference(key)[source]#
Look up one reference, listing the alternatives on failure.
- 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.
keysdefaults to every reference: the software paper, then the paper describing the framework, then the two method references.