1D Pipeline API (pymorgan.oneD)#

Dataset1D (pymorgan.oneD.dataset)#

The Dataset1D pipeline object.

Dataset1D ties the 1-D pipeline together: load (load), process (process), plot (plot) and analyse (analyse). It holds the raw arrays plus provenance and resolves presentation defaults from the active pymorgan.settings.Settings. The stage modules contain the actual logic; the methods here are thin, well-typed entry points that pass self (and the resolved settings) through. Heavy imports (matplotlib, scipy) stay inside the methods.

class pymorgan.oneD.dataset.Dataset1D(Zavg_R, delays, probe, units, nscans=nan, Zss_R=None, Zstdv=None, *, source=None, data_type=None, scan_ids=None, counts=None)[source]#

Bases: object

A one-dimensional time-resolved dataset and its processing pipeline.

Variables:
  • Zavg_R – Averaged signal, [Ndelays x Npixels x Ndetectors].

  • probe (delays,) – Delay and probe (spectral) axes.

  • units – Unit dictionary (see helpers.units2dic).

  • Zstdv (nscans, Zss_R,) – Scan count, single-scan signal and standard deviation.

  • Zavg_C – Background-corrected signal (None until background_correct()).

Parameters:
  • units (dict)

  • source (str | None)

  • data_type (str | None)

property Units: dict#

Alias for units for backward compatibility with legacy specs.

classmethod from_file(path, data_type=None, **loader_kwargs)[source]#

Load a dataset from path using data_type (auto-detected when omitted).

Extra keyword arguments are forwarded to the loader (e.g. spectrum, slowmod and anisotropy for the MESS_TRIR reader). Loaders that take no options simply receive none.

Parameters:
Return type:

Dataset1D

property Z#

corrected if available, else raw.

Type:

Most-processed signal

property n_detectors: int#

Number of detector channels in the signal.

property is_corrected: bool#

Whether a background correction has been applied.

property has_single_scans: bool#

Whether real per-scan arrays are available in Zss_R.

True when Zss_R is a 4-D [Ndelays x Npixels x Ndet x Nscans] array carrying finite data (e.g. a MESS dataset loaded with Settings.load_single_scans); False for a NaN placeholder.

property history: list[ProcessingStep]#

Ordered list of recorded processing steps applied to this dataset.

property can_undo: bool#

Whether an undo snapshot is available.

property can_redo: bool#

Whether a redo snapshot is available.

undo()[source]#

Undo the most recent processing step (or coalesced tweak).

Return type:

bool

redo()[source]#

Redo the most recently undone processing step.

Return type:

bool

reset_to_raw()[source]#

Restore the raw initial dataset state and clear processing history.

Return type:

bool

revert_to_step(step_index)[source]#

Revert the dataset to the state immediately after step_index (-1 = raw).

Parameters:

step_index (int)

Return type:

bool

history_to_dicts()[source]#

Serialize processing history to JSON/TOML-friendly dictionaries.

Return type:

list[dict[str, Any]]

load_history_from_dicts(items)[source]#

Restore processing history metadata from serialized dictionaries.

Parameters:

items (Sequence[dict[str, Any]])

Return type:

None

to_python_script(*, include_plot=True, include_settings=True, plot_kwargs=None)[source]#

Generate a standalone Python script reproducing this dataset’s pipeline.

Parameters:
  • include_plot (bool)

  • include_settings (bool)

  • plot_kwargs (dict | None)

Return type:

str

scan_signal(detector=0)[source]#

Return the single-scan signal [Ndelays x Npixels x Nscans].

Uses the background-corrected single scans (Zss_C) when available, otherwise the raw single scans (Zss_R). Raises if no per-scan data is present (see has_single_scans).

Parameters:

detector (int)

Return type:

ndarray

copy(deep=True)[source]#

Return a copy of the dataset.

When deep=True (default), all internal arrays are cloned independently.

Parameters:

deep (bool)

Return type:

Dataset1D

crop(tmin=None, tmax=None, probe_min=None, probe_max=None)[source]#

Crop the dataset along the delay and/or probe axes.

Mutates the dataset in-place and returns self for chaining. To keep the original dataset intact, call dataset.copy().crop(...).

Parameters:
Return type:

Dataset1D

to_pdat(path, *, detector=None, use_corrected=True, write_noise=True)[source]#

Export dataset to .pdat (and optional .pdatn) file(s).

Parameters:
  • path (str or Path) – Output file path.

  • detector (int, optional) – Specific detector to export. If None and dataset has multiple detectors, writes separate _DET1.pdat, _DET2.pdat, etc.

  • use_corrected (bool, default True) – Whether to write background-corrected data.

  • write_noise (bool, default True) – Whether to also write sibling .pdatn noise files.

Returns:

Paths of written .pdat files.

Return type:

list[Path]

to_dataframe(format='tidy', detector=0, use_corrected=True)[source]#

Export dataset as a pandas DataFrame.

Parameters:
  • format ({"tidy", "wide"}, default "tidy") – If “tidy”, returns columns ['delay', 'probe', 'signal'] (and 'noise' if present). If “wide”, returns a DataFrame with index=delays and columns=probe.

  • detector (int, default 0) – Detector index to export.

  • use_corrected (bool, default True) – Whether to export the background-corrected signal (falls back to raw if uncorrected).

to_hdf5(path)[source]#

Save dataset to a self-contained HDF5 file.

Parameters:

path (str | PathLike)

Return type:

Path

save_hdf5(path)[source]#

Alias of to_hdf5().

Parameters:

path (str | PathLike)

Return type:

Path

to_glotaran_ascii(path, *, orientation='time', signal_unit='mOD', use_corrected=True, detector=0)[source]#

Export dataset to Glotaran / TIMP .ascii format.

Parameters:
Return type:

Path

to_glotaran_nc(path, *, signal_unit='mOD', use_corrected=True, detector=0, write_noise=True)[source]#

Export dataset to a Glotaran / pyglotaran CF-1.8 NetCDF4 .nc file.

Parameters:
Return type:

Path

property rms: ndarray | None#

Return the raw single-shot RMS noise matrix if present in units.

noise_array()[source]#

Per-point noise (standard deviation) of the signal, or None.

Noise is taken from Zstdv when it carries non-trivial values (e.g. loaded from a sibling .pdatn file), otherwise computed as the standard deviation across the scan axis of Zss_R when single-scan data is present. Returns None when neither is available.

Returns:

Same shape as Z ([Ndelays x Npixels x Ndetectors]), in the same unit as the signal (mOD), or None when the dataset carries no noise information.

Return type:

numpy.ndarray or None

Notes

Public because it is the input to weighted fitting: PyRATE-TA reads it to build the 1/sigma weights that turn a fit statistic into a true reduced chi-squared. A dataset without a .pdatn sibling and without single scans returns None, and a weighted fit of it is refused rather than silently falling back to an unweighted one.

property has_noise: bool#

True if non-trivial noise or single-scan standard deviation is available.

axis_units(display=False, settings=None)[source]#

Units of the dataset axes: X (probe), Y (delay) and Z (signal).

Returns a DatasetUnits whose entries carry the quantity, the unit token, the mathtext used on plots and the display scaling factor:

>>> data.axis_units().x.unit
'cm-1'
>>> print(data.axis_units())
Axis units
  x: Wavenumber in cm-1
  y: Delay in ps
  z: $\Delta$A in x1E3

With display=True the spectral axis is reported as it would be plotted, i.e. converted to Settings.x_axis_unit and carrying the 10^3 factor when the plot applies one; otherwise the dataset’s own (stored) units are reported.

Parameters:

display (bool)

property has_extended_sample_info: bool#

Whether extended (‘all available’) sample metadata is available.

sample_info(show_all=False)[source]#

Return an HTML dataset summary shown in the GUI info box.

Parameters:

show_all (bool)

Return type:

str

sample_info_console(show_all=False)[source]#

Return a plain text, console-friendly summary of the 1-D dataset.

Parameters:

show_all (bool)

Return type:

str

calibration_status()[source]#

Return a clean, human-readable probe calibration source description.

Return type:

str

print_sample_info(show_all=False)[source]#

Print the console-friendly summary of the 1-D dataset.

Parameters:

show_all (bool)

Return type:

None

background_correct(tmin, tmax, do_correct=True)[source]#

Subtract the pre-zero background averaged over [tmin, tmax].

Returns self so calls can be chained.

Parameters:

do_correct (bool)

Return type:

Dataset1D

detect_scatter_bands(*, detector=0, tmin=None, tmax=None, allow_positive=False)[source]#

Auto-detect localised scatter bands from the pre-zero spectrum.

Parameters:
  • detector (int, default 0) – 0-based detector channel index to inspect.

  • tmin (float, optional) – Pre-zero delay window bounds. Defaults to delays <= -1.0 (or earliest negative delays).

  • tmax (float, optional) – Pre-zero delay window bounds. Defaults to delays <= -1.0 (or earliest negative delays).

  • allow_positive (bool, default False) – Whether to detect positive sharp pre-zero artefacts alongside negative scatter dips.

Returns:

Auto-detected primary and optional coupled 2nd-order harmonic bands.

Return type:

list of ScatterBand

apply_scatter_removal(result)[source]#

Apply a computed ScatterRemovalResult in-place.

Copies the cleaned averaged and single-scan arrays, stores the removal metadata, and backs up Zstdv prior to updating it when result.Zstdv is provided.

Parameters:

result (ScatterRemovalResult) – Output produced by pymorgan.oneD.scatter.compute_scatter_removal().

Returns:

Returns self so calls can be chained.

Return type:

Dataset1D

remove_scatter(bands=None, **kwargs)[source]#

Run multi-band scatter and dynamic background removal in-place.

Delegates to pymorgan.oneD.scatter.compute_scatter_removal() and applies the cleaned arrays (and optional updated Zstdv) to this dataset. Run prior to chirp correction so unchirped scatter tied to the delay stage is isolated cleanly.

Parameters:
  • bands (list of ScatterBand, optional) – Explicit scatter bands in native probe units. When None, bands are automatically detected from the pre-zero spectrum.

  • **kwargs – Additional keyword arguments forwarded to pymorgan.oneD.scatter.compute_scatter_removal() (such as method, rank, poly_deg, t0_exclude, scale_broadband, per_scan, update_noise, and transmittance_space).

Returns:

Returns self so calls can be chained.

Return type:

Dataset1D

clear_scatter_removal()[source]#

Clear applied advanced scatter removal state and restore original Zstdv.

Returns:

Returns self so calls can be chained.

Return type:

Dataset1D

recalc_average(scan_indices, *, spectrum=0, slowmod=0, noise_weighted=True)[source]#

Recompute the averaged signal and standard deviation over selected scans.

Parameters:
  • scan_indices (sequence of int) – 0-based scan indices to combine.

  • spectrum (int, default 0) – Spectrum index (for MESS datasets).

  • slowmod (int, default 0) – Slow-modulation index (for MESS datasets).

  • noise_weighted (bool, default True) – Whether to combine scans using inverse-variance noise weighting (default) or direct arithmetic averaging.

Returns:

Returns self for chaining.

Return type:

Dataset1D

mask_probe_regions(ranges, detector=None)[source]#

Remove or mask data in the specified probe ranges (in native units).

For single-detector datasets (or when n_detectors <= 1), specified probe ranges are removed from the probe and data arrays.

For multi-detector datasets, the masking is applied to the specified detector channel only, setting data in the masked range to NaN so each detector retains its independent probe axis and grid dimensions.

Returns self so calls can be chained.

Parameters:
Return type:

Dataset1D

shift_t0(t0_shift)[source]#

Shift the delay time axis by subtracting t0_shift.

Updates self.delays = self.delays - t0_shift. Since single-scan data (Zss_R) and accumulation counts (counts) are aligned with self.delays, they are automatically shifted. Resetting self.Zavg_C forces background correction to re-evaluate pre-zero delay indices with the updated time axis.

Parameters:

t0_shift (float)

Return type:

Dataset1D

subtract_solvent(solvent, dt=0.0, scale=1.0)[source]#

Subtract a scaled, time-shifted solvent background from this dataset.

The solvent signal is interpolated onto this dataset’s delay grid after applying a timing offset dt. The corrected signal replaces (or initialises) Zavg_C, so it composes naturally with a prior background_correct() call: the solvent is subtracted from whichever signal is currently returned by Z.

Parameters:
  • solvent (Dataset1D) – The solvent (reference) dataset. If it has been background- corrected (solvent.Zavg_C is not None) its corrected signal is used; otherwise the raw signal (solvent.Zavg_R) is used.

  • dt (float or array-like) – Timing offset in ps (scalar or per-pixel array of length Npixels). A positive dt shifts the solvent signal towards earlier times on the sample delay grid.

  • scale (float or array-like) – Amplitude scaling factor (scalar or per-pixel array of length Npixels).

Returns:

self — so calls can be chained.

Return type:

Dataset1D

subtract_shockwave(pixels=None, probe_range=None, probe_values=None, one_based=True)[source]#

Subtract an average kinetic trace calculated over selected pixels or probe region.

Calculates an average kinetic trace over the specified pixel(s) or probe region and subtracts it from all pixels in the dataset. Updates Zavg_C (and Zss_C if single-scan data is present).

Parameters:
  • pixels (int, sequence of int, slice, or None) – Pixel index or indices to average over (1-based by default when one_based=True).

  • probe_range (tuple (min_probe, max_probe) or None) – Probe axis range (in native units) over which to select pixels.

  • probe_values (float or sequence of float or None) – Probe value(s) in native units for which to find the nearest pixel(s).

  • one_based (bool, default True) – Whether integer pixels are 1-based pixel numbers (1..Npixels).

Returns:

self — so calls can be chained.

Return type:

Dataset1D

fit_solvent_auto(solvent, det_idx=0, per_pixel_dt=None, per_pixel_scale=None)[source]#

Automatically find optimal timing offset and scaling for solvent subtraction.

