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:
objectA 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 (
Noneuntilbackground_correct()).
- Parameters:
- classmethod from_file(path, data_type=None, **loader_kwargs)[source]#
Load a dataset from
pathusingdata_type(auto-detected when omitted).Extra keyword arguments are forwarded to the loader (e.g.
spectrum,slowmodandanisotropyfor the MESS_TRIR reader). Loaders that take no options simply receive none.
- property Z#
corrected if available, else raw.
- Type:
Most-processed signal
- property has_single_scans: bool#
Whether real per-scan arrays are available in
Zss_R.True when
Zss_Ris a 4-D[Ndelays x Npixels x Ndet x Nscans]array carrying finite data (e.g. a MESS dataset loaded withSettings.load_single_scans); False for a NaN placeholder.
- property history: list[ProcessingStep]#
Ordered list of recorded processing steps applied to this dataset.
- reset_to_raw()[source]#
Restore the raw initial dataset state and clear processing history.
- Return type:
- revert_to_step(step_index)[source]#
Revert the dataset to the state immediately after
step_index(-1= raw).
- load_history_from_dicts(items)[source]#
Restore processing history metadata from serialized dictionaries.
- to_python_script(*, include_plot=True, include_settings=True, plot_kwargs=None)[source]#
Generate a standalone Python script reproducing this dataset’s pipeline.
- 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 (seehas_single_scans).
- copy(deep=True)[source]#
Return a copy of the dataset.
When
deep=True(default), all internal arrays are cloned independently.
- 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
selffor chaining. To keep the original dataset intact, calldataset.copy().crop(...).
- 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
.pdatnnoise 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_glotaran_ascii(path, *, orientation='time', signal_unit='mOD', use_corrected=True, detector=0)[source]#
Export dataset to Glotaran / TIMP
.asciiformat.
- 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
.ncfile.
- noise_array()[source]#
Per-point noise (standard deviation) of the signal, or
None.Noise is taken from
Zstdvwhen it carries non-trivial values (e.g. loaded from a sibling.pdatnfile), otherwise computed as the standard deviation across the scan axis ofZss_Rwhen single-scan data is present. ReturnsNonewhen neither is available.- Returns:
Same shape as
Z([Ndelays x Npixels x Ndetectors]), in the same unit as the signal (mOD), orNonewhen 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/sigmaweights that turn a fit statistic into a true reduced chi-squared. A dataset without a.pdatnsibling and without single scans returnsNone, and a weighted fit of it is refused rather than silently falling back to an unweighted one.
- axis_units(display=False, settings=None)[source]#
Units of the dataset axes: X (probe), Y (delay) and Z (signal).
Returns a
DatasetUnitswhose 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=Truethe spectral axis is reported as it would be plotted, i.e. converted toSettings.x_axis_unitand carrying the10^3factor 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_console(show_all=False)[source]#
Return a plain text, console-friendly summary of the 1-D dataset.
- calibration_status()[source]#
Return a clean, human-readable probe calibration source description.
- Return type:
- 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
selfso calls can be chained.
- 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
ScatterRemovalResultin-place.Copies the cleaned averaged and single-scan arrays, stores the removal metadata, and backs up
Zstdvprior to updating it whenresult.Zstdvis provided.- Parameters:
result (ScatterRemovalResult) – Output produced by
pymorgan.oneD.scatter.compute_scatter_removal().- Returns:
Returns
selfso calls can be chained.- Return type:
- 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 updatedZstdv) 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 asmethod,rank,poly_deg,t0_exclude,scale_broadband,per_scan,update_noise, andtransmittance_space).
- Returns:
Returns
selfso calls can be chained.- Return type:
- clear_scatter_removal()[source]#
Clear applied advanced scatter removal state and restore original
Zstdv.- Returns:
Returns
selfso calls can be chained.- Return type:
- 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
selffor chaining.- Return type:
- 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
selfso calls can be chained.
- 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 withself.delays, they are automatically shifted. Resettingself.Zavg_Cforces background correction to re-evaluate pre-zero delay indices with the updated time axis.
- 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 priorbackground_correct()call: the solvent is subtracted from whichever signal is currently returned byZ.- Parameters:
solvent (Dataset1D) – The solvent (reference) dataset. If it has been background- corrected (
solvent.Zavg_Cis notNone) 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 positivedtshifts 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:
- 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(andZss_Cif 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
pixelsare 1-based pixel numbers (1..Npixels).
- Returns:
self— so calls can be chained.- Return type:
- 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
dtand a global (or per-pixel) amplitude scaling factorsscaleto 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:
- 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
Dataset1Dholding the differentiated signals with updated units metadata (e.g.d(Delta A)/dt).
- 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,
selfmust 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:
- 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,
selfmust 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:
- 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:
- 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.
- 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.
- plot_contour(ax=None, **kwargs)[source]#
Delay-vs-probe contour map.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a new figure. When an axis is given the figure layout is left to the caller, so the panel can be placed in aGridSpeccomposite.**kwargs – Passed to
pymorgan.oneD.plot.plot_contour(), which documents them all. The ones reached for most often areZscale(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_colorbarandshow_xlabel/show_ylabel. Anything not given follows the activeSettings.
- Return type:
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:
ax (mpl_toolkits.mplot3d.axes3d.Axes3D, optional) – 3-D axis to draw into (
projection="3d"required when supplied).**kwargs – Passed to
pymorgan.oneD.plot.plot_noise_3d()(detector,x_axis_unit,label_style, …).
- Return type:
- 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:
ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a new figure.**kwargs – Passed to
pymorgan.oneD.plot.plot_counts().
- Return type:
- plot_surface(ax=None, **kwargs)[source]#
Delay-vs-probe 3D surface with colourmap shading.
- Parameters:
ax (mpl_toolkits.mplot3d.axes3d.Axes3D, optional) – 3-D axis to draw into (
projection="3d"required when supplied).**kwargs – Passed to
pymorgan.oneD.plot.plot_surface(); see there for the full list (rstride/cstride,elev/azim,Yscale,cmap_ID, …).
- Return type:
- 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;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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) andshow_xlabel/show_ylabel.
- Return type:
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:
ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.**kwargs – Passed to
pymorgan.oneD.plot.plot_background()(doSmooth,normY,colour,title,x_axis_unit, …).
- Return type:
- Raises:
ValueError – If no background has been computed; run
background_correct()first (do_correct=Falsestores 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;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.**kwargs – Passed to
pymorgan.oneD.plot.plot_kinetics(). Commonly used:plotStyle(format string, e.g."-"),Xscale,normY,lw/msandshow_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:
plot_wavelengths (sequence of float) – Probe positions to cut at, in the native probe unit.
ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.**kwargs – Passed to
pymorgan.oneD.plot.plot_scan_kinetics(); most oftenbinsize(scans averaged per trace),XscaleandnormY.
- 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 (seehas_single_scans).- Parameters:
plot_delays (sequence of float) – Delays to cut at, in this dataset’s time unit.
ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.**kwargs – Passed to
pymorgan.oneD.plot.plot_scan_spectra(); most oftenbinsize,doSmoothandnormY.
- Return type:
- 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;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.**kwargs – Passed to
pymorgan.oneD.plot.plot_species_spectra()(printErrors,normY,doSmooth,Abs/Em, …).
- Return type:
Notes
The
Sfit/Taus/TauErrinputs 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_step(**kwargs)[source]#
Gaussian(+derivatives)+erf-step fit, restricted to an early-time window.
- fit_chirp_wavelet(**kwargs)[source]#
Wavelet-based edge-detection fit at every probe pixel + Cauchy dispersion fit.
- fit_chirp_manual(points, **kwargs)[source]#
Cauchy dispersion fit to manually-picked
(wavelength, delay)points.
- 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
ChirpFitto 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).
- pymorgan.oneD.dataset.load_1D(path, data_type=None, **loader_kwargs)[source]#
Convenience wrapper for
Dataset1D.from_file().When
data_typeisNone(default) or"auto",pymorgan.detect_format()infers the format automatically (falling back to"PDAT"). Extra keyword arguments are forwarded to the selected loader.
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
fnunder one or more data-type names.
- pymorgan.oneD.registry.get_loader(name)[source]#
Return the loader registered for
nameor raiseKeyError.
- pymorgan.oneD.registry.available_loaders()[source]#
Return the sorted list of registered data-type names.
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, |
delays |
Delay axis, |
probe |
Spectral (probe) axis, |
Units |
Unit dictionary (see |
Nscans |
Number of scans, or |
Zss_R |
Single-scan signal, |
Zstdv |
Standard deviation of the signal, |
New instrument formats are added by decorating a reader with
register_loader().
- pymorgan.oneD.load.get_loader(name)[source]#
Return the loader registered for
nameor raiseKeyError.
- pymorgan.oneD.load.available_loaders()[source]#
Return the sorted list of registered data-type names.
- pymorgan.oneD.load.register_dataset_glob(name, pattern)[source]#
Declare
nameas a file-based format whose datasets matchpattern.
- pymorgan.oneD.load.register_dataset_detector(*names)[source]#
Register a
folder -> boolpredicate marking a directory-based dataset.
- pymorgan.oneD.load.register_dataset_describer(*names)[source]#
Register a
folder -> dictdescribing per-dataset selection options.The dict is advisory metadata the GUI uses to configure selectors (e.g.
{"n_spectra": int, "n_slowmod": int}). ReturnsNonewhen no describer is registered for the data type.
- pymorgan.oneD.load.register_dataset_file_filter(*names)[source]#
Register a
file_path -> boolpredicate filtering dataset browser files.
- pymorgan.oneD.load.is_dataset_file_status(name, file_path)[source]#
Whether
file_pathis a candidate/valid dataset file for typename.Returns
(is_candidate, is_valid).
- pymorgan.oneD.load.is_dataset_file(name, file_path)[source]#
Whether
file_pathis an averaged dataset file for typename.
- pymorgan.oneD.load.dataset_glob(name)[source]#
Return the file glob for a file-based format, or
None.
- pymorgan.oneD.load.is_directory_format(name)[source]#
Whether
namestores each dataset as a directory (has a detector).
- pymorgan.oneD.load.is_dataset_dir_status(name, folder)[source]#
Whether
folderis a candidate/valid dataset of typename.Returns
(is_candidate, is_valid).
- pymorgan.oneD.load.is_dataset_dir(name, folder)[source]#
Whether
folderis a loadable dataset of typename.
- pymorgan.oneD.load.describe_dataset(name, folder)[source]#
Return per-dataset selection metadata, or
Noneif unavailable.
- pymorgan.oneD.load.read_PDAT(datafilename)[source]#
Read a PyMORGAN
.pdatfile (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.
- 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
.pdatnfile.
- 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.Dataset1Dto.pdat(and optional.pdatn) files.If the dataset has multiple detectors and
detectoris None, exports one.pdatper detector with a_DET{i}filename suffix.Returns the list of exported Paths.
- pymorgan.oneD.load.save_1D_hdf5(dataset, path)[source]#
Save a
pymorgan.oneD.Dataset1Dinstance to a FAIR/NeXus HDF5 archive.
- pymorgan.oneD.load.read_1D_hdf5(path)[source]#
Read a Dataset1D from an HDF5 file written by save_1D_hdf5.
- pymorgan.oneD.load.load_1D_hdf5(path)[source]#
Load an HDF5 archive into a fully restored
pymorgan.oneD.Dataset1D.
- 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
- 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
- pymorgan.oneD.load.read_UoS_IRpp(path, *, load_single_scans=None)[source]#
Read a University of Sheffield TRIR dataset folder or file (.2D / .DT).
- 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.
- pymorgan.oneD.load.mess_calibration_status(folder)[source]#
One-line probe-calibration status for the status bar after a MESS load.
- Return type:
- 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.
- 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).
- 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).
- 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
- pymorgan.oneD.load.find_pymess_calibrated_probe_csv(path, n_pix)[source]#
Locate a matching
CalibratedProbe.csvfor 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), orNoneif no matching file exists.
- pymorgan.oneD.load.embed_calibrated_probe_h5(h5_path, csv_path=None, *, backup_original=True)[source]#
Permanently embed a
CalibratedProbe.csvprobe axis inside an.h5dataset 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.
- 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).
- 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)
- 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-branges, e.g."1-4 6 9"or"1-3, 5". Out-of-range or malformed tokens raiseValueError. Returns the unique indices in ascending order.
- 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>/tempand combines the selectedscan_indices(0-based). Whennoise_weighted=True(default), combines scans by inverse-variance weighting (weight1/noise**2), matching the acquisition’s averaged data: selecting every scan reproduces the main-directory_signal/_signal_noisefiles. WhenFalse, 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.
- pymorgan.oneD.load.parse_ufs(file_path)[source]#
Parse a Surface Xplorer
.ufsbinary file into(delays, probe, sig_mod, meta).Supports
Version2(64-bit big-endian IEEE floats>f8) andVersion1(32-bit big-endian floats>f4). ConvertsDA/ODsignal values tomOD(* 1000.0) unlessz_unitalready indicatesmOD, sorts descending probe axes ascending, tracks interpolated padding quality, and includes a fallback for third-partycsv -> ufsconversion outputs.
- pymorgan.oneD.load.parse_helios_csv(file_path)[source]#
Parse a single Helios CSV file into delays, probe, and signal (in mOD, NaN-interpolated).
- pymorgan.oneD.load.read_Helios_UFS(datafilename, dataset_name=None)[source]#
Read a Surface Xplorer
.ufsdataset (averaged file and sibling_scan*.ufs).
- pymorgan.oneD.load.read_Helios_TA(datafilename, dataset_name=None)[source]#
Read Helios transient absorption dataset (
.csvor.ufsaveraged file and single scans).
- pymorgan.oneD.load.read_Exported_TXT(datafilename)[source]#
Read an Exported TXT transient absorption dataset (TA.txt, time.txt, wavelength.txt).
- pymorgan.oneD.load.parse_quickcontrol_info(filepath)[source]#
Parse a PhaseTech QuickControl
.infotab-delimited header file.
- pymorgan.oneD.load.classify_quickcontrol_info(filepath)[source]#
Classify a QuickControl
.infofile into(kind, has_scans).
- 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) / 3is placed at channel 0 so it is active by default, followed byParallel(channel 1) andPerpendicular(channel 2).- Parameters:
- Returns:
LoaderResult –
(Zavg_R, delays, probe, Units, Nscans, Zss_R, Zstdv)- Return type:
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 ofdo_correct. Withdo_correct=Falsethe 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(positivedtmeans 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 positivedtshifts 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
Npixelsapplies 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
dtand a global (or per-pixel) amplitude scaling factorsscalesuch that the corrected signalZ_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
pixelsfrom 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
pixelsare 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 3DZ) or[Ndelays × Ndet × Nscans](for 4DZ).
- 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:
- 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
Dataset1Dinstances (or 2D arrays), or a single multi-detectorDataset1Dwheredetector_paranddetector_perpspecify 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
perpendicularis None,parallelmust 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 anisotropyDataset1D.- 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]
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, viascipy.optimize.least_squares()). A second pass re-fits every pixel from smoothed initial guesses (an intermediate dispersion fit fort0, moving-median smoothing forFWHM/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 (seepymorgan.gui.picker.ContourPickerinaxis="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:
objectResult of a chirp/dispersion fit.
coeffsare the Cauchy dispersion coefficients (seecauchy_t0()).Pfitholds the per-pixel (or per-point, formode="manual") fit results: 8 columns[t0, FWHM, G0_amp, G1_amp, G2_amp, offset, tau_exp, exp_amp]formode="automatic"; 7 columns[t0, FWHM, G0_amp, G1_amp, G2_amp, offset, step_amp]formode="step"withuse_exp=False, or 9 columns (appending[tau_exp, exp_amp]) whenuse_exp=True–FWHMis the genuine full width at half maximum (ps) of the Gaussian IRF in both modes, no further conversion needed – or a single[t0]column formode="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)
n_cauchy_terms (int)
lambda_ref (float)
fit_pixels (ndarray)
Dfit (ndarray | None)
mean_irf_fs (float)
detector (int)
use_exp (bool)
do_2nd_pass (bool)
smooth_window (int)
t_min (float)
t_max (float)
n_skipped (int)
omega_w (float)
gamma_w (float)
source (str | None)
chirp_file (str | 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 forfitPixelsto maintain compatibility with downstream analysis scripts. Sincesavematcannot embed a Python callable,chirpFun_strcarries the equivalent anonymous-function source, andusageprovides instructions on how to evaluate the curve.- Return type:
- 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_reforn_cauchy_terms. These are inferred automatically:lambda_refis reconstructed frommean(fitWL)– standard dispersion analysis uses this value as the reference wavelength for the Cauchy dispersion formula, and it can be verified from thescaleVecclosure embedded in the saved function handle.n_cauchy_termsis inferred fromlen(Cfit).modeis guessed from the column count ofPfit: 8 →"automatic", 7 or 9 →"step", anything else →"manual".
- 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). Thelambda_refprefactors render every coefficient dimensionless and of comparable magnitude.
- 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 tomax(100, 10 * ptp(t0))according to the overall slope oft0(lambda).
- 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_maskselects which Gaussian-IRF derivative terms to include (1st, 2nd);use_expadds the erf-broadened exponential (coherent artefact / early dynamics) term. Withdo_2nd_pass(default), a second VARPRO pass re-fits every pixel from an intermediate dispersion fit (fort0) and moving-median smoothing (forFWHM/tau_exp). Pixels with non-finite or all-zero data are skipped silently (NaN inPfit).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 asdelays - t0so the IRF stays centred regardless of dispersion); it is not needed for headless/scripted use.
- 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(). Whenuse_exp=True(defaultFalse), an erf-broadened exponential coherent-artefact term is added, extendingPfitfrom 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)(seefit_chirp_automatic()).
- 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.pointsis typically produced by interactively clicking the embedded contour map (seepymorgan.gui.picker.ContourPicker,axis="xy"). At leastn_cauchy_termspoints are required.
- 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(oroptimize_wavelet=True), the wavelet parametersomega_wandgamma_ware refined iteratively before the main per-pixel scan. A Nelder-Mead simplex optimiser minimises the RMS of thet0residuals 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 returnedChirpFitobject (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:
detector (int)
t_min (float)
t_max (float)
omega_w (float)
gamma_w (float)
n_cauchy_terms (int)
cauchy_lambda_ref (float | None)
do_2nd_pass (bool)
smooth_window (int)
optimise_wavelet (bool)
optimize_wavelet (bool | None)
opt_max_iter (int)
opt_progress_callback (Callable[[int, str, float], None] | None)
preview_callback (Callable[[float, ndarray, ndarray, ndarray, float], None] | None)
- Return type:
- 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.
- pymorgan.oneD.chirp.save_chirp_fit(fit, path, n_detectors=1)[source]#
Save
fittopathas a.h5/.hdf5,.json, or.matfile based on path suffix.
- pymorgan.oneD.chirp.load_chirp_fit(path)[source]#
Load a
ChirpFitpreviously written bysave_chirp_fit().Also accepts legacy MAT chirp correction files. The legacy MAT format stores
Cfit,fitWL,fitPixels,Pfitand achirpFunfunction-handle object. The function handle cannot be evaluated by scipy, but it is not needed: the Cauchy dispersion curve is fully reconstructed fromCfitand the inferred reference wavelength (seeChirpFit.from_dict()).- Return type:
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:
objectConfiguration 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_maxif 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. WhenNoneor non-positive, defaults tomax(3 * step, 0.5 * span).taper_width (float or None, optional) – Raised-cosine taper width extending beyond
[p_min, p_max]. WhenNoneor non-positive, defaults tomin(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). WhenNone, inherits the globalrankargument.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:
- 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:
objectOutputs and diagnostics from
compute_scatter_removal().- Variables:
Zavg_C (np.ndarray) – Scatter- and background-corrected averaged signal matching
Zavg_Rshape.Zss_C (np.ndarray or None) – Corrected single-scan tensor
[Ndelays x Npixels x Ndet x Nscans]whenper_scan=Trueand single scans are available, elseNone.Zstdv (np.ndarray or None) – Recomputed inter-scan standard deviation across cleaned single scans when
update_noise=Trueand multiple scans exist, elseNone.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_Cisolating 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:
- bands: list[ScatterBand]#
- 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:
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).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 sigmaadded 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 viadetect_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.rankoverrides 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_svdmodes so coherent artifacts aroundt0are 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
Zstdvacross the cleaned single scans whenper_scanis active andNscans > 1.transmittance_space (bool, default False) – Convert ΔA to transmittance modulation
10^(-ΔA/scale) - 1before decomposition (for very strong / optically nonlinear scatter).mask_saturated (bool, default False) – Mask raw pixels inside enabled scatter cores exceeding
saturation_thresholdtoNaN.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
Noneprocesses all channels and computes diagnostics for detector 0).
- Return type:
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:
objectContainer 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:
- kind: Literal['wavelength', 'timescale']#
- 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 acrossblend_window. -"cutover": Direct concatenation atcutover_wlwithout 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:
- 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_scatteris 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:
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:
objectContainer 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:
- recompose(k=None)[source]#
Recompose the data matrix using the first
kcomponents.- 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.
- to_dataset(k=None, name=None, units=None)[source]#
Construct a new
Dataset1Dcontaining the recomposed data.
- 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)whereMis the number of delays andNis 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:
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.
Nonecreates a new figure sized fromSettings.contour_figsizeand lays it out withtight_layout. When an axis is supplied the figure geometry is left untouched, which is what makes the plotter usable inside aGridSpeccomposite (seeexamples/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 toSettings.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) –
Trueoverlays black contour lines on the filled map;Falsecolours 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
ShowLinesis set. The filled background always uses the raw data. Values <= 1 disable smoothing.filled (bool, default True) – Draw the filled
contourfbackground.Falsegives 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 whenNlevelsis 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 toSettings.cmap.anisotropy (bool, default False) – Treat
Zas 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
Zmaxis 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
pcolormeshinstead of contour sets and skip the line overlay. Much faster for large maps and for interactive use. Defaults toSettings.quick_plots.show_xlabel (bool, default True) – Draw the X / Y axis labels. Set to
Falseon 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
Falseon inner panels of a composite figure that share an axis with a neighbour.show_colorbar (bool, default True) – Attach the divider colorbar. Set
Falsewhen several panels share one externally drawn colorbar.show_colorbar_label (bool, default True) – Draw the unit label on the colorbar (ignored when
show_colorbarisFalse).
- Returns:
The axis the map was drawn into.
- Return type:
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_contourdoes.axis_nameis"x","y"or"z";scaleis"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 –
Yscaledefaults toSettings.time_axis_scaleand the tick labels toSettings.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.
Nonecreates one; a supplied axis must already haveprojection="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
Trueby default.show_ylabel (bool) – Element visibility, all
Trueby default.show_colorbar (bool) – Element visibility, all
Trueby default.show_colorbar_label (bool) – Element visibility, all
Trueby 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:
- 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:
- Raises:
ValueError – If the dataset carries neither a noise array nor single-scan data.
See also
pymorgan.oneD.Dataset1D.noise_arraythe 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 (HonouringSettings.x_axis_unitandSettings.secondary_axis).
- 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:
- pymorgan.oneD.plot.legend_placement(settings=None)[source]#
loc(and anchor) for a cut legend, as**kwargsforax.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:
- 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;
Nonecreates a figure sized fromSettings.spectra_figsize.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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 aSpectrum. Drawn inverted and normalised on a twin axis whose zero is aligned with the transient one.Emis multiplied byX**4first (wavelength-to-wavenumber Jacobian for a fluorescence spectrum).Em (dict or Spectrum, optional) – Steady-state absorption / emission overlay, as
{"X": ..., "Y": ...}or aSpectrum. Drawn inverted and normalised on a twin axis whose zero is aligned with the transient one.Emis multiplied byX**4first (wavelength-to-wavenumber Jacobian for a fluorescence spectrum).doSmooth (int, default 0) – Box-filter width in points.
> 0plots the smoothed trace only;< 0plots 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:
Notes
Detector gaps are masked, so traces are broken rather than interpolated across them. When
Settings.error_shadingis 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 Matplotliblocputs 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 ondata(bkg_avg, populated byDataset1D.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;
Nonecreates a figure sized fromSettings.spectra_figsize.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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 (
< 0overlays 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:
- Raises:
ValueError – If no background has been computed; call
Dataset1D.background_correct()first (do_correct=Falsestores 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_unitif supplied. Each is snapped to the nearest pixel and duplicates are dropped.ax (matplotlib.axes.Axes, optional) – Axis to draw into;
Nonecreates a figure sized fromSettings.kinetics_figsize.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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;
< 0also 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().markersizeandlinewidthdefault toSettings.kinetics_marker_sizeandSettings.kinetics_line_widthunless given explicitly (ms/lwalso 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 ofplot_wavelengthsafter snapping. Useful for exporting or fitting the same data that was plotted.
Notes
When
Settings.error_shadingis on and the dataset carries a noise array, each trace is drawn with a shaded +/-1 sigma band. The legend is placed bySettings.legend_location, beside the axis by default.The returned
Yis 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_scansenabled (checkDataset1D.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;
Nonecreates a figure sized fromSettings.kinetics_figsize.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen omitted.detector (int, default 0) – Detector index for multi-detector datasets.
binsize (int, default 1) – Number of consecutive scans averaged into each trace.
1plots 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
binsizescans, 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.doSmoothmatchesplot_spectra()(>0 smoothed, <0 smoothed + faint original).Requires single-scan data (see
Dataset1D.has_single_scans); the spectral counterpart ofplot_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;
Nonecreates a figure sized fromSettings.spectra_figsize.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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 (
< 0overlays 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:
- 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
printErrorsis 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;
Nonecreates a new figure.fig (matplotlib.figure.Figure, optional) – Figure owning
ax; inferred fromaxwhen 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 bySettings.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 (
< 0overlays the raw trace faintly).printErrors (bool, default True) – Include
TauErrin 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:
Notes
The
Sfit/Taus/TauErrinputs 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.