Fits a global (or per-pixel) timing offset dt and a global (or per-pixel) amplitude scaling factors scale to match an erf-broadened step-like rise.

Parameters:
  • solvent (Dataset1D) – The solvent dataset.

  • det_idx (int, default 0) – The detector channel index to optimise for.

  • per_pixel_dt (bool or None) – Whether to optimise a separate timing offset for each pixel. If None, reads the default from active settings (solvent_per_pixel_dt).

  • per_pixel_scale (bool or None) – Whether to optimise a separate amplitude scaling factor for each pixel. If None, reads the default from active settings (solvent_per_pixel_scale).

Returns:

  • scale (float or ndarray) – Optimal global scaling factor (float) or per-pixel scaling factors (ndarray).

  • dt (float or ndarray) – Optimal global timing offset (float) or per-pixel timing offsets (ndarray).

Return type:

tuple[float | ndarray, float | ndarray]

time_derivative(*, t_min=None, interpolate=False, n_interp=None, interp_kind='cubic', smooth=False, smooth_method='savgol', smooth_window=7, smooth_poly=2)[source]#

Calculate the time derivative d(Delta A)/dt along the delay axis.

Returns a new Dataset1D holding the differentiated signals with updated units metadata (e.g. d(Delta A)/dt).

Parameters:
  • t_min (float | None)

  • interpolate (bool)

  • n_interp (int | None)

  • interp_kind (str)

  • smooth (bool)

  • smooth_method (str)

  • smooth_window (int)

  • smooth_poly (int)

Return type:

Dataset1D

calculate_anisotropy(perpendicular=None, *, g_factor=1.0, threshold=None, return_components=False, detector_par=0, detector_perp=1, use_corrected=True)[source]#

Calculate time-resolved polarization anisotropy from parallel and perpendicular signals.

Parameters:
  • perpendicular (Dataset1D, optional) – Perpendicular polarization dataset. If omitted, self must have at least 2 detectors.

  • g_factor (float or ndarray, default 1.0) – Sensitivity correction factor G.

  • threshold (float, optional) – Minimum value of isotropic signal below which anisotropy is set to NaN.

  • return_components (bool, default False) – If True, returns a dict with keys 'anisotropy', 'magic_angle', 'difference', 'parallel', and 'perpendicular'.

  • detector_par (int, default 0) – Channel index for parallel polarization when unpacking a single multi-detector dataset.

  • detector_perp (int, default 1) – Channel index for perpendicular polarization when unpacking a single multi-detector dataset.

  • use_corrected (bool, default True) – Whether to use background-corrected signal (Dataset1D.Z) or raw (Dataset1D.Zavg_R).

Returns:

Anisotropy dataset or dictionary of component datasets.

Return type:

Dataset1D or dict[str, Dataset1D]

anisotropy(perpendicular=None, *, g_factor=1.0, threshold=None, return_components=False, detector_par=0, detector_perp=1, use_corrected=True)#

Calculate time-resolved polarization anisotropy from parallel and perpendicular signals.

Parameters:
  • perpendicular (Dataset1D, optional) – Perpendicular polarization dataset. If omitted, self must have at least 2 detectors.

  • g_factor (float or ndarray, default 1.0) – Sensitivity correction factor G.

  • threshold (float, optional) – Minimum value of isotropic signal below which anisotropy is set to NaN.

  • return_components (bool, default False) – If True, returns a dict with keys 'anisotropy', 'magic_angle', 'difference', 'parallel', and 'perpendicular'.

  • detector_par (int, default 0) – Channel index for parallel polarization when unpacking a single multi-detector dataset.

  • detector_perp (int, default 1) – Channel index for perpendicular polarization when unpacking a single multi-detector dataset.

  • use_corrected (bool, default True) – Whether to use background-corrected signal (Dataset1D.Z) or raw (Dataset1D.Zavg_R).

Returns:

Anisotropy dataset or dictionary of component datasets.

Return type:

Dataset1D or dict[str, Dataset1D]

svd(k=2, detector=0, array='auto', tmin=None, tmax=None, probe_min=None, probe_max=None, centering='none', handle_nan='interpolate')[source]#

Singular Value Decomposition (SVD) of the 1D dataset.

Parameters:
  • k (int, default 2) – Number of components to use for recomposition.

  • detector (int, default 0) – Detector channel index if multi-detector dataset.

  • array ({'auto', 'corrected', 'raw'}, default 'auto') – Which data array to decompose (‘auto’ uses Zavg_C if available, else Zavg_R).

  • tmin (float, optional) – Delay range limits for cropping prior to SVD.

  • tmax (float, optional) – Delay range limits for cropping prior to SVD.

  • probe_min (float, optional) – Probe range limits for cropping prior to SVD.

  • probe_max (float, optional) – Probe range limits for cropping prior to SVD.

  • centering ({'none', 'spectrum', 'probe', 'kinetic', 'time', 'both'}, default 'none') – Centering method applied before factorization.

  • handle_nan ({'interpolate', 'drop', 'raise'}, default 'interpolate') – Strategy for handling NaN values in the selected region.

Returns:

Result container with components, scree analysis, and recomposition tools.

Return type:

SVDResult

stitch_wavelength(other, stitch_region=None, mode='blend', blend_window=None, cutover_wl=None, time_threshold=-0.1, scale_override=None, target_delays='ds2', detector1=0, detector2=0)[source]#

Stitch this dataset with another spectral window (e.g. UV/Vis + NIR).

See pymorgan.oneD.stitch.stitch_wavelength() for parameter details.

Parameters:
stitch_time(other_ns, time_overlap=(0.5, 2.0), blend_window=(1.0, 1.7), scale_model='quadratic', scale_override=None, align_wl=True, cut_scatter=False, scatter_region=(500.0, 550.0), detector_fs=0, detector_ns=0)[source]#

Stitch this ultrafast (fs) dataset with a long-delay (ns) dataset.

See pymorgan.oneD.stitch.stitch_time() for parameter details.

Parameters:
plot_contour(ax=None, **kwargs)[source]#

Delay-vs-probe contour map.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a new figure. When an axis is given the figure layout is left to the caller, so the panel can be placed in a GridSpec composite.

  • **kwargs – Passed to pymorgan.oneD.plot.plot_contour(), which documents them all. The ones reached for most often are Zscale (colour limit as a percentage of the peak), Zmin/Zmax (explicit limits, for putting panels on a common scale), Yscale ("symlog"/"log"/"lin" delay axis), ShowLines, Nlevels/Nskip, cmap_ID, x_axis_unit, show_colorbar and show_xlabel/show_ylabel. Anything not given follows the active Settings.

Return type:

matplotlib.axes.Axes

Examples

>>> ax = data.plot_contour(ShowLines=True, Zscale=30, Yscale="symlog")
plot_noise_3d(ax=None, **kwargs)[source]#

Plot the noise array as a rotatable 3D surface.

Parameters:
Return type:

mpl_toolkits.mplot3d.axes3d.Axes3D

Raises:

ValueError – If the dataset carries neither a noise array nor single-scan data.

plot_noise_spectrum(ax=None, **kwargs)[source]#

Plot the delay-averaged noise spectrum against the probe axis.

plot_counts(ax=None, **kwargs)[source]#

Plot accumulation counts as a function of probe delay.

Parameters:
Return type:

matplotlib.axes.Axes

plot_surface(ax=None, **kwargs)[source]#

Delay-vs-probe 3D surface with colourmap shading.

Parameters:
Return type:

mpl_toolkits.mplot3d.axes3d.Axes3D

plot_spectra(plot_delays, ax=None, fig=None, **kwargs)[source]#

Transient spectra at the requested delays.

Parameters:
  • plot_delays (sequence of float) – Delays to cut at, in this dataset’s time unit. Each is snapped to the nearest measured delay, so approximate values are fine.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a new figure.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • **kwargs – Passed to pymorgan.oneD.plot.plot_spectra(), which documents them all. Commonly used: doSmooth (box-filter width; negative also draws the raw trace), normY, roundT, x_axis_unit, secondary_axis, Abs/Em (steady-state overlays) and show_xlabel/show_ylabel.

Return type:

matplotlib.axes.Axes

Examples

>>> data.plot_spectra([0.5, 1, 5, 50, 500], doSmooth=3, roundT=True)
plot_background(ax=None, fig=None, **kwargs)[source]#

Pre-zero background spectrum, drawn with the transient-spectra rules.

Parameters:
Return type:

matplotlib.axes.Axes

Raises:

ValueError – If no background has been computed; run background_correct() first (do_correct=False stores it without subtracting).

plot_kinetics(plot_wavelengths, ax=None, fig=None, **kwargs)[source]#

Kinetic traces at the requested probe positions.

Parameters:
  • plot_wavelengths (sequence of float) – Probe positions to cut at, in this dataset’s native probe unit (nm, cm-1, …). Each is snapped to the nearest pixel.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a new figure.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • **kwargs – Passed to pymorgan.oneD.plot.plot_kinetics(). Commonly used: plotStyle (format string, e.g. "-"), Xscale, normY, lw/ms and show_xlabel/show_ylabel.

Returns:

  • ax (matplotlib.axes.Axes)

  • t (numpy.ndarray) – Delay axis, shape [Ndelays].

  • Y (numpy.ndarray) – Extracted traces, shape [Ndelays x Ncuts] — the same data that was plotted, ready to export or fit.

Examples

>>> ax, t, Y = data.plot_kinetics([2132, 2218], plotStyle="-", lw=1.5)
plot_scan_kinetics(plot_wavelengths, ax=None, fig=None, **kwargs)[source]#

Per-scan kinetic traces at the requested probe positions.

Diagnostic for scan-to-scan reproducibility; requires single-scan data (see has_single_scans).

Parameters:
Returns:

  • ax (matplotlib.axes.Axes)

  • t (numpy.ndarray) – Delay axis, shape [Ndelays].

  • Y (numpy.ndarray) – Binned traces, shape [Ndelays x Npixels x Nbins].

plot_scan_spectra(plot_delays, ax=None, fig=None, **kwargs)[source]#

Per-scan transient spectra at the requested delays.

Spectral counterpart of plot_scan_kinetics(); requires single-scan data (see has_single_scans).

Parameters:
Return type:

matplotlib.axes.Axes

plot_species_spectra(Sfit, Taus, TauErr, isFixTau, modelType, ax=None, fig=None, **kwargs)[source]#

EAS/SAS from a global-analysis fit.

Parameters:
  • Sfit (numpy.ndarray) – Component amplitude spectra, shape [Npixels x Ncomponents].

  • Taus (sequence of float) – Fitted lifetime of each component.

  • TauErr (sequence of float) – Uncertainty on each lifetime.

  • isFixTau (sequence of bool) – Per-component flag marking lifetimes held fixed in the fit.

  • modelType (str) – Kinetic model used, which decides the EAS / SAS wording.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a new figure.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • **kwargs – Passed to pymorgan.oneD.plot.plot_species_spectra() (printErrors, normY, doSmooth, Abs/Em, …).

Return type:

matplotlib.axes.Axes

Notes

The Sfit / Taus / TauErr inputs come from a global-analysis fit, which PyMORGAN does not perform — see the companion project PyRATE-TA. This method is the rendering half of that seam and takes plain arrays, so it is independent of how the fit was obtained.

fit_chirp_automatic(**kwargs)[source]#

VARPRO coherent-artefact + Cauchy dispersion fit.

See pymorgan.oneD.chirp.fit_chirp_automatic().

fit_chirp_step(**kwargs)[source]#

Gaussian(+derivatives)+erf-step fit, restricted to an early-time window.

See pymorgan.oneD.chirp.fit_chirp_step().

fit_chirp_wavelet(**kwargs)[source]#

Wavelet-based edge-detection fit at every probe pixel + Cauchy dispersion fit.

See pymorgan.oneD.chirp.fit_chirp_wavelet().

fit_chirp_manual(points, **kwargs)[source]#

Cauchy dispersion fit to manually-picked (wavelength, delay) points.

See pymorgan.oneD.chirp.fit_chirp_manual().

plot_chirp_diagnostics(fit, **kwargs)[source]#

Review figures for a chirp fit. See pymorgan.oneD.chirp.plot_chirp_diagnostics().

apply_chirp_correction(fit, detector=None, boundary_handling=None)[source]#

Apply a loaded ChirpFit to correct the dispersion in this dataset.

Interpolates all active signals (raw, corrected, stdv, and single scans) for the given detector onto the same time-delay grid.

Boundary handling options are: - “crop” -> Option 2: Slices/crops the delays axis to keep only fully finite regions where all pixels are defined. - “extrapolate” -> Option 1: Fills out-of-bound values with the nearest valid boundary endpoint value (no NaNs).

Parameters:
  • detector (int | None)

  • boundary_handling (str | None)

Return type:

None

embed_calibrated_probe(csv_path=None, *, backup_original=True)[source]#

Embed a CalibratedProbe.csv probe axis directly inside the source .h5 file.

Parameters:
Return type:

dict[str, Any]

pymorgan.oneD.dataset.load_1D(path, data_type=None, **loader_kwargs)[source]#

Convenience wrapper for Dataset1D.from_file().

When data_type is None (default) or "auto", pymorgan.detect_format() infers the format automatically (falling back to "PDAT"). Extra keyword arguments are forwarded to the selected loader.

Parameters:
Return type:

Dataset1D

Loaders & Registry (pymorgan.oneD.load, pymorgan.oneD.registry)#

Backwards-compatible shim.

The loader registry now lives in pymorgan.oneD.load. This module re-exports its public names so that from pymorgan.oneD.registry import ... keeps working.

pymorgan.oneD.registry.register_loader(*names)[source]#

Register fn under one or more data-type names.

Parameters:

names (str)

Return type:

Callable[[Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]], Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]]

pymorgan.oneD.registry.get_loader(name)[source]#

Return the loader registered for name or raise KeyError.

Parameters:

name (str)

Return type:

Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]

pymorgan.oneD.registry.available_loaders()[source]#

Return the sorted list of registered data-type names.

Return type:

list[str]

Loading stage of the 1-D pipeline: readers and their registry.

A loader maps a file path to the seven fields consumed by pymorgan.oneD.Dataset1D:

Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv

Field

Meaning / shape

Zavg_R

Averaged signal, [Ndelays x Npixels x Ndetectors]

delays

Delay axis, [Ndelays]

probe

Spectral (probe) axis, [Npixels]

Units

Unit dictionary (see helpers.units2dic)

Nscans

Number of scans, or numpy.nan if unavailable

Zss_R

Single-scan signal, [Ndelays x Npixels x Ndetectors x Nscans]

Zstdv

Standard deviation of the signal, [Ndelays x Npixels]

New instrument formats are added by decorating a reader with register_loader().

pymorgan.oneD.load.register_loader(*names)[source]#

Register fn under one or more data-type names.

Parameters:

names (str)

Return type:

Callable[[Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]], Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]]

pymorgan.oneD.load.get_loader(name)[source]#

Return the loader registered for name or raise KeyError.

Parameters:

name (str)

Return type:

Callable[[str], tuple[Any, Any, Any, dict, Any, Any, Any]]

pymorgan.oneD.load.available_loaders()[source]#

Return the sorted list of registered data-type names.

Return type:

list[str]

pymorgan.oneD.load.register_dataset_glob(name, pattern)[source]#

Declare name as a file-based format whose datasets match pattern.

Parameters:
Return type:

None

pymorgan.oneD.load.register_dataset_detector(*names)[source]#

Register a folder -> bool predicate marking a directory-based dataset.

Parameters:

names (str)

Return type:

Callable[[Callable[[Path], bool]], Callable[[Path], bool]]

pymorgan.oneD.load.register_dataset_describer(*names)[source]#

Register a folder -> dict describing per-dataset selection options.

The dict is advisory metadata the GUI uses to configure selectors (e.g. {"n_spectra": int, "n_slowmod": int}). Returns None when no describer is registered for the data type.

Parameters:

names (str)

Return type:

Callable[[Callable[[Path], dict]], Callable[[Path], dict]]

pymorgan.oneD.load.register_dataset_file_filter(*names)[source]#

Register a file_path -> bool predicate filtering dataset browser files.

Parameters:

names (str)

Return type:

Callable[[Callable[[Path], bool]], Callable[[Path], bool]]

pymorgan.oneD.load.is_dataset_file_status(name, file_path)[source]#

Whether file_path is a candidate/valid dataset file for type name.

Returns (is_candidate, is_valid).

Parameters:
Return type:

tuple[bool, bool]

pymorgan.oneD.load.is_dataset_file(name, file_path)[source]#

Whether file_path is an averaged dataset file for type name.

Parameters:
Return type:

bool

pymorgan.oneD.load.dataset_glob(name)[source]#

Return the file glob for a file-based format, or None.

Parameters:

name (str)

Return type:

str | None

pymorgan.oneD.load.is_directory_format(name)[source]#

Whether name stores each dataset as a directory (has a detector).

Parameters:

name (str)

Return type:

bool

pymorgan.oneD.load.is_dataset_dir_status(name, folder)[source]#

Whether folder is a candidate/valid dataset of type name.

Returns (is_candidate, is_valid).

Parameters:
Return type:

tuple[bool, bool]

pymorgan.oneD.load.is_dataset_dir(name, folder)[source]#

Whether folder is a loadable dataset of type name.

Parameters:
Return type:

bool

pymorgan.oneD.load.describe_dataset(name, folder)[source]#

Return per-dataset selection metadata, or None if unavailable.

Parameters:
Return type:

dict | None

pymorgan.oneD.load.read_PDAT(datafilename)[source]#

Read a PyMORGAN .pdat file (averaged data already in mOD).

The first line holds the time and probe units separated by *; the first data row is the probe axis (leading 0), and every later row is a delay followed by the signal at each probe coordinate.

Parameters:

datafilename (str)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.write_pdat(path, delays, probe, z_data, *, time_unit='ps', probe_unit='cm^{-1}', noise=None)[source]#

Write a 1-D transient absorption slice to a PyMORGAN .pdat (and optional .pdatn) file.

Parameters:
  • path (str or Path) – Target file path (.pdat extension added if omitted).

  • delays (ndarray, shape [Ndelays]) – Delay axis values.

  • probe (ndarray, shape [Npixels]) – Probe spectral axis values.

  • z_data (ndarray, shape [Ndelays x Npixels]) – Signal data matrix.

  • time_unit (str, default "ps") – Delay timescale unit string (e.g. “ps”, “ns”, “fs”).

  • probe_unit (str, default "cm^{-1}") – Probe spectral unit string (e.g. “cm^{-1}”, “nm”, “eV”).

  • noise (ndarray, optional) – Standard deviation / noise matrix [Ndelays x Npixels]. If supplied, writes a sibling .pdatn file.

Returns:

The written .pdat file path.

Return type:

Path

pymorgan.oneD.load.export_pdat(dataset, path, *, detector=None, use_corrected=True, write_noise=True)[source]#

Export a pymorgan.oneD.Dataset1D to .pdat (and optional .pdatn) files.

If the dataset has multiple detectors and detector is None, exports one .pdat per detector with a _DET{i} filename suffix.

Returns the list of exported Paths.

Parameters:
Return type:

list[Path]

pymorgan.oneD.load.save_1D_hdf5(dataset, path)[source]#

Save a pymorgan.oneD.Dataset1D instance to a FAIR/NeXus HDF5 archive.

Parameters:

path (str | PathLike)

Return type:

Path

pymorgan.oneD.load.read_1D_hdf5(path)[source]#

Read a Dataset1D from an HDF5 file written by save_1D_hdf5.

Parameters:

path (str | PathLike)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.load_1D_hdf5(path)[source]#

Load an HDF5 archive into a fully restored pymorgan.oneD.Dataset1D.

Parameters:

path (str | PathLike)

pymorgan.oneD.load.read_UniGE_nsTA(datafilename)[source]#

Read a UniGE nanosecond Transient Absorption (.dat) file.

Header lines start with ‘%’ and contain metadata. Data rows contain: - Column 0: delay value (seconds, converted to ns) - Column 1: pixel index (0 to Npixels-1) - Column 2: TA signal - Column 3: rms - Column 4: error (noise) - Column 5: n samples / accumulation counts

Return type:

Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv, scan_ids, counts

Parameters:

datafilename (str)

pymorgan.oneD.load.read_UniGE_fsTA(datafilename)[source]#

Read a UniGE step-scan femtosecond Transient Absorption (.dat) file.

Header lines start with ‘%’ and contain dataset metadata. Data rows contain: - Column 0: delay value (seconds, converted to ps) - Column 1: accumulation count - Columns 2..N: alternating Signal (uOD) and Error (uOD) pairs for each pixel

Return type:

Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv, scan_ids

Parameters:

datafilename (str)

pymorgan.oneD.load.read_UoS_IRpp(path, *, load_single_scans=None)[source]#

Read a University of Sheffield TRIR dataset folder or file (.2D / .DT).

Parameters:
  • path (str)

  • load_single_scans (bool | None)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.read_RAL_IRpp(path, *, load_single_scans=None)[source]#

Read a Rutherford Appleton Laboratory (CLF Ultra / LIFEtime) IRpp dataset.

Supports dual-detector arrays (2 detectors of 128 pixels each, 256 pixels total) and single-cycle scans (Run * Cycle*.csv). Delays are extracted from column headers and sorted into ascending order.

Parameters:
Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.mess_calibration_status(folder)[source]#

One-line probe-calibration status for the status bar after a MESS load.

Return type:

str

pymorgan.oneD.load.parse_mess_sample_info(path)[source]#

Parse a MESS sample_info.txt file into a clean summary string.

Only non-empty key-value entries and comments are included.

Parameters:

path (Path | str)

Return type:

str

pymorgan.oneD.load.read_MESS_TRIR(path, *, spectrum=0, slowmod=0, anisotropy='NONE', load_single_scans=None)[source]#

Read a MESS transient-IR dataset folder (probe axis in cm^-1).

Parameters:
  • path (str)

  • spectrum (int)

  • slowmod (int)

  • anisotropy (str)

  • load_single_scans (bool | None)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.read_MESS_TRUVIS(path, *, spectrum=0, slowmod=0, anisotropy='NONE', load_single_scans=None)[source]#

Read a MESS transient-UV/Vis (TA) dataset folder (probe axis in nm).

Parameters:
  • path (str)

  • spectrum (int)

  • slowmod (int)

  • anisotropy (str)

  • load_single_scans (bool | None)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.classify_pymess_h5(filepath)[source]#

Classify a PyMESS .h5 file into one of: - ‘pump_probe’: Standard 1D Pump-Probe (delay stage scan) - ‘shaper_t2_scan’: 1D Pump-Probe recorded in the 2D tab via 1-pulse shaper delay scan - ‘2d_time_domain’: True 2D Time-Domain spectrum (2-pulse shaper t1 scan) - ‘2d_freq_domain’: True 2D Frequency-Domain spectrum (shaper frequency scan) - ‘other’: Calibration, magic angle, find_t0, aborted empty file, or non-PyMESS HDF5

Parameters:

filepath (str | Path)

Return type:

str

pymorgan.oneD.load.find_pymess_calibrated_probe_csv(path, n_pix)[source]#

Locate a matching CalibratedProbe.csv for a PyMESS dataset file or folder.

Returns (probe_array, csv_path, location_label, cal_level) in priority order (data folder -> calib -> Cal+Chirp -> root folder -> parent calib -> parent Cal+Chirp), or None if no matching file exists.

Parameters:
Return type:

tuple[ndarray, Path, str, str] | None

pymorgan.oneD.load.embed_calibrated_probe_h5(h5_path, csv_path=None, *, backup_original=True)[source]#

Permanently embed a CalibratedProbe.csv probe axis inside an .h5 dataset file.

Supports PyMESS 1D (pump_probe, shaper_t2_scan), PyMESS 2D (time-domain and frequency-domain), PyMESS calibration HDF5 files, and PyMORGAN native 1D HDF5 archives.

Parameters:
Return type:

dict[str, Any]

pymorgan.oneD.load.read_PyMESS_PP(datafilename, *, load_single_scans=True, **kwargs)[source]#

Read a PyMESS pump-probe or shaper t2-scan (.h5) transient absorption file.

Handles standard single-condition scans as well as 1-pulse shaper t2 scans recorded in the 2D tab and multi-state slow modulation (e.g. polarization cycling, anisotropy, TOPAS stepping, mapped to Ndetectors).

Parameters:
  • datafilename (str) – Path to the PyMESS HDF5 (.h5) file.

  • load_single_scans (bool, optional) – Whether to load individual scan passes (default: True).

Returns:

LoaderResult – (Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv)

Return type:

tuple

pymorgan.oneD.load.load_pymess_anisotropy(datafilename, G_factor=1.0, threshold_mOD=0.05)[source]#

Load a slow-modulated polarization scan and unpack into Parallel, Perpendicular, Isotropic, and Anisotropy datasets.

Parameters:
  • datafilename (str or Path) – Path to the PyMESS HDF5 (.h5) file.

  • G_factor (float, optional) – Instrumental G-factor (I_par / I_perp sensitivity ratio). Default is 1.0.

  • threshold_mOD (float, optional) – Minimum isotropic signal in mOD below which anisotropy is clamped to NaN to prevent noise divergence. Default is 0.05 mOD.

Returns:

Dictionary containing: - ‘parallel’: Dataset1D of Parallel transient absorption - ‘perpendicular’: Dataset1D of Perpendicular transient absorption - ‘isotropic’: Dataset1D of Isotropic transient absorption - ‘anisotropy’: Dataset1D of Time-resolved polarization anisotropy r(t)

Return type:

dict of str -> Dataset1D

pymorgan.oneD.load.read_HARPIA(datafilename)[source]#

Read a Light Conversion HARPIA-TA transient absorption data file (.dat).

The file format consists of headers followed by repeated blocks: Line 0: Mode / reference info (e.g., ‘Pump-probe, Not referenced, …’) Line 1: Background header specification Line 2: Measurement header specification Line 3: ‘Wavelength: <val1>t<val2>…’ (probe axis in nm)

Followed by blocks starting with ‘Background, scan S, Delay …’ or ‘Measurement, scan S, Delay …’, a ‘Pump=…’ line, and 4 array lines for: 1. Sample Pumped (SmplPumped) 2. Reference Pumped (RefPumped) 3. Sample Unpumped (SmplUnpumped) 4. Reference Unpumped (RefUnpumped)

Return type:

Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv, scan_ids

Parameters:

datafilename (str)

pymorgan.oneD.load.parse_scan_selection(text, nmax)[source]#

Parse a 1-based scan selection string into sorted 0-based indices.

Accepts space- and/or comma-separated singles and a-b ranges, e.g. "1-4 6 9" or "1-3, 5". Out-of-range or malformed tokens raise ValueError. Returns the unique indices in ascending order.

Parameters:
Return type:

list[int]

pymorgan.oneD.load.mess_recalc_average(path, scan_indices, *, spectrum=0, slowmod=0, noise_weighted=True)[source]#

Recompute the average over selected MESS scans.

Reads the per-scan signal and per-scan noise from <folder>/temp and combines the selected scan_indices (0-based). When noise_weighted=True (default), combines scans by inverse-variance weighting (weight 1/noise**2), matching the acquisition’s averaged data: selecting every scan reproduces the main-directory _signal / _signal_noise files. When False, computes the direct arithmetic mean and propagates the per-scan noise. Returns (Zavg_R, Zstdv) shaped [Ndelays x Npixels x 1] and aligned to the dataset’s (deduplicated, sorted) delay axis.

Parameters:
Return type:

tuple[ndarray, ndarray]

pymorgan.oneD.load.parse_ufs(file_path)[source]#

Parse a Surface Xplorer .ufs binary file into (delays, probe, sig_mod, meta).

Supports Version2 (64-bit big-endian IEEE floats >f8) and Version1 (32-bit big-endian floats >f4). Converts DA / OD signal values to mOD (* 1000.0) unless z_unit already indicates mOD, sorts descending probe axes ascending, tracks interpolated padding quality, and includes a fallback for third-party csv -> ufs conversion outputs.

Parameters:

file_path (Path | str)

Return type:

tuple[ndarray, ndarray, ndarray, dict[str, Any]]

pymorgan.oneD.load.parse_helios_csv(file_path)[source]#

Parse a single Helios CSV file into delays, probe, and signal (in mOD, NaN-interpolated).

Parameters:

file_path (Path | str)

Return type:

tuple[ndarray, ndarray, ndarray]

pymorgan.oneD.load.read_Helios_UFS(datafilename, dataset_name=None)[source]#

Read a Surface Xplorer .ufs dataset (averaged file and sibling _scan*.ufs).

Parameters:
  • datafilename (str)

  • dataset_name (str | None)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.read_Helios_TA(datafilename, dataset_name=None)[source]#

Read Helios transient absorption dataset (.csv or .ufs averaged file and single scans).

Parameters:
  • datafilename (str)

  • dataset_name (str | None)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.read_Exported_TXT(datafilename)[source]#

Read an Exported TXT transient absorption dataset (TA.txt, time.txt, wavelength.txt).

Parameters:

datafilename (str)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.load.parse_quickcontrol_info(filepath)[source]#

Parse a PhaseTech QuickControl .info tab-delimited header file.

Parameters:

filepath (str | PathLike)

Return type:

dict[str, str]

pymorgan.oneD.load.classify_quickcontrol_info(filepath)[source]#

Classify a QuickControl .info file into (kind, has_scans).

Parameters:

filepath (str or PathLike) – Candidate .info path.

Returns:

kind is '1d', '2d', or None if not a QuickControl header. has_scans indicates whether at least one companion .scan file is present on disk.

Return type:

tuple of (str or None, bool)

pymorgan.oneD.load.read_QuickControl_PP(datafilename, *, load_single_scans=True, **kwargs)[source]#

Read a PhaseTech QuickControl 1D pump-probe dataset (.info + .scan).

When both parallel (_PAR#) and perpendicular (_PER#) scan series are present, the isotropic Magic Angle signal (PAR + 2 * PER) / 3 is placed at channel 0 so it is active by default, followed by Parallel (channel 1) and Perpendicular (channel 2).

Parameters:
  • datafilename (str) – Path to <prefix>.info, bare <prefix>, a sibling .scan file, or a folder containing a single 1D QuickControl dataset.

  • load_single_scans (bool, optional) – Whether to populate the 4D single-scan array Zss_R (default: True).

Returns:

LoaderResult – (Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv)

Return type:

tuple

Processing & Chirp Correction (pymorgan.oneD.process, pymorgan.oneD.chirp)#

Processing stage of the 1-D pipeline.

Basic operations (background subtraction) live here; the module is the home for future advanced processing (chirp/dispersion correction, coherent-artefact removal, SVD, global-analysis pre-processing).

pymorgan.oneD.process.background_correct(Zavg_R, Zss_R, nscans, delays, tmin, tmax, do_correct=True)[source]#

Subtract the pre-zero background averaged over [tmin, tmax].

Returns (Zavg_C, Zss_C, bkg_avg, bkg_ss). The background spectra (bkg_avg/bkg_ss) are always computed over [tmin, tmax] and stored, so they remain available for inspection/plotting regardless of do_correct. With do_correct=False the raw signal arrays are passed through unchanged (the background is computed but not subtracted).

Parameters:

do_correct (bool)

pymorgan.oneD.process.subtract_solvent(Z_sample, delays_sample, Z_solvent, delays_solvent, dt=0.0, scale=1.0)[source]#

Subtract a scaled, time-shifted solvent background from a sample signal.

The solvent signal is interpolated onto the sample’s delay grid after shifting its time axis by dt (positive dt means the solvent t₀ comes later than the sample t₀, i.e. the solvent delays are effectively shifted forward). Out-of-range delays are filled with the nearest boundary value (no extrapolation artefacts).

Parameters:
  • Z_sample (ndarray, shape [Ndelays × Npixels × Ndet]) – Sample signal (most-processed version available).

  • delays_sample (ndarray, shape [Ndelays]) – Sample delay axis (ps).

  • Z_solvent (ndarray, shape [Ndelays_s × Npixels × Ndet]) – Solvent signal (most-processed version available).

  • delays_solvent (ndarray, shape [Ndelays_s]) – Solvent delay axis (ps).

  • dt (float) – Global timing offset in ps. The effective solvent delays used for interpolation are delays_solvent - dt (i.e. a positive dt shifts the solvent signal towards earlier times on the sample grid).

  • scale (float or array-like) – Global (or per-pixel) amplitude scaling factor applied to the interpolated solvent before subtraction. A scalar applies the same factor to every pixel; a 1-D array of length Npixels applies a per-pixel factor.

Returns:

ndarray

Return type:

corrected signal, same shape as Z_sample

pymorgan.oneD.process.fit_solvent_auto(Z_sample, delays_sample, Z_solvent, delays_solvent, det_idx=0, per_pixel_dt=False, per_pixel_scale=True)[source]#

Automatically fit solvent time offsets and scaling factor.

Optimises a global (or per-pixel) timing offset dt and a global (or per-pixel) amplitude scaling factors scale such that the corrected signal Z_sample - scale * Z_solvent(t - dt) is as close as possible to an erf-broadened step-like rise.

Parameters:
  • Z_sample (ndarray, shape [Ndelays × Npixels × Ndet]) – Sample signal.

  • delays_sample (ndarray, shape [Ndelays]) – Sample delay axis (ps).

  • Z_solvent (ndarray, shape [Ndelays_s × Npixels × Ndet]) – Solvent signal.

  • delays_solvent (ndarray, shape [Ndelays_s]) – Solvent delay axis (ps).

  • det_idx (int, default 0) – The detector channel to use for the fitting optimisation.

  • per_pixel_dt (bool, default False) – If True, optimizes independent per-pixel timing offsets instead of a single global timing offset.

  • per_pixel_scale (bool, default True) – If True, optimizes independent per-pixel amplitude scaling factors instead of a single global scaling factor.

Returns:

  • scale (float or ndarray, shape [Npixels]) – Optimal global scaling factor (float) or per-pixel scaling factors (ndarray).

  • dt (float or ndarray, shape [Npixels]) – Optimal global timing offset (float) or per-pixel timing offsets (ndarray).

pymorgan.oneD.process.subtract_shockwave(Z, pixels, one_based=True)[source]#

Subtract an average kinetic trace calculated over pixels from all pixels.

Parameters:
  • Z (ndarray, shape [Ndelays × Npixels × Ndet] or [Ndelays × Npixels × Ndet × Nscans]) – Signal matrix to be corrected.

  • pixels (int, sequence of int, slice, or 1D boolean ndarray) – Pixel index or indices over which to compute the average shockwave trace.

  • one_based (bool, default True) – Whether pixels are specified as 1-based pixel indices (1..Npixels). Set to False if passing 0-based array indices (0..Npixels-1).

Returns:

  • Z_corrected (ndarray, same shape as Z) – Signal matrix after subtracting the averaged kinetic trace.

  • shockwave_trace (ndarray) – The extracted average kinetic trace that was subtracted, with shape [Ndelays × Ndet] (for 3D Z) or [Ndelays × Ndet × Nscans] (for 4D Z).

pymorgan.oneD.process.time_derivative(delays, Zavg_R, Zss_R=None, *, t_min=None, interpolate=False, n_interp=None, interp_kind='cubic', smooth=False, smooth_method='savgol', smooth_window=7, smooth_poly=2)[source]#

Calculate the time derivative d(Delta A)/dt along the delay axis.

Parameters:
  • delays (np.ndarray, shape (Ndelays,)) – Original delay values.

  • Zavg_R (np.ndarray) – Averaged transient absorption signal.

  • Zss_R (np.ndarray, optional) – Single-scan data if present.

  • t_min (float, optional) – If specified, drops all delay points where delays < t_min.

  • interpolate (bool, default False) – Whether to interpolate the data onto a denser delay grid before differentiating.

  • n_interp (int, optional) – Number of points for the interpolated delay grid. Defaults to 2 * len(delays).

  • interp_kind (str, default "cubic") – Interpolation method: “linear”, “cubic”, or “pchip”.

  • smooth (bool, default False) – Whether to smooth the kinetics before differentiating.

  • smooth_method (str, default "savgol") – Smoothing filter: “savgol”, “gaussian”, or “moving_average”.

  • smooth_window (int, default 7) – Window size for smoothing (odd integer >= 5 for savgol).

  • smooth_poly (int, default 2) – Polynomial order for Savitzky-Golay filter.

Returns:

  • delays_out (np.ndarray) – Output delay axis.

  • Zavg_dt (np.ndarray) – Differentiated averaged signal array (dZ/dt).

  • Zss_dt (np.ndarray or None) – Differentiated single-scan array if Zss_R was provided.

Return type:

tuple[ndarray, ndarray, ndarray | None]

pymorgan.oneD.process.calculate_anisotropy(parallel, perpendicular=None, *, g_factor=1.0, threshold=None, return_components=False, detector_par=0, detector_perp=1, use_corrected=True)[source]#

Calculate time-resolved polarization anisotropy from parallel and perpendicular datasets.

Supports either two separate Dataset1D instances (or 2D arrays), or a single multi-detector Dataset1D where detector_par and detector_perp specify the respective polarization channels.

Formulas#

  • Anisotropy:
    \[r(t, \omega) = \frac{I_\parallel - G \cdot I_\perp}{I_\parallel + 2G \cdot I_\perp}\]
  • Magic Angle / Isotropic signal:
    \[I_\text{MA}(t, \omega) = \frac{I_\parallel + 2G \cdot I_\perp}{3}\]
  • Polarization Difference:
    \[\Delta I(t, \omega) = I_\parallel - G \cdot I_\perp\]
param parallel:

Parallel polarization dataset or 2D array [Ndelays x Npixels]. If perpendicular is None, parallel must have at least 2 detectors.

type parallel:

Dataset1D or ndarray

param perpendicular:

Perpendicular polarization dataset or 2D array [Ndelays x Npixels].

type perpendicular:

Dataset1D or ndarray, optional

param g_factor:

Sensitivity correction factor G (scalar or 1D array of shape [Npixels]).

type g_factor:

float or ndarray, default 1.0

param threshold:

Minimum absolute value of the isotropic denominator below which anisotropy is clamped to NaN (avoids division-by-zero noise spikes).

type threshold:

float, optional

param return_components:

If True, returns a dict with keys 'anisotropy', 'magic_angle', 'difference', 'parallel', and 'perpendicular'. If False, returns just the anisotropy Dataset1D.

type return_components:

bool, default False

param detector_par:

Channel index for parallel polarization when unpacking a single multi-detector dataset.

type detector_par:

int, default 0

param detector_perp:

Channel index for perpendicular polarization when unpacking a single multi-detector dataset.

type detector_perp:

int, default 1

param use_corrected:

Whether to use background-corrected signal (Dataset1D.Z) or raw (Dataset1D.Zavg_R).

type use_corrected:

bool, default True

returns:

Anisotropy dataset or dictionary of component datasets.

rtype:

Dataset1D or dict[str, Dataset1D]

Parameters:

Chirp-correction (dispersion) fitting for the 1-D pipeline.

Kept in its own module, separate from pymorgan.oneD.process, because the coherent-artefact / dispersion fit is a substantially larger and more self-contained piece of analysis than the routine background subtraction that lives there. This is a fitting step only: it produces and saves the chirp (dispersion) coefficients. Loading a saved fit and applying it as a correction to a dataset (interpolating each pixel’s kinetic trace onto a common, chirp-free delay axis) is not implemented yet and is intentionally out of scope here.

Three fit modes are provided:

  • Automatic – VARPRO (variable projection): a Gaussian IRF (optionally with its 1st/2nd derivatives) plus a constant offset and an optional erf-broadened exponential (coherent artefact + early dynamics) is fit at every probe pixel. The linear amplitudes are eliminated in closed form at each iteration, leaving only (t0, FWHM, tau_exp) as nonlinear parameters (bounded Trust-Region-Reflective, via scipy.optimize.least_squares()). A second pass re-fits every pixel from smoothed initial guesses (an intermediate dispersion fit for t0, moving-median smoothing for FWHM/tau_exp).

  • Step function – a simpler Gaussian (+ derivatives) plus an erf (Heaviside convolved with the same Gaussian) step model, fit jointly (not VARPRO) over an early-time window. Useful as a quick/robust alternative when the exponential component of the Automatic model is not needed or not well-conditioned.

  • Manual – fits the Cauchy dispersion equation directly to a set of user-picked (wavelength, delay) points (see pymorgan.gui.picker.ContourPicker in axis="xy" mode), with no per-pixel IRF fit.

In all three modes, the resulting t0(lambda) values are fit to a generalised Cauchy dispersion equation (truncated at n_cauchy_terms, quadratic-in-1/lambda terms only), using an iteratively-reweighted (bisquare) linear least-squares fit – the dispersion equation is linear in its coefficients, so this is solved as a bound-constrained (bisquare-)reweighted linear least squares fit rather than a generic nonlinear solve.

Heavy/optional imports (scipy, pandas, scipy.io) are kept inside the functions that need them, matching the rest of the 1-D pipeline.

class pymorgan.oneD.chirp.ChirpFit(mode, coeffs, fit_wl, Pfit, equation='Cauchy', n_cauchy_terms=6, lambda_ref=nan, fit_pixels=<factory>, Dfit=None, mean_irf_fs=nan, detector=0, deriv_mask=(False, False), use_exp=False, do_2nd_pass=True, smooth_window=10, t_min=nan, t_max=nan, n_skipped=0, omega_w=nan, gamma_w=nan, source=None, chirp_file=None, created=<factory>)[source]#

Bases: object

Result of a chirp/dispersion fit.

coeffs are the Cauchy dispersion coefficients (see cauchy_t0()). Pfit holds the per-pixel (or per-point, for mode="manual") fit results: 8 columns [t0, FWHM, G0_amp, G1_amp, G2_amp, offset, tau_exp, exp_amp] for mode="automatic"; 7 columns [t0, FWHM, G0_amp, G1_amp, G2_amp, offset, step_amp] for mode="step" with use_exp=False, or 9 columns (appending [tau_exp, exp_amp]) when use_exp=True – FWHM is the genuine full width at half maximum (ps) of the Gaussian IRF in both modes, no further conversion needed – or a single [t0] column for mode="manual". Pixels skipped during an automatic/step fit (non-finite/all-zero data, or fit failure) carry NaN.

Parameters:
mode: str#
coeffs: ndarray#
fit_wl: ndarray#
Pfit: ndarray#
equation: str = 'Cauchy'#
n_cauchy_terms: int = 6#
lambda_ref: float = nan#
fit_pixels: ndarray#
Dfit: ndarray | None = None#
mean_irf_fs: float = nan#
detector: int = 0#
deriv_mask: tuple[bool, bool] = (False, False)#
use_exp: bool = False#
do_2nd_pass: bool = True#
smooth_window: int = 10#
t_min: float = nan#
t_max: float = nan#
n_skipped: int = 0#
omega_w: float = nan#
gamma_w: float = nan#
source: str | None = None#
chirp_file: str | None = None#
created: str#
property fwhm: ndarray#

Return the FWHM (in ps) vs wavelength for each fitted pixel.

Returns an array of NaN if not available (e.g. manual mode).

property t0: ndarray#

Return the fitted t0 (in ps) at each fitted wavelength (before Cauchy smoothing).

property fit_parameters_dict: dict[str, ndarray]#

Return a dictionary of the individual pixel/point fit parameters.

to_dict()[source]#

Flatten to a dictionary of arrays and scalars for saving via save_chirp_fit.

Uses compatible variable names (Cfit, fitPixels, fitWL, Pfit, Dfit) and 1-based indexing for fitPixels to maintain compatibility with downstream analysis scripts. Since savemat cannot embed a Python callable, chirpFun_str carries the equivalent anonymous-function source, and usage provides instructions on how to evaluate the curve.

Return type:

dict

classmethod from_dict(d)[source]#

Reconstruct from a dict produced by loading (see load_chirp_fit()).

Accepts both the standard compatible keys (Cfit/fitPixels/ fitWL, 1-based pixels) and the alternative key names (coeffs/fit_pixels/fit_wl, 0-based) for backward compatibility.

Also handles legacy MAT files, which do not store mode, lambda_ref or n_cauchy_terms. These are inferred automatically:

  • lambda_ref is reconstructed from mean(fitWL) – standard dispersion analysis uses this value as the reference wavelength for the Cauchy dispersion formula, and it can be verified from the scaleVec closure embedded in the saved function handle.

  • n_cauchy_terms is inferred from len(Cfit).

  • mode is guessed from the column count of Pfit: 8 → "automatic", 7 or 9 → "step", anything else → "manual".

Parameters:

d (dict)

Return type:

ChirpFit

pymorgan.oneD.chirp.cauchy_t0(coeffs, probe, lambda_ref)[source]#

Evaluate the generalised Cauchy dispersion equation at probe.

t0(L) = coeffs[0] + sum_{n=1}^{N-1} coeffs[n] * lambda_ref^(2n) / L^(2n). The lambda_ref prefactors render every coefficient dimensionless and of comparable magnitude.

Parameters:
Return type:

ndarray

pymorgan.oneD.chirp.fit_cauchy_dispersion(fit_wl, t0, *, n_terms=6, lambda_ref=None, robust=True, bounds=None, max_iter=30, tol=1e-09)[source]#

Fit t0(lambda) to the Cauchy dispersion equation.

The equation is linear in its coefficients, so this is solved as a bound-constrained (bisquare-)reweighted linear least squares fit (scipy.optimize.lsq_linear() per IRLS iteration) rather than a generic nonlinear solve. Returns (coeffs, lambda_ref).

Default bounds leave the leading (offset) term unconstrained ([-inf, inf]) and constrain higher-order terms in sign with magnitude up to max(100, 10 * ptp(t0)) according to the overall slope of t0(lambda).

Parameters:
Return type:

tuple[ndarray, float]

pymorgan.oneD.chirp.fit_chirp_automatic(data, *, detector=0, deriv_mask=(False, False), use_exp=True, n_cauchy_terms=6, cauchy_lambda_ref=None, do_2nd_pass=True, smooth_window=10, fit_pixels=None, progress_callback=None, should_cancel=None, preview_callback=None)[source]#

VARPRO coherent-artefact fit at every probe pixel + Cauchy dispersion fit.

deriv_mask selects which Gaussian-IRF derivative terms to include (1st, 2nd); use_exp adds the erf-broadened exponential (coherent artefact / early dynamics) term. With do_2nd_pass (default), a second VARPRO pass re-fits every pixel from an intermediate dispersion fit (for t0) and moving-median smoothing (for FWHM/tau_exp). Pixels with non-finite or all-zero data are skipped silently (NaN in Pfit). preview_callback, if given, is called after every pixel as (wavelength, delays, y_data, model_curve, t0) – intended for a live single-pixel data-vs-fit preview (e.g. in the GUI’s progress dialog, typically plotted as delays - t0 so the IRF stays centred regardless of dispersion); it is not needed for headless/scripted use.

Parameters:
Return type:

ChirpFit

pymorgan.oneD.chirp.fit_chirp_step(data, *, detector=0, deriv_mask=(True, True), use_exp=False, t_min=-1.0, t_max=3.0, n_cauchy_terms=6, cauchy_lambda_ref=None, fit_pixels=None, progress_callback=None, should_cancel=None, preview_callback=None)[source]#

Gaussian(+derivatives)+erf-step fit at every pixel, restricted to [t_min, t_max].

A simpler, jointly-fit (non-VARPRO) alternative to fit_chirp_automatic(). When use_exp=True (default False), an erf-broadened exponential coherent-artefact term is added, extending Pfit from 7 to 9 columns [t0, FWHM, G0_amp, G1_amp, G2_amp, offset, step_amp, tau_exp, exp_amp]. preview_callback, if given, is called after every pixel as (wavelength, delays, y_data, model_curve, t0) (see fit_chirp_automatic()).

Parameters:
Return type:

ChirpFit

pymorgan.oneD.chirp.fit_chirp_manual(data, points, *, detector=0, n_cauchy_terms=6, cauchy_lambda_ref=None)[source]#

Fit the Cauchy dispersion equation to manually-picked (wavelength, delay) points.

points is typically produced by interactively clicking the embedded contour map (see pymorgan.gui.picker.ContourPicker, axis="xy"). At least n_cauchy_terms points are required.

Parameters:
Return type:

ChirpFit

pymorgan.oneD.chirp.fit_chirp_wavelet(data, *, detector=0, t_min=-1.0, t_max=3.0, omega_w=0.125, gamma_w=0.225, n_cauchy_terms=6, cauchy_lambda_ref=None, do_2nd_pass=True, smooth_window=10, optimise_wavelet=False, optimize_wavelet=None, opt_max_iter=100, opt_progress_callback=None, fit_pixels=None, progress_callback=None, should_cancel=None, preview_callback=None)[source]#

Wavelet-based edge-detection fit at every probe pixel + Cauchy dispersion fit.

Based on the method by Kefer et al. (Applied Optics 2024). Convolves raw kinetics with a Morlet wavelet to isolate edge-like signal onsets (modulus peak).

When optimise_wavelet=True (or optimize_wavelet=True), the wavelet parameters omega_w and gamma_w are refined iteratively before the main per-pixel scan. A Nelder-Mead simplex optimiser minimises the RMS of the t0 residuals around the fitted Cauchy dispersion curve – i.e. it finds the wavelet shape that yields the smoothest, most continuous dispersion trace. The optimal parameters replace the user-supplied initial values, and are stored in the returned ChirpFit object (fit.omega_w, fit.gamma_w). opt_progress_callback, if given, is called after every optimiser iteration as (iter_number, param_summary_str, rms_fs).

Parameters:
Return type:

ChirpFit

pymorgan.oneD.chirp.plot_chirp_diagnostics(data, fit, *, detector=None)[source]#

Build the chirp-fit review figures: dispersion overlay, fit+residuals, and (for mode in {"automatic", "step"}) IRF FWHM vs wavelength, all combined into a single dashboard figure using Matplotlib subfigures.

Layout: [contour] [fig2 (dispersion fit + residuals)] [still contour] [fig3 (IRF FWHM vs wavelength)]

Returns a list containing the new single figure.

Parameters:
Return type:

list

pymorgan.oneD.chirp.save_chirp_fit(fit, path, n_detectors=1)[source]#

Save fit to path as a .h5/.hdf5, .json, or .mat file based on path suffix.

Parameters:
Return type:

None

pymorgan.oneD.chirp.load_chirp_fit(path)[source]#

Load a ChirpFit previously written by save_chirp_fit().

Also accepts legacy MAT chirp correction files. The legacy MAT format stores Cfit, fitWL, fitPixels, Pfit and a chirpFun function-handle object. The function handle cannot be evaluated by scipy, but it is not needed: the Cauchy dispersion curve is fully reconstructed from Cfit and the inferred reference wavelength (see ChirpFit.from_dict()).

Return type:

ChirpFit

pymorgan.oneD.chirp.default_chirp_filename(detector=None, n_detectors=1)[source]#

Default save name, e.g. chirpCorr_20260622-143000.mat or chirpCorr_DET1_20260622-143000.mat.

Parameters:
  • detector (int | None)

  • n_detectors (int)

Return type:

str

Advanced Scatter Removal (pymorgan.oneD.scatter)#

Advanced multi-band scatter and dynamic background removal for 1-D data.

Real pump-probe datasets often suffer from pump scatter that dims, spectrally walks, jitters delay-to-delay, or varies scan-to-scan alongside broadband fluorescence / wing drift. A static pre-zero subtraction cannot track those changes and leaves large positive/negative artifacts at late delays or around harmonic wavelengths.

This module isolates localized scatter bands from the broadband pre-zero background, optionally scales the broadband term by a smooth scatter envelope, and solves a joint local model (scatter basis + smooth local TA polynomial) per delay (and per single scan when available) so underlying transient absorption features and coherent artifacts are preserved.

class pymorgan.oneD.scatter.ScatterBand(p_min, p_max, wing_width=None, taper_width=None, enabled=True, label='', rank=None, couple_to=None)[source]#

Bases: object

Configuration for a single spectral scatter band (in native probe units).

Variables:
  • p_min (float) – Lower spectral bound of the scatter core in native probe units (swapped automatically with p_max if given in reverse order).

  • p_max (float) – Upper spectral bound of the scatter core in native probe units.

  • wing_width (float or None, optional) – Side-wing margin added on either side of [p_min, p_max] to form the local fitting window. When None or non-positive, defaults to max(3 * step, 0.5 * span).

  • taper_width (float or None, optional) – Raised-cosine taper width extending beyond [p_min, p_max]. When None or non-positive, defaults to min(wing_width, max(2 * step, 0.25 * span)).

  • enabled (bool, default True) – Whether the band is actively modelled and subtracted.

  • label (str, default "") – Human-readable label shown in diagnostics and GUI tables.

  • rank (int or None, optional) – Optional per-band override for the scatter basis rank / Taylor order (minimum 1). When None, inherits the global rank argument.

  • couple_to (int or None, optional) – Optional 0-based index of a primary band whose smoothed amplitude envelope drives this harmonic band with a single global scale factor.

Parameters:
p_min: float#
p_max: float#
wing_width: float | None = None#
taper_width: float | None = None#
enabled: bool = True#
label: str = ''#
rank: int | None = None#
couple_to: int | None = None#
class pymorgan.oneD.scatter.ScatterRemovalResult(Zavg_C, Zss_C, Zstdv, bkg_avg, bkg_ss, Z_static_C, Z_diff, bands, detector, params, band_diagnostics, metrics)[source]#

Bases: object

Outputs and diagnostics from compute_scatter_removal().

Variables:
  • Zavg_C (np.ndarray) – Scatter- and background-corrected averaged signal matching Zavg_R shape.

  • Zss_C (np.ndarray or None) – Corrected single-scan tensor [Ndelays x Npixels x Ndet x Nscans] when per_scan=True and single scans are available, else None.

  • Zstdv (np.ndarray or None) – Recomputed inter-scan standard deviation across cleaned single scans when update_noise=True and multiple scans exist, else None.

  • bkg_avg (np.ndarray) – Pre-zero background spectrum extracted from the raw signal.

  • bkg_ss (np.ndarray or None) – Per-scan pre-zero background spectra when single scans were processed, else None.

  • Z_static_C (np.ndarray) – Reference signal corrected solely with standard static pre-zero subtraction.

  • Z_diff (np.ndarray) – Difference matrix Z_static_C - Zavg_C isolating the dynamic scatter and broadband background component removed by the algorithm.

  • bands (list of ScatterBand) – Resolved scatter-band definitions used for the calculation.

  • detector (int) – 0-based detector index used for diagnostics and quality metrics.

  • params (dict) – Full parameter dictionary recording the configuration used.

  • band_diagnostics (list of dict) – Per-band basis matrices, pre-zero templates, per-delay coefficients, raw/smoothed amplitude envelopes, and centroid shifts for visualization.

  • metrics (dict) – Quantitative before/after summary metrics (pre-zero core RMS, positive-delay spectral roughness vs. wing reference, inter-scan STD, and saturated-pixel count).

Parameters:
Zavg_C: ndarray#
Zss_C: ndarray | None#
Zstdv: ndarray | None#
bkg_avg: ndarray#
bkg_ss: ndarray | None#
Z_static_C: ndarray#
Z_diff: ndarray#
bands: list[ScatterBand]#
detector: int#
params: dict[str, Any]#
band_diagnostics: list[dict[str, Any]]#
metrics: dict[str, Any]#
pymorgan.oneD.scatter.detect_scatter_bands(Z_2d, delays, probe, *, tmin=None, tmax=None, units=None, allow_positive=False)[source]#

Automatically detect primary and harmonic pump-scatter bands from pre-zero spectra.

Uses a two-tier strategy:

  1. Median-filter detrending + robust MAD thresholding on the pre-zero spectrum to detect strong localised scatter bands (negative by default, or signed when allow_positive=True).

  2. For calibrated wavelength (nm) probe axes, checks 2 * pump_wl (from metadata or the strongest Pass-1 band) for weaker 2nd-order grating scatter dips (>= 3 sigma added as coupled suggestions, auto-enabled when >= 5 sigma).

Parameters:
  • Z_2d (np.ndarray) – Two-dimensional transient signal matrix of shape [Ndelays x Npixels].

  • delays (np.ndarray) – Delay axis vector of length Ndelays.

  • probe (np.ndarray) – Spectral probe axis vector of length Npixels.

  • tmin (float, optional) – Pre-zero delay window bounds used to average the static background spectrum. Defaults to delays <= -1.0 (or earliest negative delays).

  • tmax (float, optional) – Pre-zero delay window bounds used to average the static background spectrum. Defaults to delays <= -1.0 (or earliest negative delays).

  • units (dict, optional) – Dataset units dictionary (used to detect OD vs. mOD scaling, wavelength calibration, and optional pymess_metadata["pump_wl_nm"]).

  • allow_positive (bool, default False) – Whether to detect positive sharp pre-zero artefacts in addition to negative scatter dips.

Returns:

Detected primary and optional coupled harmonic scatter bands ordered by descending peak amplitude.

Return type:

list of ScatterBand

pymorgan.oneD.scatter.compute_scatter_removal(dataset, bands=None, *, tmin=None, tmax=None, method='local_svd', rank=3, poly_deg=2, t0_exclude=(-0.5, 1.5), scale_broadband=True, per_scan=True, update_noise=True, transmittance_space=False, mask_saturated=False, saturation_threshold=500.0, allow_positive=False, detector=None)[source]#

Run multi-band scatter and dynamic background removal on a Dataset1D.

Parameters:
  • dataset (Dataset1D) – Input dataset.

  • bands (list of ScatterBand, optional) – Scatter bands (in native probe units). When None, bands are automatically detected via detect_scatter_bands().

  • tmin (float, optional) – Pre-zero delay window used for template extraction and baseline comparison. Defaults to delays <= -1.0 (or earliest negative delays).

  • tmax (float, optional) – Pre-zero delay window used for template extraction and baseline comparison. Defaults to delays <= -1.0 (or earliest negative delays).

  • method ({"local_svd", "taylor", "warped"}, default "local_svd") – Scatter basis model.

  • rank (int, default 3) – Number of local SVD modes or Taylor derivative order + 1 (per-band band.rank overrides this when set).

  • poly_deg (int, default 2) – Polynomial degree for the smooth local TA baseline inside fit windows.

  • t0_exclude (tuple of (float, float), default (-0.5, 1.5)) – Delay window excluded when learning local_svd modes so coherent artifacts around t0 are preserved.

  • scale_broadband (bool, default True) – Scale the non-scatter broadband pre-zero background by the slow Savitzky-Golay envelope of the primary scatter amplitude.

  • per_scan (bool, default True) – Clean individual scans (Zss_R) before averaging when available.

  • update_noise (bool, default True) – Recompute Zstdv across the cleaned single scans when per_scan is active and Nscans > 1.

  • transmittance_space (bool, default False) – Convert ΔA to transmittance modulation 10^(-ΔA/scale) - 1 before decomposition (for very strong / optically nonlinear scatter).

  • mask_saturated (bool, default False) – Mask raw pixels inside enabled scatter cores exceeding saturation_threshold to NaN.

  • saturation_threshold (float, default 500.0) – Absolute raw signal threshold for saturation masking (mOD).

  • allow_positive (bool, default False) – Also auto-detect positive sharp pre-zero features.

  • detector (int, optional) – If provided, process and compute diagnostics with respect to this detector channel (default None processes all channels and computes diagnostics for detector 0).

Return type:

ScatterRemovalResult

Stitching & SVD (pymorgan.oneD.stitch, pymorgan.oneD.svd)#

Dataset stitching algorithms for 1D Transient Absorption Spectroscopy.

Provides: - Wavelength stitching (e.g. UV/Vis + NIR spectral window merging) with

linear blending or hard cutover, and overlap scaling factor optimization.

  • Timescale stitching (e.g. femtosecond + nanosecond delay merging) with unit conversion, linear spectrometer calibration alignment, and wavelength-dependent quadratic scaling factor estimation.

class pymorgan.oneD.stitch.StitchResult(dataset, kind, scaling_factor, scaling_model='scalar', stitch_region=(0.0, 0.0), blend_window=None, cutover_val=None, blend_method='cubic', wl_shift_params=None, scaling_params=<factory>)[source]#

Bases: object

Container for dataset stitching results, scaling parameters, and provenance.

Variables:
  • dataset (Dataset1D) – The resulting stitched Dataset1D object.

  • kind ({"wavelength", "timescale"}) – The type of stitching performed.

  • scaling_factor (float | np.ndarray) – Scalar multiplier or 1D array of wavelength-dependent scaling factors.

  • scaling_model ({"scalar", "quadratic", "manual"}) – Model used to compute the scaling factor.

  • stitch_region (tuple[float, float]) – Overlap interval used for scaling estimation.

  • blend_window (tuple[float, float] | None) – Transition window for blending.

  • cutover_val (float | None) – Cutover threshold (if hard cutover).

  • blend_method ({"cubic", "linear", "quintic", "cosine", "step"}) – Transition weighting function used for blending.

  • wl_shift_params (tuple[float, float] | None) – Linear wavelength shift parameters (slope m, intercept b) if applied.

  • scaling_params (dict[str, Any]) – Additional fit diagnostics, polynomial coefficients, or SSR.

Parameters:
dataset: Dataset1D#
kind: Literal['wavelength', 'timescale']#
scaling_factor: float | np.ndarray#
scaling_model: str = 'scalar'#
stitch_region: tuple[float, float] = (0.0, 0.0)#
blend_window: tuple[float, float] | None = None#
cutover_val: float | None = None#
blend_method: str = 'cubic'#
wl_shift_params: tuple[float, float] | None = None#
scaling_params: dict[str, Any]#
property delays: ndarray#

1D delays array of the stitched dataset.

property probe: ndarray#

1D probe array of the stitched dataset.

property Z: ndarray#

Stitched data matrix [Ndelays x Npixels x 1].

to_dataset()[source]#

Return the stitched Dataset1D object.

Return type:

Dataset1D

export(filepath, file_format=None)[source]#

Export stitched dataset to file (PDAT, HDF5, or CSV).

Parameters:
Return type:

None

pymorgan.oneD.stitch.stitch_wavelength(ds1, ds2, stitch_region=None, mode='blend', blend_window=None, cutover_wl=None, time_threshold=-0.1, scale_override=None, target_delays='ds2', detector1=0, detector2=0, blend_method='cubic')[source]#

Stitch two datasets with different spectral ranges (e.g. UV/Vis + NIR).

Parameters:
  • ds1 (Dataset1D) – Dataset 1 (typically the shorter wavelength window, e.g. UV/Vis).

  • ds2 (Dataset1D) – Dataset 2 (typically the longer wavelength window, e.g. NIR).

  • stitch_region (tuple[float, float], optional) – Wavelength range (wl_min, wl_max) over which the scaling factor C is fitted (such that C * ds1 ~ ds2). If None, automatically set to the inner 80% of the overlapping probe range.

  • mode ({"blend", "cutover"}, default "blend") – Stitching transition mode: - "blend": Weighted linear cross-fade ramp across blend_window. - "cutover": Direct concatenation at cutover_wl without interpolation.

  • blend_window (tuple[float, float], optional) – Wavelength transition window (blend_start, blend_end). Defaults to the overlap region.

  • cutover_wl (float, optional) – Wavelength threshold below which ds1 is kept and above which ds2 is kept. Defaults to the midpoint of the overlap region.

  • time_threshold (float, default -0.1) – Minimum delay time for including kinetic points in the scaling fit.

  • scale_override (float, optional) – Manual scaling factor to use instead of the least-squares optimal factor.

  • target_delays ({"ds2", "ds1"} or np.ndarray, default "ds2") – Delay grid onto which the non-matching dataset is interpolated.

  • detector1 (int, default 0) – Detector channels if multi-detector datasets.

  • detector2 (int, default 0) – Detector channels if multi-detector datasets.

  • blend_method (Literal['cubic', 'linear', 'quintic', 'cosine', 'step'])

Returns:

Result containing the stitched Dataset1D and fit metadata.

Return type:

StitchResult

pymorgan.oneD.stitch.stitch_time(ds_fs, ds_ns, time_overlap=(0.5, 2.0), blend_window=(1.0, 1.7), scale_model='quadratic', scale_override=None, align_wl=True, cut_scatter=False, scatter_region=(500.0, 550.0), detector_fs=0, detector_ns=0, blend_method='cubic')[source]#

Stitch femtosecond and nanosecond/microsecond datasets across timescales.

Parameters:
  • ds_fs (Dataset1D) – Ultrafast (femtosecond) dataset. If delays are in ps, they are automatically converted to ns.

  • ds_ns (Dataset1D) – Long-delay (nanosecond) dataset with delays in ns.

  • time_overlap (tuple[float, float], default (0.5, 2.0)) – Delay window in ns where the scaling factor is calculated.

  • blend_window (tuple[float, float], default (1.0, 1.7)) – Delay transition window in ns over which the blend weight ramp is applied.

  • scale_model ({"quadratic", "scalar"}, default "quadratic") –

    • "quadratic": Fit a smooth quadratic polynomial S(lambda) across wavelengths.

    • "scalar": Fit a single global scalar multiplier C.

  • scale_override (float, optional) – Manual scalar scaling multiplier.

  • align_wl (bool, default True) – Optimize linear spectrometer shift (m * lambda + b) to reconcile slight grating offsets.

  • cut_scatter (bool, default False) – Exclude scatter band from wavelength alignment.

  • scatter_region (tuple[float, float], default (500.0, 550.0)) – Wavelength band to ignore during alignment if cut_scatter is True.

  • detector_fs (int, default 0) – Detector channel index.

  • detector_ns (int, default 0) – Detector channel index.

  • blend_method ({"cubic", "linear", "quintic", "cosine", "step"}, default "cubic") – Weighting function used across the blend transition window.

Returns:

Result containing the stitched Dataset1D and scaling diagnostics.

Return type:

StitchResult

Singular Value Decomposition (SVD) for 1D Transient Absorption Spectroscopy.

Provides SVD factorization, component extraction, scree analysis, data recomposition with rank-k truncation, and residual calculation.

class pymorgan.oneD.svd.SVDResult(U, S, Vt, delays, probe, k, raw_matrix, centering='none', offset=<factory>, variance_explained=<factory>, cumulative_variance=<factory>, units=<factory>)[source]#

Bases: object

Container for SVD results with rank-k recomposition and component access.

Variables:
  • U (np.ndarray) – Left singular vectors (temporal components), shape (M, n_comp).

  • S (np.ndarray) – Singular values, shape (n_comp,) in descending order.

  • Vt (np.ndarray) – Right singular vectors transposed (spectral components), shape (n_comp, N).

  • delays (np.ndarray) – 1D delay axis array of length M.

  • probe (np.ndarray) – 1D probe axis array of length N.

  • k (int) – Default / active rank truncation (number of components for recomposition).

  • raw_matrix (np.ndarray) – The input data matrix (cropped and NaN-handled), shape (M, N).

  • centering (str) – Centering applied before SVD (“none”, “spectrum”, “kinetic”, “both”).

  • offset (np.ndarray) – Centering offset array subtracted before SVD, shape (M, N) or broadcastable.

  • variance_explained (np.ndarray) – Fraction of total variance explained by each singular value: \(S_i^2 / \sum S_j^2\).

  • cumulative_variance (np.ndarray) – Cumulative sum of fraction of total variance explained.

  • units (dict) – Units dictionary associated with the dataset (if available).

Parameters:
U: ndarray#
S: ndarray#
Vt: ndarray#
delays: ndarray#
probe: ndarray#
k: int#
raw_matrix: ndarray#
centering: str = 'none'#
offset: ndarray#
variance_explained: ndarray#
cumulative_variance: ndarray#
units: dict#
property n_components: int#

Total number of available singular components.

recompose(k=None)[source]#

Recompose the data matrix using the first k components.

Parameters:

k (int, optional) – Number of components to use. If None, uses self.k.

Returns:

Recomposed 2D matrix of shape (M, N), including the centering offset.

Return type:

np.ndarray

residuals(k=None)[source]#

Compute residuals (raw_matrix - recompose(k)).

Parameters:

k (int, optional) – Number of components to use. If None, uses self.k.

Returns:

Residuals 2D matrix of shape (M, N).

Return type:

np.ndarray

component_time(idx, scaled=True)[source]#

Return the temporal trace (left singular vector) for component idx.

Parameters:
  • idx (int) – 0-based component index.

  • scaled (bool, default True) – If True, scales by the corresponding singular value \(S[idx]\).

Return type:

ndarray

component_probe(idx)[source]#

Return the spectral trace (right singular vector) for component idx.

Parameters:

idx (int) – 0-based component index.

Return type:

ndarray

variance_at(k)[source]#

Return cumulative variance explained by the first k components (0 to 1).

Parameters:

k (int)

Return type:

float

to_dataset(k=None, name=None, units=None)[source]#

Construct a new Dataset1D containing the recomposed data.

Parameters:
  • k (int, optional) – Number of components to use. If None, uses self.k.

  • name (str, optional) – Source description name.

  • units (dict, optional) – Units dictionary. Defaults to self.units.

Returns:

New dataset with recomposed signal in Zavg_R and Zavg_C.

Return type:

Dataset1D

to_dataframe(k=None)[source]#

Convert components, scree table, recomposed, and residuals to pandas DataFrames.

Returns a dictionary with keys: 'scree', 'temporal', 'spectral', 'recomposed', and 'residuals'.

Parameters:

k (int | None)

Return type:

dict[str, pd.DataFrame]

export_csv(filepath, k=None)[source]#

Export SVD scree summary and first k components to CSV file(s).

If filepath ends with .csv, writes a composite CSV with sections.

Parameters:
Return type:

None

pymorgan.oneD.svd.compute_svd(data, delays, probe, k=2, tmin=None, tmax=None, probe_min=None, probe_max=None, centering='none', handle_nan='interpolate', units=None)[source]#

Compute Singular Value Decomposition on transient absorption data.

Parameters:
  • data (np.ndarray) – 2D data matrix of shape (M, N) where M is the number of delays and N is the number of probe points.

  • delays (np.ndarray) – 1D delay array of length M.

  • probe (np.ndarray) – 1D probe array of length N.

  • k (int, default 2) – Number of principal components to select for recomposition.

  • tmin (float, optional) – Delay range limits for cropping prior to SVD.

  • tmax (float, optional) – Delay range limits for cropping prior to SVD.

  • probe_min (float, optional) – Probe range limits for cropping prior to SVD.

  • probe_max (float, optional) – Probe range limits for cropping prior to SVD.

  • centering ({"none", "spectrum", "probe", "kinetic", "time", "both"}, default "none") – Centering method applied before factorization: - "none": Standard uncentered SVD (physical TA decomposition). - "spectrum" / "probe": Subtract average spectrum (mean across delays). - "kinetic" / "time": Subtract average kinetic trace (mean across probe). - "both": Double-centered SVD.

  • handle_nan ({"interpolate", "drop", "raise"}, default "interpolate") – How to handle NaN values in data: - "interpolate": Drop fully-NaN rows/cols, then interpolate isolated NaNs. - "drop": Drop any row or column containing NaN. - "raise": Raise ValueError if NaNs are found.

  • units (dict, optional) – Units dictionary associated with the dataset.

Returns:

Result container with components, scree analysis, and recomposition tools.

Return type:

SVDResult

1D Plotters (pymorgan.oneD.plot)#

Plotting stage of the 1-D pipeline.

Every plotter takes a Dataset1D as its first argument and reads the delay/probe axes, signal and unit dictionary from it. Label style, colourmap, time-axis scale and the delta-A unit convention default to the active pymorgan.settings.Settings and can be overridden per call. This makes the plotting layer extensible: a new view only needs (data, ax, ...) and gains the whole pipeline’s context.

pymorgan.oneD.plot.plot_contour(data, ax=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, ShowLines=False, smooth=0, filled=True, Nlevels=None, Nskip=None, white_levels=None, Asinh=False, asinh_pct=None, cbarLbl='top', cmap_ID=None, anisotropy=False, Zmax=None, Zmin=None, Zscale=100, ProbeDir='X', Yscale=None, time_axis_label=None, quick=None, show_xlabel=True, show_ylabel=True, show_colorbar=True, show_colorbar_label=True, aspect='auto')[source]#

Delay-vs-probe contour map of data.

Draws the transient signal as a filled contour map (probe on X, delay on Y by default) with a symmetric, zero-centred colour scale and a divider colorbar. Every keyword that is not given falls back to the active Settings, so the defaults follow the settings file and only per-figure choices need to be passed.

Parameters:
  • data (Dataset1D) – Dataset to plot. Bound as Dataset1D.plot_contour, so this argument is supplied automatically when called as a method.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into. None creates a new figure sized from Settings.contour_figsize and lays it out with tight_layout. When an axis is supplied the figure geometry is left untouched, which is what makes the plotter usable inside a GridSpec composite (see examples/composite_1D.py).

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for axis labels, e.g. "Delay (ps)" vs "Delay / ps". Defaults to Settings.label_style.

  • delta_a_units (str, optional) – Signal-unit convention for the colorbar label (“mOD”, “x1E3”, …). Defaults to Settings.delta_a_units. Data are always stored in mOD.

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display. Defaults to Settings.x_axis_unit (no conversion when unset).

  • secondary_axis (bool, optional) – Add a complementary-unit axis opposite the probe axis (top for ProbeDir="X", right for "Y"). Defaults to the active setting.

  • ShowLines (bool, default False) – True overlays black contour lines on the filled map; False colours the contour lines with the colourmap instead.

  • smooth (int, default 0) – Box-filter width (points) applied to the data used for the contour-line overlay only, when ShowLines is set. The filled background always uses the raw data. Values <= 1 disable smoothing.

  • filled (bool, default True) – Draw the filled contourf background. False gives a line-only map.

  • Nlevels (int, optional) – Number of contour levels (rounded up to an even number so the scale stays symmetric about zero). Default 30.

  • Nskip (int, default 2) – Keep every Nskip-th contour line, counting outwards from zero, so the line overlay stays legible when Nlevels is large.

  • white_levels (float, optional) – Number of central levels forced to white, which suppresses noise around the zero crossing. Defaults to Settings.white_levels.

  • Asinh (bool, default False) – Apply arcsinh color scaling and non-linear contour levels, compressing large amplitudes so weak and strong bands can share one scale while preserving native signal units on the data and colorbar.

  • asinh_pct (float, optional) – Linear threshold for arcsinh color scaling as a percentage of the active amplitude limit (Zscale / Zmax). Defaults to Settings.asinh_pct (5.0%).

  • cbarLbl ({"side", "top"}, default "side") – Place the colorbar unit label beside or above the bar.

  • cmap_ID (str, optional) – Colourmap specification (e.g. "DkRd/Wh/DkBu", "vik", "berlin"). Defaults to Settings.cmap.

  • anisotropy (bool, default False) – Treat Z as an anisotropy map and fix the colour scale to +/-0.7.

  • Zmin (float, optional) – Explicit colour-scale limits, in the plotted signal units. Given together they override Zscale; this is how several panels are put on a common scale.

  • Zmax (float, optional) – Explicit colour-scale limits, in the plotted signal units. Given together they override Zscale; this is how several panels are put on a common scale.

  • Zscale (float, default 100) – Colour-scale limit as a percentage of the peak absolute signal, used when Zmax is not given. Values below 100 saturate the map and bring out weak features.

  • ProbeDir ({"X", "Y"}, default "X") – Axis carrying the probe; "Y" transposes the map so delay runs along X.

  • Yscale ({"symlog", "log", "lin"}, optional) – Scale of the delay axis. Defaults to Settings.time_axis_scale. "symlog" is linear within +/-1 (time unit) and logarithmic outside.

  • time_axis_label (str, optional) – Tick-label convention for a log/symlog delay axis. Defaults to Settings.time_axis_label.

  • quick (bool, optional) – Draw a single rasterised pcolormesh instead of contour sets and skip the line overlay. Much faster for large maps and for interactive use. Defaults to Settings.quick_plots.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels. Set to False on inner panels of a composite figure that share an axis with a neighbour.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels. Set to False on inner panels of a composite figure that share an axis with a neighbour.

  • show_colorbar (bool, default True) – Attach the divider colorbar. Set False when several panels share one externally drawn colorbar.

  • show_colorbar_label (bool, default True) – Draw the unit label on the colorbar (ignored when show_colorbar is False).

Returns:

The axis the map was drawn into.

Return type:

matplotlib.axes.Axes

Notes

Detector gaps (jumps in the probe axis larger than 1.5x the median spacing) are masked so no contour is interpolated across them.

Examples

>>> ax = data.plot_contour(ShowLines=True, Zscale=30, Yscale="symlog")
>>> data.plot_contour(ax=ax_panel, show_colorbar=False, Zmin=-2, Zmax=2)
pymorgan.oneD.plot.apply_delay_axis(where, axis_name, scale, Y_t, time_axis_label=None, settings=None)[source]#

Scale and format a delay axis the way plot_contour does.

axis_name is "x", "y" or "z"; scale is "symlog", "log" or "lin". Keeps every delay axis consistent with the embedded contour (same scale, limits and tick-label format), which is what the plot-controls panel configures.

Public so that a host application drawing a view PyMORGAN has no concept of – PyRATE-TA’s concentration profiles, for instance – still gets the delay axis this package defines, rather than a second convention beside it.

pymorgan.oneD.plot.plot_surface(data, ax=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, ShowLines=False, Asinh=False, cbarLbl='top', cmap_ID=None, show_xlabel=True, show_ylabel=True, show_colorbar=True, show_colorbar_label=True, rstride=1, cstride=1, elev=30, azim=-60, Yscale=None, time_axis_label=None)[source]#

Render delay-vs-probe 3D surface plot with colourmap shading.

The delay (Y) axis follows the same configuration as the contour plots – Yscale defaults to Settings.time_axis_scale and the tick labels to Settings.time_axis_label – so the surface matches the embedded preview and the plot-controls panel.

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_surface.

  • ax (mpl_toolkits.mplot3d.axes3d.Axes3D, optional) – 3-D axis to draw into. None creates one; a supplied axis must already have projection="3d".

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Z label.

  • ShowLines (bool, default False) – Draw the surface with visible wireframe edges.

  • Asinh (bool, default False) – Plot arcsinh(Z), compressing large amplitudes.

  • cbarLbl ({"side", "top"}, default "side") – Placement of the colorbar unit label.

  • cmap_ID (str, optional) – Colourmap specification; defaults to Settings.cmap.

  • show_xlabel (bool) – Element visibility, all True by default.

  • show_ylabel (bool) – Element visibility, all True by default.

  • show_colorbar (bool) – Element visibility, all True by default.

  • show_colorbar_label (bool) – Element visibility, all True by default.

  • rstride (int, default 1) – Row / column downsampling of the surface mesh. Increase for large maps.

  • cstride (int, default 1) – Row / column downsampling of the surface mesh. Increase for large maps.

  • elev (float, default 30 and -60) – Initial camera elevation and azimuth, in degrees.

  • azim (float, default 30 and -60) – Initial camera elevation and azimuth, in degrees.

  • Yscale ({"symlog", "log", "lin"}, optional) – Scale of the delay axis; defaults to Settings.time_axis_scale.

  • time_axis_label (str, optional) – Tick-label convention for a log/symlog delay axis.

Returns:

The axis the surface was drawn into.

Return type:

mpl_toolkits.mplot3d.axes3d.Axes3D

pymorgan.oneD.plot.plot_noise_3d(data, ax=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, show_xlabel=True, show_ylabel=True)[source]#

Plot the noise array as a rotatable 3D surface plot using the ‘hot_r’ colourmap.

The noise surface makes it easy to spot pixels or delay ranges where the standard deviation is anomalously high (bad detector pixels, a drifting scan) before those regions are trusted in a fit.

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_noise_3d.

  • ax (mpl_toolkits.mplot3d.axes3d.Axes3D, optional) – 3-D axis to draw into (projection="3d" required when supplied).

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the noise (Z) label.

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display.

  • secondary_axis (bool, optional) – Add a complementary-unit axis.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

Returns:

The axis the surface was drawn into.

Return type:

mpl_toolkits.mplot3d.axes3d.Axes3D

Raises:

ValueError – If the dataset carries neither a noise array nor single-scan data.

See also

pymorgan.oneD.Dataset1D.noise_array

the array this plots.

pymorgan.oneD.plot.plot_noise_spectrum(data, ax=None, fig=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, dualScale=None, color='purple', title=None, show_xlabel=True, show_ylabel=True, **kwargs)[source]#

Plot the delay-averaged noise spectrum versus the probe axis.

Computes the mean across the delay axis of Dataset1D.noise_array() and renders it as a 1-D trace against the active spectral X axis unit (Honouring Settings.x_axis_unit and Settings.secondary_axis).

Parameters:
  • detector (int)

  • label_style (str | None)

pymorgan.oneD.plot.plot_counts(data, ax=None, *, settings=None, label_style=None, Yscale=None, time_axis_label=None)[source]#

Plot accumulation counts as a function of probe delay.

Parameters:
  • data (Dataset1D) – Dataset to plot.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into. If None, creates a new figure.

  • settings (Settings, optional) – Active settings.

  • label_style (str, optional) – Label delimiter style.

  • Yscale ({"symlog", "log", "lin"}, optional) – Delay axis scale (defaults to time_axis_scale from settings).

  • time_axis_label (str, optional) – Format string for delay axis tick labels.

Return type:

matplotlib.axes.Axes

pymorgan.oneD.plot.legend_placement(settings=None)[source]#

loc (and anchor) for a cut legend, as **kwargs for ax.legend.

"outside right" (the default) parks the legend beside the axis, which suits a stand-alone figure with many traces; every other value places it inside. A host drawing into a small embedded panel passes a settings copy that forces it inside, since an outside legend there is drawn over the neighbouring panel or clipped away entirely.

Public so that a host application redrawing a legend of its own (PyRATE-TA’s embedded panels do, after overlaying a fit) places it where the user asked rather than guessing.

Return type:

dict

pymorgan.oneD.plot.plot_spectra(data, plot_delays, ax=None, fig=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, dualScale=None, normY=False, anisotropy=None, roundT=None, flipColor=False, Abs=None, Em=None, doSmooth=0, show_xlabel=True, show_ylabel=True, **kwargs)[source]#

Transient spectra at the requested plot_delays.

Draws one spectrum per requested delay, coloured along a rainbow scale from early to late, with a draggable legend giving each delay in the most readable time unit (fs / ps / ns). Unset keywords fall back to the active Settings.

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_spectra.

  • plot_delays (sequence of float) – Delays to cut at, in the dataset’s own time unit. Each is snapped to the nearest measured delay and duplicates are dropped, so approximate values are fine.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a figure sized from Settings.spectra_figsize.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label (“mOD”, “x1E3”, …).

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display.

  • secondary_axis (bool, optional) – Add a top axis in the complementary spectral unit.

  • dualScale (bool, optional) – Deprecated alias for secondary_axis.

  • normY (bool, default False) – Normalise each spectrum to its own peak absolute amplitude, which compares band shapes independently of intensity.

  • anisotropy (bool, optional) – Label the Y axis r(t) and fix its limits to [-1.0, 1.0]. Inferred automatically if data is an anisotropy dataset.

  • roundT (bool, optional) – Round the delays shown in the legend. Defaults to Settings.round_labels.

  • flipColor (bool, default False) – Reverse the rainbow colour order (late delays coloured as early ones).

  • Abs (dict or Spectrum, optional) – Steady-state absorption / emission overlay, as {"X": ..., "Y": ...} or a Spectrum. Drawn inverted and normalised on a twin axis whose zero is aligned with the transient one. Em is multiplied by X**4 first (wavelength-to-wavenumber Jacobian for a fluorescence spectrum).

  • Em (dict or Spectrum, optional) – Steady-state absorption / emission overlay, as {"X": ..., "Y": ...} or a Spectrum. Drawn inverted and normalised on a twin axis whose zero is aligned with the transient one. Em is multiplied by X**4 first (wavelength-to-wavenumber Jacobian for a fluorescence spectrum).

  • doSmooth (int, default 0) – Box-filter width in points. > 0 plots the smoothed trace only; < 0 plots the smoothed trace over a faint copy of the raw one, which is the honest way to show how much smoothing was applied.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot() (linewidth, linestyle, …).

Returns:

The axis the spectra were drawn into.

Return type:

matplotlib.axes.Axes

Notes

Detector gaps are masked, so traces are broken rather than interpolated across them. When Settings.error_shading is on and the dataset carries a noise array, each trace is drawn with a shaded +/-1 sigma band.

The legend is placed by Settings.legend_location – beside the axis by default, which suits a single-panel figure; any Matplotlib loc puts it inside instead.

Examples

>>> data.plot_spectra([0.5, 1, 5, 50, 500], doSmooth=3, roundT=True)
>>> data.plot_spectra([1, 10], ax=panel, x_axis_unit="nm", secondary_axis=True)
pymorgan.oneD.plot.plot_background(data, ax=None, fig=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, dualScale=None, normY=False, doSmooth=0, color='r', title=None, show_xlabel=True, show_ylabel=True, **kwargs)[source]#

Pre-zero background spectrum, drawn with the transient-spectra rules.

Mirrors plot_spectra() for the single averaged background trace stored on data (bkg_avg, populated by Dataset1D.background_correct()): same detector-gap masking, dual-scale option, axis labels, zero line and autoscaling. There is no legend (a single trace).

A flat background at zero indicates a clean pre-zero region; structure in it that resembles the transient spectrum usually means the background window overlaps the rise, or that scattered pump light reaches the detector.

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_background.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a figure sized from Settings.spectra_figsize.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label.

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display.

  • secondary_axis (bool, optional) – Add a top axis in the complementary spectral unit.

  • dualScale (bool, optional) – Deprecated alias for secondary_axis.

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

  • doSmooth (int, default 0) – Box-filter width in points (< 0 overlays the raw trace faintly).

  • colour (str, default "r") – Line colour.

  • title (str, optional) – Axis title.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot().

Returns:

The axis the background was drawn into.

Return type:

matplotlib.axes.Axes

Raises:

ValueError – If no background has been computed; call Dataset1D.background_correct() first (do_correct=False stores the background without subtracting it).

pymorgan.oneD.plot.plot_kinetics(data, plot_wavelengths, ax=None, fig=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, normY=False, Xscale=None, anisotropy=None, plotStyle='o-', doSmooth=0, round_labels=None, show_xlabel=True, show_ylabel=True, swap_axes=False, x_axis_unit=None, input_unit=None, **kwargs)[source]#

Kinetic traces at the requested plot_wavelengths.

Draws the signal versus delay at one or more probe positions, on the time axis convention of the active Settings ("symlog" by default: linear within +/-1 time unit, logarithmic outside, so the rise around time zero and decades of decay share one panel).

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_kinetics.

  • plot_wavelengths (sequence of float) – Probe positions to cut at, in the dataset’s native probe unit (nm, cm-1, …) by default, or in input_unit if supplied. Each is snapped to the nearest pixel and duplicates are dropped.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a figure sized from Settings.kinetics_figsize.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label (“mOD”, “x1E3”, …).

  • normY (bool, default False) – Normalise each trace to its own peak absolute amplitude, which compares decay kinetics independently of amplitude.

  • Xscale ({"symlog", "log", "lin"}, optional) – Scale of the delay axis. Defaults to Settings.time_axis_scale.

  • anisotropy (bool, optional) – Label the Y axis r(t) and fix its limits to [-1.0, 1.0]. Inferred automatically if data is an anisotropy dataset.

  • doSmooth (int, default 0) – Box-filter width in points applied to each trace; < 0 also draws the raw trace faintly underneath, so the smoothing can be judged.

  • plotStyle (str, default "o-") – Matplotlib format string for the traces, e.g. "-" for lines only.

  • round_labels (bool, optional) – Round the probe positions shown in the legend. Defaults to Settings.round_labels.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • x_axis_unit (str, optional) – Display spectral unit for the trace legend labels (defaults to Settings.x_axis_unit).

  • input_unit (str, optional) – Unit of plot_wavelengths (None / "native", "display" for scaled display units, or an explicit spectral unit such as "eV" or "nm").

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot(). markersize and linewidth default to Settings.kinetics_marker_size and Settings.kinetics_line_width unless given explicitly (ms / lw also count as given).

Returns:

  • ax (matplotlib.axes.Axes) – The axis the traces were drawn into.

  • t (numpy.ndarray) – Delay axis, shape [Ndelays].

  • Y (numpy.ndarray) – Extracted traces, shape [Ndelays x Ncuts], in the order of plot_wavelengths after snapping. Useful for exporting or fitting the same data that was plotted.

Notes

When Settings.error_shading is on and the dataset carries a noise array, each trace is drawn with a shaded +/-1 sigma band. The legend is placed by Settings.legend_location, beside the axis by default.

The returned Y is the extracted data itself, so this is also the supported way to get traces out of PyMORGAN for fitting elsewhere (kinetic fitting lives in the companion project PyRATE-TA).

Examples

>>> ax, t, Y = data.plot_kinetics([2132, 2218], plotStyle="-", lw=1.5)
>>> Y.shape
(45, 2)
pymorgan.oneD.plot.plot_scan_kinetics(data, plot_wavelengths, ax=None, fig=None, *, detector=0, binsize=1, settings=None, label_style=None, delta_a_units=None, normY=False, Xscale=None, plotStyle='o-', round_labels=None, show_xlabel=True, show_ylabel=True, x_axis_unit=None, input_unit=None, **kwargs)[source]#

Per-scan kinetic traces at requested plot_wavelengths.

Overlays one trace per scan group at each probe position. When more than one probe position is requested, the position is prefixed to each label. This is the diagnostic for scan-to-scan reproducibility: systematic drift between groups points to sample degradation or a moving alignment, whereas random scatter is just shot noise.

Requires single-scan data, i.e. a directory format loaded with Settings.load_single_scans enabled (check Dataset1D.has_single_scans).

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_scan_kinetics.

  • plot_wavelengths (sequence of float) – Probe positions to cut at, in the native probe unit (or input_unit).

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a figure sized from Settings.kinetics_figsize.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • binsize (int, default 1) – Number of consecutive scans averaged into each trace. 1 plots every scan; larger values trade scan resolution for signal-to-noise.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label.

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

  • Xscale ({"symlog", "log", "lin"}, optional) – Scale of the delay axis; defaults to Settings.time_axis_scale.

  • plotStyle (str, default "o-") – Matplotlib format string for the traces.

  • round_labels (bool, optional) – Round the probe positions in the legend; defaults to Settings.round_labels.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • x_axis_unit (str, optional) – Display spectral unit for the trace legend labels and titles (defaults to Settings.x_axis_unit).

  • input_unit (str, optional) – Unit of plot_wavelengths (None / "native", "display" for scaled display units, or an explicit spectral unit such as "eV" or "nm").

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot().

Returns:

  • ax (matplotlib.axes.Axes) – The axis the traces were drawn into.

  • t (numpy.ndarray) – Delay axis, shape [Ndelays].

  • Y (numpy.ndarray) – Binned traces, shape [Ndelays x Npixels x Nbins].

pymorgan.oneD.plot.plot_scan_spectra(data, plot_delays, ax=None, fig=None, *, detector=0, binsize=1, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, normY=False, doSmooth=0, roundT=None, show_xlabel=True, show_ylabel=True, **kwargs)[source]#

Per-scan transient spectra at the requested delay(s).

Overlays one spectrum per scan – or per group of binsize scans, averaged – at each requested delay. Traces are coloured by scan group and the legend labels the groups (“Scan 3”, “Scans 4 to 6”); the delay is prefixed when more than one delay is requested. doSmooth matches plot_spectra() (>0 smoothed, <0 smoothed + faint original).

Requires single-scan data (see Dataset1D.has_single_scans); the spectral counterpart of plot_scan_kinetics().

Parameters:
  • data (Dataset1D) – Dataset to plot; supplied automatically via Dataset1D.plot_scan_spectra.

  • plot_delays (sequence of float) – Delays to cut at, in the dataset’s own time unit.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a figure sized from Settings.spectra_figsize.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • detector (int, default 0) – Detector index for multi-detector datasets.

  • binsize (int, default 1) – Number of consecutive scans averaged into each spectrum.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label.

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display.

  • secondary_axis (bool, optional) – Add a top axis in the complementary spectral unit.

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

  • doSmooth (int, default 0) – Box-filter width in points (< 0 overlays the raw trace faintly).

  • roundT (bool, optional) – Round the delays in the legend; defaults to Settings.round_labels.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot().

Returns:

The axis the spectra were drawn into.

Return type:

matplotlib.axes.Axes

pymorgan.oneD.plot.plot_species_spectra(data, Sfit, Taus, TauErr, isFixTau, modelType, ax=None, fig=None, *, detector=0, settings=None, label_style=None, delta_a_units=None, x_axis_unit=None, secondary_axis=None, dualScale=None, normY=False, anisotropy=False, roundT=None, flipColor=False, Abs=None, Em=None, doSmooth=0, printErrors=None, pair_round=None, species_labels=None, show_xlabel=True, show_ylabel=True, **kwargs)[source]#

Plot evolution-/species-associated spectra from a global-analysis fit.

Draws the amplitude spectrum of each component returned by a global fit, one trace per component, labelled with its lifetime and (optionally) the fitted uncertainty. Whether the traces are EAS or SAS depends on modelType: a parallel (sum-of-exponentials) model gives decay-associated spectra, a sequential model gives evolution-associated spectra.

Parameters:
  • data (Dataset1D) – Dataset the fit was performed on; supplies the probe axis. Supplied automatically via Dataset1D.plot_species_spectra.

  • Sfit (numpy.ndarray) – Component amplitude spectra, shape [Npixels x Ncomponents]. Probe pixels that are all-NaN are dropped.

  • Taus (sequence of float) – Fitted lifetime of each component, in the dataset’s time unit.

  • TauErr (sequence of float) – Uncertainty on each lifetime; used only when printErrors is set.

  • isFixTau (sequence of bool) – Per-component flag marking lifetimes that were held fixed in the fit; those are labelled without an uncertainty.

  • modelType (str) – Kinetic model the fit used, which decides the EAS / SAS wording in the legend.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw into; None creates a new figure.

  • fig (matplotlib.figure.Figure, optional) – Figure owning ax; inferred from ax when omitted.

  • settings (Settings, optional) – Settings object to resolve defaults from; defaults to the active one.

  • label_style ({"()", "[]", "/", ""}, optional) – Delimiter convention for the axis labels.

  • delta_a_units (str, optional) – Signal-unit convention for the Y label.

  • x_axis_unit ({"nm", "cm-1", "eV", "THz"}, optional) – Convert the probe axis to this unit for display.

  • secondary_axis (bool, optional) – Add a top axis in the complementary spectral unit.

  • dualScale (bool, optional) – Deprecated alias for secondary_axis.

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

  • anisotropy (bool, default False) – Label the Y axis r(t) and fix its limits.

  • roundT (bool, optional) – Round the lifetimes shown in the legend to two significant figures. Defaults to Settings.round_labels; the remaining digits are capped by Settings.label_digits.

  • flipColor (bool, default False) – Reverse the rainbow colour order.

  • Abs (dict or Spectrum, optional) – Steady-state absorption / emission overlay, as in plot_spectra().

  • Em (dict or Spectrum, optional) – Steady-state absorption / emission overlay, as in plot_spectra().

  • doSmooth (int, default 0) – Box-filter width in points (< 0 overlays the raw trace faintly).

  • printErrors (bool, default True) – Include TauErr in the legend labels.

  • pair_round (bool, default False) – Round each lifetime together with its uncertainty (see pymorgan.helpers.round_to_uncertainty()), so neither is quoted more precisely than the other supports.

  • show_xlabel (bool, default True) – Draw the X / Y axis labels.

  • show_ylabel (bool, default True) – Draw the X / Y axis labels.

  • **kwargs – Forwarded to matplotlib.axes.Axes.plot().

  • detector (int)

Returns:

The axis the spectra were drawn into.

Return type:

matplotlib.axes.Axes

Notes

The Sfit / Taus / TauErr inputs come from a global-analysis fit, which PyMORGAN does not perform - see the companion project PyRATE-TA. This function is the rendering half of that seam and takes plain arrays, so it is independent of how the fit was obtained.