"""The :class:`Dataset1D` pipeline object.
``Dataset1D`` ties the 1-D pipeline together: **load** (:mod:`.load`),
**process** (:mod:`.process`), **plot** (:mod:`.plot`) and **analyse**
(:mod:`.analyse`). It holds the raw arrays plus provenance and resolves
presentation defaults from the active :class:`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.
"""
from __future__ import annotations
import html
from collections.abc import Sequence
from os import PathLike
from pathlib import Path
from typing import Any, Literal
import numpy as np
from ..provenance import HistoryManager, ProcessingStep, generate_python_script
from ..settings import DeltaAUnits, Settings, get_settings
from . import process
from .load import get_loader
# Plain-text probe-axis units (the QPlainTextEdit info box renders no LaTeX).
_PLAIN_PROBE_UNIT = {"Wavenumber": "cm\u207b\u00b9", "Wavelength": "nm", "Energy": "eV"}
def _ltx_to_text(s: str) -> str:
"""Best-effort conversion of a LaTeX unit string to plain Unicode text."""
return (
s.replace("$", "")
.replace(r"\times 10^{3}", "\u00d710\u00b3")
.replace("^{-1}", "\u207b\u00b9")
.replace("{", "")
.replace("}", "")
.strip()
)
def _format_1d_delay_val(t: float, unit_in: str) -> str:
if not np.isfinite(t):
return "n/a"
try:
from .. import helpers as hlp
val, u_out = hlp.ConvertTimeUnits(float(t), unit_in)
u_clean = u_out.replace(r"$\mu$s", "μs")
val_str = f"{val:g}"
return f"{val_str} {u_clean}"
except Exception:
val_str = f"{t:g}"
return f"{val_str} {unit_in}"
def _format_1d_delay_info(delays, unit_in: str, html: bool = False) -> str:
arr = np.asarray(delays, dtype=float)
n = int(arr.size)
if n == 0:
range_str = "[n/a, n/a]"
else:
dmin = float(np.nanmin(arr))
dmax = float(np.nanmax(arr))
min_str = _format_1d_delay_val(dmin, unit_in)
max_str = _format_1d_delay_val(dmax, unit_in)
range_str = f"[{min_str}, {max_str}]"
prefix = "<b>Delays:</b>" if html else "Delays:"
return f"{prefix} {n}, range: {range_str}"
[docs]
class Dataset1D:
"""A one-dimensional time-resolved dataset and its processing pipeline.
Attributes
----------
Zavg_R:
Averaged signal, ``[Ndelays x Npixels x Ndetectors]``.
delays, probe:
Delay and probe (spectral) axes.
units:
Unit dictionary (see ``helpers.units2dic``).
nscans, Zss_R, Zstdv:
Scan count, single-scan signal and standard deviation.
Zavg_C:
Background-corrected signal (``None`` until :meth:`background_correct`).
"""
def __init__(
self,
Zavg_R,
delays,
probe,
units: dict,
nscans=np.nan,
Zss_R=None,
Zstdv=None,
*,
source: str | None = None,
data_type: str | None = None,
scan_ids=None,
counts=None,
):
self.Zavg_R = np.asarray(Zavg_R)
if self.Zavg_R.ndim == 2:
self.Zavg_R = self.Zavg_R[:, :, np.newaxis]
self.delays = np.asarray(delays)
self.probe = np.asarray(probe)
default_u = {
"unitsT_lbl": "Delay",
"unitsT_ltx": "ps",
"unitsL_lbl": "Wavenumber",
"unitsL_ltx": r"$\mathrm{cm^{-1}}$",
"unitsZ_lbl": r"$\Delta$A",
"unitsZ_ltx": "mOD",
}
self.units = {**default_u, **(units or {})}
self.nscans = nscans
self.Zss_R = Zss_R
if Zstdv is not None:
zstdv_arr = np.asarray(Zstdv)
if zstdv_arr.ndim == 2:
zstdv_arr = zstdv_arr[:, :, np.newaxis]
self.Zstdv = zstdv_arr
else:
self.Zstdv = None
self.source = source
self.data_type = data_type
self.scan_ids = scan_ids
self.counts = counts if counts is not None else self.units.get("counts")
self.cal_source = self.units.get("cal_source")
self.cal_level = self.units.get("cal_level")
if self.Zss_R is not None and getattr(self.Zss_R, "ndim", 0) == 4:
self.total_scans = int(self.Zss_R.shape[-1])
elif np.isfinite(nscans) and int(nscans) >= 1:
self.total_scans = int(nscans)
else:
self.total_scans = None
self.Zavg_C = None
self.Zss_C = None
self.bkg_avg = None
self.bkg_ss = None
self.chirp_fit = None
self.mask_ranges = None
self._scatter_removal_params = None
self._scatter_removal_result = None
self._orig_Zstdv = None
self._bkg_params: dict[str, Any] | None = None
self._loader_kwargs: dict[str, Any] = {}
self._history = HistoryManager()
@property
def Units(self) -> dict:
"""Alias for :attr:`units` for backward compatibility with legacy specs."""
return self.units
@Units.setter
def Units(self, value: dict) -> None:
self.units = value
# ----------------------------------------------------------------- #
# Load (construction) #
# ----------------------------------------------------------------- #
[docs]
@classmethod
def from_file(
cls, path: str | PathLike, data_type: str | None = None, **loader_kwargs
) -> Dataset1D:
"""Load a dataset from ``path`` using ``data_type`` (auto-detected when omitted).
Extra keyword arguments are forwarded to the loader (e.g. ``spectrum``,
``slowmod`` and ``anisotropy`` for the MESS_TRIR reader). Loaders that
take no options simply receive none.
"""
explicit_type = data_type is not None and str(data_type).strip().lower() != "auto"
if not explicit_type:
from ..detect import detect_format
match = detect_format(path)
if match is not None and match.dimension == "1D":
data_type = match.data_type
path = match.resolved_path
else:
data_type = "PDAT"
assert data_type is not None
loader = None
if not (data_type == "HDF5" and not loader_kwargs):
loader = get_loader(data_type)
try:
if data_type == "HDF5" and not loader_kwargs:
import h5py
p = Path(path)
if p.is_file() and h5py.is_hdf5(p):
with h5py.File(p, "r") as f:
if "delays" in f and "Zavg_R" in f:
from .load import load_1D_hdf5
ds = load_1D_hdf5(p)
if ds.data_type and "original_data_type" not in ds.units:
ds.units["original_data_type"] = ds.data_type
ds.data_type = data_type
ds.source = str(path)
return ds
loader = get_loader(data_type)
assert loader is not None
res = loader(str(path), **loader_kwargs)
except (KeyError, FileNotFoundError):
raise
except Exception as exc:
if explicit_type:
from ..detect import detect_format
match = detect_format(path)
if match is not None and (
match.dimension != "1D" or match.data_type != data_type
):
raise ValueError(
f"{exc} (Detected format for {Path(path).name!r}: {match.dimension} "
f"{match.data_type!r}; try data_type={match.data_type!r} or omit "
f"data_type for auto-detection.)"
) from exc
raise
counts = None
if len(res) >= 9:
Zavg_R, delays, probe, units, nscans, Zss_R, Zstdv, scan_ids, counts = res[:9]
elif len(res) >= 8:
Zavg_R, delays, probe, units, nscans, Zss_R, Zstdv, scan_ids = res[:8]
else:
Zavg_R, delays, probe, units, nscans, Zss_R, Zstdv = res
scan_ids = None
units = dict(units or {})
if counts is not None:
units["counts"] = counts
if scan_ids is None and "scan_ids" in units:
scan_ids = units["scan_ids"]
if "sample_info" not in units:
try:
from .load import _find_mess_sample_info_file, parse_mess_sample_info
info_file = _find_mess_sample_info_file(path)
if info_file is not None:
info_str = parse_mess_sample_info(info_file)
if info_str:
units["sample_info"] = info_str
except Exception:
pass
ds = cls(
Zavg_R,
delays,
probe,
units,
nscans,
Zss_R,
Zstdv,
source=str(path),
data_type=data_type,
scan_ids=scan_ids,
counts=counts,
)
ds._loader_kwargs = dict(loader_kwargs)
return ds
# ----------------------------------------------------------------- #
# Properties #
# ----------------------------------------------------------------- #
@property
def Z(self):
"""Most-processed signal: corrected if available, else raw."""
return self.Zavg_R if self.Zavg_C is None else self.Zavg_C
@property
def n_detectors(self) -> int:
"""Number of detector channels in the signal."""
return self.Zavg_R.shape[2] if self.Zavg_R.ndim == 3 else 1
@property
def is_corrected(self) -> bool:
"""Whether a background correction has been applied."""
return self.Zavg_C is not None
@property
def has_single_scans(self) -> bool:
"""Whether real per-scan arrays are available in ``Zss_R``.
True when ``Zss_R`` is a 4-D ``[Ndelays x Npixels x Ndet x Nscans]``
array carrying finite data (e.g. a MESS dataset loaded with
``Settings.load_single_scans``); False for a NaN placeholder.
"""
z = self.Zss_R
if z is None:
return False
z = np.asarray(z)
return z.ndim == 4 and z.shape[3] >= 1 and bool(np.any(np.isfinite(z)))
# ----------------------------------------------------------------- #
# Provenance & Undo/Redo #
# ----------------------------------------------------------------- #
@property
def history(self) -> list[ProcessingStep]:
"""Ordered list of recorded processing steps applied to this dataset."""
return self._history.steps
@property
def can_undo(self) -> bool:
"""Whether an undo snapshot is available."""
return self._history.can_undo
@property
def can_redo(self) -> bool:
"""Whether a redo snapshot is available."""
return self._history.can_redo
[docs]
def undo(self) -> bool:
"""Undo the most recent processing step (or coalesced tweak)."""
return self._history.undo(self)
[docs]
def redo(self) -> bool:
"""Redo the most recently undone processing step."""
return self._history.redo(self)
[docs]
def reset_to_raw(self) -> bool:
"""Restore the raw initial dataset state and clear processing history."""
return self._history.reset_to_raw(self)
[docs]
def revert_to_step(self, step_index: int) -> bool:
"""Revert the dataset to the state immediately after ``step_index`` (``-1`` = raw)."""
return self._history.revert_to(self, step_index)
[docs]
def history_to_dicts(self) -> list[dict[str, Any]]:
"""Serialize processing history to JSON/TOML-friendly dictionaries."""
return self._history.to_dicts()
[docs]
def load_history_from_dicts(self, items: Sequence[dict[str, Any]]) -> None:
"""Restore processing history metadata from serialized dictionaries."""
self._history.load_dicts(items)
[docs]
def to_python_script(
self,
*,
include_plot: bool = True,
include_settings: bool = True,
plot_kwargs: dict | None = None,
) -> str:
"""Generate a standalone Python script reproducing this dataset's pipeline."""
return generate_python_script(
self,
include_plot=include_plot,
include_settings=include_settings,
plot_kwargs=plot_kwargs,
)
[docs]
def scan_signal(self, detector: int = 0) -> np.ndarray:
"""Return the single-scan signal ``[Ndelays x Npixels x Nscans]``.
Uses the background-corrected single scans (``Zss_C``) when available,
otherwise the raw single scans (``Zss_R``). Raises if no per-scan data
is present (see :attr:`has_single_scans`).
"""
if not self.has_single_scans:
raise ValueError(
"No single-scan data available. Load the dataset with "
"Settings.load_single_scans enabled."
)
z = None
if self.Zss_C is not None:
zc = np.asarray(self.Zss_C, dtype=float)
if zc.ndim == 4 and zc.shape[3] >= 1 and np.any(np.isfinite(zc)):
z = zc
if z is None:
z = np.asarray(self.Zss_R, dtype=float)
return z[:, :, detector, :]
def __repr__(self) -> str: # pragma: no cover - cosmetic
return (
f"Dataset1D(data_type={self.data_type!r}, "
f"delays={self.delays.shape}, probe={self.probe.shape}, "
f"detectors={self.n_detectors}, corrected={self.is_corrected})"
)
[docs]
def copy(self, deep: bool = True) -> Dataset1D:
"""Return a copy of the dataset.
When ``deep=True`` (default), all internal arrays are cloned independently.
"""
import copy as _copy
def _dup(arr):
if arr is None:
return None
return np.copy(arr) if deep else arr
new_ds = Dataset1D(
_dup(self.Zavg_R),
_dup(self.delays),
_dup(self.probe),
_copy.deepcopy(self.units) if deep else self.units.copy(),
nscans=self.nscans,
Zss_R=_dup(self.Zss_R),
Zstdv=_dup(self.Zstdv),
source=self.source,
data_type=self.data_type,
scan_ids=_copy.deepcopy(self.scan_ids) if deep else self.scan_ids,
counts=_dup(self.counts),
)
new_ds.Zavg_C = _dup(self.Zavg_C)
new_ds.Zss_C = _dup(self.Zss_C)
new_ds.bkg_avg = _dup(self.bkg_avg)
new_ds.bkg_ss = _dup(self.bkg_ss)
mask_r = getattr(self, "mask_ranges", None)
new_ds.mask_ranges = _copy.deepcopy(mask_r) if deep else mask_r
new_ds.cal_level = getattr(self, "cal_level", None)
new_ds.cal_source = getattr(self, "cal_source", None)
sc_params = getattr(self, "_scatter_removal_params", None)
new_ds._scatter_removal_params = _copy.deepcopy(sc_params) if deep else sc_params
sc_res = getattr(self, "_scatter_removal_result", None)
new_ds._scatter_removal_result = _copy.deepcopy(sc_res) if deep else sc_res
new_ds._orig_Zstdv = _dup(getattr(self, "_orig_Zstdv", None))
new_ds.chirp_fit = _copy.deepcopy(self.chirp_fit) if deep else self.chirp_fit
bkg_p = getattr(self, "_bkg_params", None)
new_ds._bkg_params = _copy.deepcopy(bkg_p) if deep else bkg_p
lk = getattr(self, "_loader_kwargs", None)
new_ds._loader_kwargs = _copy.deepcopy(lk) if (deep and lk is not None) else dict(lk or {})
new_ds._solvent_dataset = getattr(self, "_solvent_dataset", None)
new_ds._solvent_dt = _dup(getattr(self, "_solvent_dt", None)) if isinstance(getattr(self, "_solvent_dt", None), np.ndarray) else getattr(self, "_solvent_dt", None)
new_ds._solvent_scale = _dup(getattr(self, "_solvent_scale", None)) if isinstance(getattr(self, "_solvent_scale", None), np.ndarray) else getattr(self, "_solvent_scale", None)
new_ds._shockwave_pixels = _dup(getattr(self, "_shockwave_pixels", None)) if isinstance(getattr(self, "_shockwave_pixels", None), np.ndarray) else getattr(self, "_shockwave_pixels", None)
new_ds._shockwave_trace = _dup(getattr(self, "_shockwave_trace", None)) if isinstance(getattr(self, "_shockwave_trace", None), np.ndarray) else getattr(self, "_shockwave_trace", None)
hist = getattr(self, "_history", None)
new_ds._history = hist.copy(deep=deep) if hist is not None else HistoryManager()
return new_ds
[docs]
def crop(
self,
tmin: float | None = None,
tmax: float | None = None,
probe_min: float | None = None,
probe_max: float | None = None,
) -> Dataset1D:
"""Crop the dataset along the delay and/or probe axes.
Mutates the dataset in-place and returns ``self`` for chaining.
To keep the original dataset intact, call ``dataset.copy().crop(...)``.
"""
if tmin is None and tmax is None and probe_min is None and probe_max is None:
return self
if tmin is not None and tmax is not None and float(tmin) > float(tmax):
tmin, tmax = tmax, tmin
if probe_min is not None and probe_max is not None and float(probe_min) > float(probe_max):
probe_min, probe_max = probe_max, probe_min
def _do():
if tmin is not None or tmax is not None:
old_nt = len(self.delays)
t_low = -np.inf if tmin is None else float(tmin)
t_high = np.inf if tmax is None else float(tmax)
t_mask = (self.delays >= t_low) & (self.delays <= t_high)
if not np.any(t_mask):
raise ValueError(f"No delay points fall in range [{t_low}, {t_high}]")
self.delays = self.delays[t_mask]
if self.Zavg_R is not None:
self.Zavg_R = self.Zavg_R[t_mask]
if self.Zavg_C is not None:
self.Zavg_C = self.Zavg_C[t_mask]
if self.Zss_R is not None:
self.Zss_R = self.Zss_R[t_mask]
if self.Zss_C is not None:
self.Zss_C = self.Zss_C[t_mask]
if self.Zstdv is not None:
self.Zstdv = self.Zstdv[t_mask]
if (
getattr(self, "_orig_Zstdv", None) is not None
and self._orig_Zstdv.shape[0] == old_nt
):
self._orig_Zstdv = self._orig_Zstdv[t_mask]
if (
isinstance(self.counts, np.ndarray)
and self.counts.ndim >= 1
and self.counts.shape[0] == old_nt
):
self.counts = self.counts[t_mask]
if (
isinstance(self.units, dict)
and isinstance(self.units.get("rms"), np.ndarray)
and self.units["rms"].shape[0] == old_nt
):
self.units = dict(self.units)
self.units["rms"] = self.units["rms"][t_mask]
if probe_min is not None or probe_max is not None:
old_np = len(self.probe)
p_low = -np.inf if probe_min is None else float(probe_min)
p_high = np.inf if probe_max is None else float(probe_max)
p_probe = self.probe[:, 0] if self.probe.ndim > 1 else self.probe
p_mask = (p_probe >= p_low) & (p_probe <= p_high)
if not np.any(p_mask):
raise ValueError(f"No probe points fall in range [{p_low}, {p_high}]")
self.probe = self.probe[p_mask] if self.probe.ndim == 1 else self.probe[p_mask, :]
if self.Zavg_R is not None:
self.Zavg_R = (
self.Zavg_R[:, p_mask] if self.Zavg_R.ndim == 2 else self.Zavg_R[:, p_mask, :]
)
if self.Zavg_C is not None:
self.Zavg_C = (
self.Zavg_C[:, p_mask] if self.Zavg_C.ndim == 2 else self.Zavg_C[:, p_mask, :]
)
if self.Zss_R is not None:
if self.Zss_R.ndim == 4:
self.Zss_R = self.Zss_R[:, p_mask, :, :]
elif self.Zss_R.ndim == 3:
self.Zss_R = self.Zss_R[:, p_mask, :]
if self.Zss_C is not None:
if self.Zss_C.ndim == 4:
self.Zss_C = self.Zss_C[:, p_mask, :, :]
elif self.Zss_C.ndim == 3:
self.Zss_C = self.Zss_C[:, p_mask, :]
if self.Zstdv is not None:
self.Zstdv = (
self.Zstdv[:, p_mask] if self.Zstdv.ndim == 2 else self.Zstdv[:, p_mask, :]
)
if (
getattr(self, "_orig_Zstdv", None) is not None
and self._orig_Zstdv.ndim >= 2
and self._orig_Zstdv.shape[1] == old_np
):
self._orig_Zstdv = (
self._orig_Zstdv[:, p_mask]
if self._orig_Zstdv.ndim == 2
else self._orig_Zstdv[:, p_mask, :]
)
if (
isinstance(self.counts, np.ndarray)
and self.counts.ndim >= 2
and self.counts.shape[1] == old_np
):
self.counts = (
self.counts[:, p_mask]
if self.counts.ndim == 2
else self.counts[:, p_mask, :]
)
if (
isinstance(self.units, dict)
and isinstance(self.units.get("rms"), np.ndarray)
and self.units["rms"].ndim >= 2
and self.units["rms"].shape[1] == old_np
):
self.units = dict(self.units)
rms_arr = self.units["rms"]
self.units["rms"] = (
rms_arr[:, p_mask] if rms_arr.ndim == 2 else rms_arr[:, p_mask, :]
)
if self.bkg_avg is not None:
self.bkg_avg = (
self.bkg_avg[p_mask] if self.bkg_avg.ndim == 1 else self.bkg_avg[p_mask, :]
)
if self.bkg_ss is not None:
self.bkg_ss = (
self.bkg_ss[p_mask] if self.bkg_ss.ndim == 1 else self.bkg_ss[p_mask, :]
)
if isinstance(self.units, dict) and "counts" in self.units and self.counts is not None:
self.units = dict(self.units)
self.units["counts"] = self.counts
self._scatter_removal_result = None
self._scatter_removal_params = None
params = {
k: float(v)
for k, v in (
("tmin", tmin),
("tmax", tmax),
("probe_min", probe_min),
("probe_max", probe_max),
)
if v is not None
}
self._history.record_call(self, "crop", _do, params=params)
return self
[docs]
def to_pdat(
self,
path: str | PathLike,
*,
detector: int | None = None,
use_corrected: bool = True,
write_noise: bool = True,
) -> list[Path]:
"""Export dataset to ``.pdat`` (and optional ``.pdatn``) file(s).
Parameters
----------
path : str or Path
Output file path.
detector : int, optional
Specific detector to export. If None and dataset has multiple detectors,
writes separate ``_DET1.pdat``, ``_DET2.pdat``, etc.
use_corrected : bool, default True
Whether to write background-corrected data.
write_noise : bool, default True
Whether to also write sibling ``.pdatn`` noise files.
Returns
-------
list[Path]
Paths of written .pdat files.
"""
from .load import export_pdat
return export_pdat(
self,
path,
detector=detector,
use_corrected=use_corrected,
write_noise=write_noise,
)
[docs]
def to_dataframe(
self,
format: str = "tidy",
detector: int = 0,
use_corrected: bool = True,
):
"""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).
"""
import pandas as pd
det = int(np.clip(detector, 0, self.n_detectors - 1))
delays = np.asarray(self.delays, dtype=float)
probe = np.asarray(self._detector_probe(det), dtype=float)
z = np.asarray(self.Z if use_corrected else self.Zavg_R, dtype=float)
if z.ndim == 3:
z = z[:, :, det]
if format == "wide":
return pd.DataFrame(z, index=delays, columns=probe)
elif format == "tidy":
T, W = np.meshgrid(delays, probe, indexing="ij")
data_dict = {
"delay": T.ravel(),
"probe": W.ravel(),
"signal": z.ravel(),
}
noise = self.noise_array()
if noise is not None:
n_mat = np.asarray(noise, dtype=float)
if n_mat.ndim == 3:
n_mat = n_mat[:, :, det]
data_dict["noise"] = n_mat.ravel()
return pd.DataFrame(data_dict)
else:
raise ValueError(f"Unknown format {format!r}. Choose 'tidy' or 'wide'.")
[docs]
def to_hdf5(self, path: str | PathLike) -> Path:
"""Save dataset to a self-contained HDF5 file."""
from .load import save_1D_hdf5
return save_1D_hdf5(self, path)
[docs]
def save_hdf5(self, path: str | PathLike) -> Path:
"""Alias of :meth:`to_hdf5`."""
return self.to_hdf5(path)
[docs]
def to_glotaran_ascii(
self,
path: str | PathLike,
*,
orientation: str = "time",
signal_unit: str = "mOD",
use_corrected: bool = True,
detector: int = 0,
) -> Path:
"""Export dataset to Glotaran / TIMP ``.ascii`` format."""
from .interop import write_glotaran_ascii
return write_glotaran_ascii(
self,
path,
orientation=orientation,
signal_unit=signal_unit,
use_corrected=use_corrected,
detector=detector,
)
[docs]
def to_glotaran_nc(
self,
path: str | PathLike,
*,
signal_unit: str = "mOD",
use_corrected: bool = True,
detector: int = 0,
write_noise: bool = True,
) -> Path:
"""Export dataset to a Glotaran / pyglotaran CF-1.8 NetCDF4 ``.nc`` file."""
from .interop import write_glotaran_nc
return write_glotaran_nc(
self,
path,
signal_unit=signal_unit,
use_corrected=use_corrected,
detector=detector,
write_noise=write_noise,
)
def _repr_html_(self) -> str:
"""Rich HTML summary card for Jupyter notebook display."""
time_unit = self.units.get("unitsT_ltx", "ps").replace("$", "")
probe_unit = self.units.get("unitsL_lbl", "Wavenumber")
probe_sym = self.units.get("unitsL_ltx", "cm^{-1}").replace("$", "")
z_unit = self.units.get("unitsZ_lbl", "\u0394A")
d_min = f"{float(np.nanmin(self.delays)):.2f}" if self.delays.size else "n/a"
d_max = f"{float(np.nanmax(self.delays)):.2f}" if self.delays.size else "n/a"
p_min = f"{float(np.nanmin(self.probe)):.1f}" if self.probe.size else "n/a"
p_max = f"{float(np.nanmax(self.probe)):.1f}" if self.probe.size else "n/a"
corr_badge = (
'<span style="background:#10b981;color:#fff;padding:2px 8px;border-radius:12px;font-size:11px;">Corrected</span>'
if self.is_corrected
else '<span style="background:#64748b;color:#fff;padding:2px 8px;border-radius:12px;font-size:11px;">Raw</span>'
)
return (
'<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Helvetica, Arial, sans-serif; '
'border: 1px solid #cbd5e1; border-radius: 8px; padding: 14px 18px; max-width: 540px; '
'background: #ffffff; color: #1e293b; box-shadow: 0 1px 3px rgba(0,0,0,0.05); margin: 8px 0;">'
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #e2e8f0; padding-bottom: 8px;">'
f'<span style="font-weight: 700; font-size: 15px; color: #0f172a;">PyMORGAN Dataset1D</span>'
f'<div>{corr_badge}</div>'
'</div>'
'<table style="width: 100%; border-collapse: collapse; font-size: 13px;">'
f'<tr><td style="color:#64748b; padding: 3px 0;">Data Type</td><td style="font-weight:600;">{self.data_type or "Unknown"}</td></tr>'
f'<tr><td style="color:#64748b; padding: 3px 0;">Dimensions</td><td style="font-weight:600;">{len(self.delays)} delays × {self.probe.shape[0]} pixels × {self.n_detectors} det</td></tr>'
f'<tr><td style="color:#64748b; padding: 3px 0;">Delay range</td><td>[{d_min}, {d_max}] {time_unit}</td></tr>'
f'<tr><td style="color:#64748b; padding: 3px 0;">Probe range ({probe_unit})</td><td>[{p_min}, {p_max}] {probe_sym}</td></tr>'
f'<tr><td style="color:#64748b; padding: 3px 0;">Signal unit</td><td>{z_unit}</td></tr>'
f'<tr><td style="color:#64748b; padding: 3px 0;">Calibration</td><td style="color:#0369a1;">{self.calibration_status()}</td></tr>'
'</table>'
'</div>'
)
# ----------------------------------------------------------------- #
# Shared resolution #
# ----------------------------------------------------------------- #
def _detector_slice(self, detector: int = 0):
"""Return the 2-D ``[Ndelays x Npixels]`` slice for ``detector``."""
if self.Z.ndim == 2:
return self.Z
return self.Z[:, :, detector]
def _detector_probe(self, detector: int = 0) -> np.ndarray:
"""Return 1-D probe array for ``detector``."""
probe = np.asarray(self.probe, dtype=float)
if probe.ndim > 1:
d = int(np.clip(detector, 0, probe.shape[1] - 1))
return probe[:, d]
return probe
# ----------------------------------------------------------------- #
# Sample-info / noise summary #
# ----------------------------------------------------------------- #
@property
def rms(self) -> np.ndarray | None:
"""Return the raw single-shot RMS noise matrix if present in units."""
if hasattr(self, "units") and isinstance(self.units, dict):
return self.units.get("rms")
return None
[docs]
def noise_array(self):
"""Per-point noise (standard deviation) of the signal, or ``None``.
Noise is taken from :attr:`Zstdv` when it carries non-trivial values
(e.g. loaded from a sibling ``.pdatn`` file), otherwise computed as the
standard deviation across the scan axis of :attr:`Zss_R` when
single-scan data is present. Returns ``None`` when neither is available.
Returns
-------
numpy.ndarray or None
Same shape as :attr:`Z` (``[Ndelays x Npixels x Ndetectors]``), in
the same unit as the signal (mOD), or ``None`` when the dataset
carries no noise information.
Notes
-----
Public because it is the input to weighted fitting: PyRATE-TA reads it to
build the ``1/sigma`` weights that turn a fit statistic into a true
reduced chi-squared. A dataset without a ``.pdatn`` sibling and without
single scans returns ``None``, and a weighted fit of it is refused
rather than silently falling back to an unweighted one.
"""
z = self.Zstdv
if z is not None:
z = np.asarray(z, dtype=float)
if z.size and np.any(np.isfinite(z)) and not np.allclose(np.nan_to_num(z), 0.0):
return z
if self.has_single_scans:
zss = np.asarray(self.Zss_R, dtype=float)
if zss.size and np.any(np.isfinite(zss)):
return np.nanstd(zss, axis=-1)
return None
@property
def has_noise(self) -> bool:
"""True if non-trivial noise or single-scan standard deviation is available."""
return self.noise_array() is not None
def _noise_array(self):
"""Deprecated alias of :meth:`noise_array`.
Kept so code written against the private name keeps working; new code
calls :meth:`noise_array`.
"""
return self.noise_array()
[docs]
def axis_units(self, display: bool = False, settings=None):
"""Units of the dataset axes: X (probe), Y (delay) and Z (signal).
Returns a :class:`~pymorgan.helpers.DatasetUnits` whose entries carry the
quantity, the unit token, the mathtext used on plots and the display
scaling factor::
>>> data.axis_units().x.unit
'cm-1'
>>> print(data.axis_units())
Axis units
x: Wavenumber in cm-1
y: Delay in ps
z: $\\Delta$A in x1E3
With ``display=True`` the spectral axis is reported as it would be
plotted, i.e. converted to ``Settings.x_axis_unit`` and carrying the
``10^3`` factor when the plot applies one; otherwise the dataset's own
(stored) units are reported.
"""
from pymorgan import helpers as hlp
from ..settings import get_settings
units = self.units or {}
if hlp.is_uncalibrated_probe(self):
return hlp.DatasetUnits(
x=hlp.AxisUnit(quantity="Pixel index", unit="px", latex="", scale=1.0),
y=hlp.delay_axis_unit(units),
z=hlp.signal_axis_unit(units),
)
native = hlp.native_x_unit(units)
scale = 1.0
unit = native
if display:
s = settings or get_settings()
x_axis_unit = getattr(s, "x_axis_unit", "native")
x_axis_unit = x_axis_unit.value if hasattr(x_axis_unit, "value") else x_axis_unit
unit = hlp.resolve_x_unit(x_axis_unit, native)
# The 1-D plots only rescale wavenumber axes (see plot._resolve_x_axis).
if unit == "cm-1":
probe = np.asarray(self.probe, dtype=float)
scale = hlp.display_scale(hlp.convert_spectral(probe, native, unit))
return hlp.DatasetUnits(
x=hlp.spectral_axis_unit(unit, scale),
y=hlp.delay_axis_unit(units),
z=hlp.signal_axis_unit(units),
)
@property
def has_extended_sample_info(self) -> bool:
"""Whether extended ('all available') sample metadata is available."""
u = self.units or {}
full = u.get("sample_info_full")
compact = u.get("sample_info")
return bool(full) and full != compact
[docs]
def sample_info(self, show_all: bool = False) -> str:
"""Return an HTML dataset summary shown in the GUI info box."""
from .. import helpers as hlp
u = self.units or {}
if hlp.is_uncalibrated_probe(self):
probe_unit = "px"
else:
probe_unit = _PLAIN_PROBE_UNIT.get(
u.get("unitsL_lbl", ""), _ltx_to_text(u.get("unitsL_ltx", ""))
)
noise_unit = (
"mOD" if u.get("unitsZ") in ("mOD", "x1E3") else _ltx_to_text(u.get("unitsZ_ltx", ""))
)
probe = np.asarray(self.probe, dtype=float)
res = float(np.median(np.abs(np.diff(probe)))) if probe.size > 1 else float("nan")
scans = f"Avg. of {int(self.nscans)} scans" if np.isfinite(self.nscans) else "Avg. Data"
sig = np.asarray(self.Z, dtype=float)
peak = (
float(np.nanmax(np.abs(sig))) if sig.size and np.any(np.isfinite(sig)) else float("nan")
)
noise = self.noise_array()
if noise is None:
line1 = "No single scan data available"
snr = "Inf"
else:
avg_noise = float(np.nanmean(noise))
max_noise = float(np.nanmax(noise))
line1 = f"<b>Avg. Noise:</b> {avg_noise:.4f} {noise_unit} <b>Max Noise:</b> {max_noise:.4f} {noise_unit}"
snr = "Inf" if avg_noise == 0 or not np.isfinite(peak) else f"{peak / avg_noise:.0f}"
res_str = f"{res:.2f} {probe_unit}" if np.isfinite(res) else "n/a"
line2 = f"<b>SNR:</b> {snr} / <b>Scans:</b> {scans} / <b>Res.:</b> {res_str}"
line3 = _format_1d_delay_info(self.delays, u.get("unitsT_ltx", "ps"), html=True)
line_cal = f"<b>Calibration:</b> {self.calibration_status()}"
lines = [line1, line2, line3, line_cal]
info_extra = (u.get("sample_info_full") or u.get("sample_info")) if show_all else u.get("sample_info")
if info_extra:
formatted_info = html.escape(str(info_extra), quote=False).replace("\n", "<br>")
lines.append(f"<b>Sample Info:</b><br>{formatted_info}")
else:
lines.append("<b>Sample Info:</b> No additional sample information available.")
return "<br>".join(lines)
[docs]
def sample_info_console(self, show_all: bool = False) -> str:
"""Return a plain text, console-friendly summary of the 1-D dataset."""
from .. import helpers as hlp
u = self.units or {}
if hlp.is_uncalibrated_probe(self):
probe_unit = "px"
else:
probe_unit = _PLAIN_PROBE_UNIT.get(
u.get("unitsL_lbl", ""), _ltx_to_text(u.get("unitsL_ltx", ""))
)
# Convert any unicode exponents to plain text
probe_unit = probe_unit.replace("cm⁻¹", "cm-1")
noise_unit = (
"mOD" if u.get("unitsZ") in ("mOD", "x1E3") else _ltx_to_text(u.get("unitsZ_ltx", ""))
)
noise_unit = noise_unit.replace("cm⁻¹", "cm-1")
probe = np.asarray(self.probe, dtype=float)
res = float(np.median(np.abs(np.diff(probe)))) if probe.size > 1 else float("nan")
scans = f"Avg. of {int(self.nscans)} scans" if np.isfinite(self.nscans) else "Avg. Data"
sig = np.asarray(self.Z, dtype=float)
peak = (
float(np.nanmax(np.abs(sig))) if sig.size and np.any(np.isfinite(sig)) else float("nan")
)
noise = self.noise_array()
if noise is None:
line1 = "No single scan data available"
snr = "Inf"
else:
avg_noise = float(np.nanmean(noise))
max_noise = float(np.nanmax(noise))
line1 = f"Avg. Noise: {avg_noise:.4f} {noise_unit} Max Noise: {max_noise:.4f} {noise_unit}"
snr = "Inf" if avg_noise == 0 or not np.isfinite(peak) else f"{peak / avg_noise:.0f}"
res_str = f"{res:.2f} {probe_unit}" if np.isfinite(res) else "n/a"
line2 = f"SNR: {snr} / Scans: {scans} / Res.: {res_str}"
line3 = _format_1d_delay_info(self.delays, u.get("unitsT_ltx", "ps"), html=False)
line_cal = f"Calibration: {self.calibration_status()}"
lines = [line1, line2, line3, line_cal]
info_extra = (u.get("sample_info_full") or u.get("sample_info")) if show_all else u.get("sample_info")
if info_extra:
lines.append(f"Sample Info:\n{info_extra}")
else:
lines.append("Sample Info: No additional sample information available.")
return "\n".join(lines)
[docs]
def calibration_status(self) -> str:
"""Return a clean, human-readable probe calibration source description."""
cal_source = getattr(self, "cal_source", None) or self.units.get("cal_source")
if cal_source:
return cal_source
cal_level = getattr(self, "cal_level", None) or self.units.get("cal_level")
if cal_level == "datadir":
return "CalibratedProbe.csv (data folder)"
if cal_level == "rootdir":
return "CalibratedProbe.csv (root folder)"
if self.data_type == "MESS_TRIR":
return "Dataset probe axis (wavenumbers.csv)"
if self.data_type == "MESS_TRUVIS":
return "Dataset probe axis (wavelengths.csv)"
if self.data_type == "HARPIA_TA":
return "Embedded HARPIA probe axis"
if self.data_type == "PDAT":
return "Dataset probe axis (PDAT header)"
if self.data_type == "Helios_TA":
return "Dataset probe axis (CSV header)"
if self.data_type == "PyMESS_PP":
return "Embedded PyMESS probe axis"
if self.data_type == "QuickControl_PP":
return "QuickControl monochromator calibration"
return "Dataset probe calibration"
[docs]
def print_sample_info(self, show_all: bool = False) -> None:
"""Print the console-friendly summary of the 1-D dataset."""
print(self.sample_info_console(show_all=show_all))
def _resolve(
self,
settings: Settings | None,
label_style: str | None,
delta_a_units: DeltaAUnits | str | None,
) -> tuple[Settings, str, dict]:
"""Resolve active settings and per-call label/unit overrides."""
s = settings or get_settings()
style = label_style if label_style is not None else s.label_style.value
if isinstance(delta_a_units, str):
delta_a_units = DeltaAUnits(delta_a_units)
units = s.units_with_convention(self.units, delta_a_units)
return s, style, units
# ----------------------------------------------------------------- #
# Process #
# ----------------------------------------------------------------- #
[docs]
def background_correct(self, tmin, tmax, do_correct: bool = True) -> Dataset1D:
"""Subtract the pre-zero background averaged over ``[tmin, tmax]``.
Returns ``self`` so calls can be chained.
"""
tmin_f = float(tmin)
tmax_f = float(tmax)
do_c = bool(do_correct)
def _do():
self.Zavg_C, self.Zss_C, self.bkg_avg, self.bkg_ss = process.background_correct(
self.Zavg_R, self.Zss_R, self.nscans, self.delays, tmin_f, tmax_f, do_correct=do_c
)
self._bkg_params = {"tmin": tmin_f, "tmax": tmax_f, "do_correct": do_c}
self._history.record_call(
self,
"background_correct",
_do,
params={"tmin": tmin_f, "tmax": tmax_f, "do_correct": do_c},
coalesce=True,
)
return self
[docs]
def detect_scatter_bands(
self,
*,
detector: int = 0,
tmin: float | None = None,
tmax: float | None = None,
allow_positive: bool = False,
):
"""Auto-detect localised scatter bands from the pre-zero spectrum.
Parameters
----------
detector : int, default 0
0-based detector channel index to inspect.
tmin, 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
-------
list of ScatterBand
Auto-detected primary and optional coupled 2nd-order harmonic bands.
"""
from .scatter import detect_scatter_bands
Z_arr = np.asarray(self.Zavg_R, dtype=float)
if Z_arr.ndim == 3:
d = int(np.clip(detector, 0, Z_arr.shape[2] - 1))
Z_2d = Z_arr[:, :, d]
else:
Z_2d = Z_arr
return detect_scatter_bands(
Z_2d,
self.delays,
self._detector_probe(detector),
tmin=tmin,
tmax=tmax,
units=self.units,
allow_positive=allow_positive,
)
[docs]
def apply_scatter_removal(self, result) -> Dataset1D:
"""Apply a computed :class:`~pymorgan.oneD.scatter.ScatterRemovalResult` in-place.
Copies the cleaned averaged and single-scan arrays, stores the removal
metadata, and backs up ``Zstdv`` prior to updating it when
``result.Zstdv`` is provided.
Parameters
----------
result : ScatterRemovalResult
Output produced by :func:`pymorgan.oneD.scatter.compute_scatter_removal`.
Returns
-------
Dataset1D
Returns ``self`` so calls can be chained.
"""
def _do():
if getattr(self, "_orig_Zstdv", None) is None and self.Zstdv is not None:
self._orig_Zstdv = np.copy(self.Zstdv)
self.Zavg_C = np.copy(result.Zavg_C)
self.Zss_C = np.copy(result.Zss_C) if result.Zss_C is not None else None
self.bkg_avg = np.copy(result.bkg_avg) if result.bkg_avg is not None else None
self.bkg_ss = np.copy(result.bkg_ss) if result.bkg_ss is not None else None
if result.Zstdv is not None:
self.Zstdv = np.copy(result.Zstdv)
elif getattr(self, "_orig_Zstdv", None) is not None:
self.Zstdv = np.copy(self._orig_Zstdv)
self._scatter_removal_result = result
self._scatter_removal_params = dict(result.params)
params = dict(getattr(result, "params", {}) or {})
self._history.record_call(self, "apply_scatter_removal", _do, params=params)
return self
[docs]
def remove_scatter(self, bands=None, **kwargs) -> Dataset1D:
"""Run multi-band scatter and dynamic background removal in-place.
Delegates to :func:`pymorgan.oneD.scatter.compute_scatter_removal` and
applies the cleaned arrays (and optional updated ``Zstdv``) to this
dataset. Run prior to chirp correction so unchirped scatter tied to the
delay stage is isolated cleanly.
Parameters
----------
bands : list of ScatterBand, optional
Explicit scatter bands in native probe units. When ``None``, bands
are automatically detected from the pre-zero spectrum.
**kwargs
Additional keyword arguments forwarded to
:func:`pymorgan.oneD.scatter.compute_scatter_removal` (such as
``method``, ``rank``, ``poly_deg``, ``t0_exclude``,
``scale_broadband``, ``per_scan``, ``update_noise``, and
``transmittance_space``).
Returns
-------
Dataset1D
Returns ``self`` so calls can be chained.
"""
from .scatter import compute_scatter_removal
def _do():
res = compute_scatter_removal(self, bands=bands, **kwargs)
return self.apply_scatter_removal(res)
params = dict(kwargs)
if bands is not None:
params["bands"] = bands
self._history.record_call(self, "remove_scatter", _do, params=params)
return self
[docs]
def clear_scatter_removal(self) -> Dataset1D:
"""Clear applied advanced scatter removal state and restore original ``Zstdv``.
Returns
-------
Dataset1D
Returns ``self`` so calls can be chained.
"""
def _do():
self._scatter_removal_result = None
self._scatter_removal_params = None
if getattr(self, "_orig_Zstdv", None) is not None:
self.Zstdv = np.copy(self._orig_Zstdv)
self._orig_Zstdv = None
self._history.record_call(self, "clear_scatter_removal", _do, params={})
return self
[docs]
def recalc_average(
self,
scan_indices: Sequence[int],
*,
spectrum: int = 0,
slowmod: int = 0,
noise_weighted: bool = True,
) -> Dataset1D:
"""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
-------
Dataset1D
Returns ``self`` for chaining.
"""
scan_indices_list = [int(k) for k in scan_indices]
if not scan_indices_list:
raise ValueError("No scans selected.")
def _do():
if self.data_type in ("MESS_TRIR", "MESS_TRUVIS"):
from .load import mess_recalc_average
Zavg, Zstdv = mess_recalc_average(
self.source,
scan_indices_list,
spectrum=spectrum,
slowmod=slowmod,
noise_weighted=noise_weighted,
)
elif self.has_single_scans:
sub = self.Zss_R[:, :, :, scan_indices_list]
with np.errstate(divide="ignore", invalid="ignore"):
if noise_weighted and len(scan_indices_list) > 1:
neg_idx = np.where(self.delays < 0)[0]
if len(neg_idx) >= 2:
scan_var = np.nanvar(sub[neg_idx, :, :, :], axis=(0, 1, 2))
valid = np.isfinite(scan_var) & (scan_var > 0)
if np.all(valid):
w = 1.0 / scan_var
w = w / np.sum(w)
Zavg = np.sum(sub * w.reshape(1, 1, 1, -1), axis=-1)
else:
Zavg = np.nanmean(sub, axis=-1)
else:
Zavg = np.nanmean(sub, axis=-1)
else:
Zavg = np.nanmean(sub, axis=-1)
if len(scan_indices_list) > 1:
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
Zstdv = np.nanstd(sub, axis=-1, ddof=1)
Zstdv = np.nan_to_num(Zstdv, nan=0.0)
else:
Zstdv = np.zeros_like(Zavg)
Zavg = np.nan_to_num(Zavg, nan=0.0)
else:
raise ValueError(
f"Dataset of type {self.data_type} has no per-scan data to recombine."
)
self.Zavg_R = Zavg
self.Zstdv = Zstdv
self.nscans = len(scan_indices_list)
self.Zavg_C = None # Invalidate background correction cache
self._bkg_params = None
self._scatter_removal_result = None
self._scatter_removal_params = None
self._orig_Zstdv = None
self._history.record_call(
self,
"recalc_average",
_do,
params={
"scan_indices": scan_indices_list,
"spectrum": int(spectrum),
"slowmod": int(slowmod),
"noise_weighted": bool(noise_weighted),
},
)
return self
[docs]
def mask_probe_regions(
self, ranges: list[tuple[float, float]], detector: int | None = None
) -> Dataset1D:
"""Remove or mask data in the specified probe ranges (in native units).
For single-detector datasets (or when n_detectors <= 1), specified probe
ranges are removed from the probe and data arrays.
For multi-detector datasets, the masking is applied to the specified
detector channel only, setting data in the masked range to NaN so each
detector retains its independent probe axis and grid dimensions.
Returns ``self`` so calls can be chained.
"""
if not ranges:
return self
clean_ranges = [(float(a), float(b)) for a, b in ranges]
def _do():
if self.n_detectors <= 1:
# Build a mask of indices to keep
keep = np.ones(self.probe.shape, dtype=bool)
for r_min, r_max in clean_ranges:
keep = keep & ~((self.probe >= r_min) & (self.probe <= r_max))
self.probe = self.probe[keep]
if self.Zavg_R is not None:
if self.Zavg_R.ndim == 3:
self.Zavg_R = self.Zavg_R[:, keep, :]
elif self.Zavg_R.ndim == 2:
self.Zavg_R = self.Zavg_R[:, keep]
if self.Zss_R is not None:
self.Zss_R = np.asarray(self.Zss_R)
if self.Zss_R.ndim == 4:
self.Zss_R = self.Zss_R[:, keep, :, :]
elif self.Zss_R.ndim == 3:
self.Zss_R = self.Zss_R[:, keep, :]
elif self.Zss_R.ndim == 2:
self.Zss_R = self.Zss_R[:, keep]
elif self.Zss_R.ndim == 1:
self.Zss_R = self.Zss_R[keep]
if self.Zstdv is not None:
self.Zstdv = np.asarray(self.Zstdv)
if self.Zstdv.ndim == 3:
self.Zstdv = self.Zstdv[:, keep, :]
elif self.Zstdv.ndim == 2:
self.Zstdv = self.Zstdv[:, keep]
elif self.Zstdv.ndim == 1:
self.Zstdv = self.Zstdv[keep]
if self.Zavg_C is not None:
if self.Zavg_C.ndim == 3:
self.Zavg_C = self.Zavg_C[:, keep, :]
elif self.Zavg_C.ndim == 2:
self.Zavg_C = self.Zavg_C[:, keep]
if self.Zss_C is not None:
if self.Zss_C.ndim == 4:
self.Zss_C = self.Zss_C[:, keep, :, :]
elif self.Zss_C.ndim == 3:
self.Zss_C = self.Zss_C[:, keep, :]
elif self.Zss_C.ndim == 2:
self.Zss_C = self.Zss_C[:, keep]
if self.bkg_avg is not None:
if self.bkg_avg.ndim == 2:
self.bkg_avg = self.bkg_avg[keep, :]
elif self.bkg_avg.ndim == 1:
self.bkg_avg = self.bkg_avg[keep]
if self.bkg_ss is not None:
if self.bkg_ss.ndim == 3:
self.bkg_ss = self.bkg_ss[keep, :, :]
elif self.bkg_ss.ndim == 2:
self.bkg_ss = self.bkg_ss[keep, :]
elif self.bkg_ss.ndim == 1:
self.bkg_ss = self.bkg_ss[keep]
self.mask_ranges = clean_ranges
self._scatter_removal_result = None
self._scatter_removal_params = None
self._orig_Zstdv = None
else:
det = detector if detector is not None else 0
det = int(np.clip(det, 0, self.n_detectors - 1))
probe_det = self._detector_probe(det)
mask_det = np.zeros(probe_det.shape, dtype=bool)
for r_min, r_max in clean_ranges:
mask_det = mask_det | ((probe_det >= r_min) & (probe_det <= r_max))
if np.any(mask_det):
if self.Zavg_R is not None and self.Zavg_R.ndim == 3:
self.Zavg_R[:, mask_det, det] = np.nan
if self.Zavg_C is not None and self.Zavg_C.ndim == 3:
self.Zavg_C[:, mask_det, det] = np.nan
if self.Zss_R is not None:
self.Zss_R = np.array(self.Zss_R, copy=True)
if self.Zss_R.ndim == 4:
self.Zss_R[:, mask_det, det, :] = np.nan
if self.Zss_C is not None:
self.Zss_C = np.array(self.Zss_C, copy=True)
if self.Zss_C.ndim == 4:
self.Zss_C[:, mask_det, det, :] = np.nan
if self.Zstdv is not None:
self.Zstdv = np.asarray(self.Zstdv)
if self.Zstdv.ndim == 3:
self.Zstdv[:, mask_det, det] = np.nan
if self.bkg_avg is not None:
self.bkg_avg = np.asarray(self.bkg_avg)
if self.bkg_avg.ndim == 2:
self.bkg_avg[mask_det, det] = np.nan
if self.bkg_ss is not None:
self.bkg_ss = np.array(self.bkg_ss, copy=True)
if self.bkg_ss.ndim == 3:
self.bkg_ss[mask_det, det, :] = np.nan
if not hasattr(self, "mask_ranges_by_det"):
self.mask_ranges_by_det = {}
self.mask_ranges_by_det[det] = clean_ranges
self.mask_ranges = clean_ranges
params: dict[str, Any] = {"ranges": [list(r) for r in clean_ranges]}
if detector is not None:
params["detector"] = int(detector)
self._history.record_call(self, "mask_probe_regions", _do, params=params)
return self
[docs]
def shift_t0(self, t0_shift: float) -> Dataset1D:
"""Shift the delay time axis by subtracting ``t0_shift``.
Updates ``self.delays = self.delays - t0_shift``.
Since single-scan data (``Zss_R``) and accumulation counts (``counts``)
are aligned with ``self.delays``, they are automatically shifted.
Resetting ``self.Zavg_C`` forces background correction to re-evaluate
pre-zero delay indices with the updated time axis.
"""
shift_f = float(t0_shift)
def _do():
self.delays = np.asarray(self.delays, dtype=float) - shift_f
self.Zavg_C = None
self._bkg_params = None
self.clear_scatter_removal()
self._history.record_call(self, "shift_t0", _do, params={"t0_shift": shift_f})
return self
[docs]
def subtract_solvent(
self, solvent, dt: float | np.ndarray = 0.0, scale: float | np.ndarray = 1.0
) -> Dataset1D:
"""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) :attr:`Zavg_C`, so it composes naturally with a prior
:meth:`background_correct` call: the solvent is subtracted from
whichever signal is currently returned by :attr:`Z`.
Parameters
----------
solvent : Dataset1D
The solvent (reference) dataset. If it has been background-
corrected (``solvent.Zavg_C`` is not ``None``) its corrected signal
is used; otherwise the raw signal (``solvent.Zavg_R``) is used.
dt : float or array-like
Timing offset in ps (scalar or per-pixel array of length ``Npixels``).
A positive ``dt`` shifts the solvent signal towards *earlier* times
on the sample delay grid.
scale : float or array-like
Amplitude scaling factor (scalar or per-pixel array of length ``Npixels``).
Returns
-------
Dataset1D
``self`` — so calls can be chained.
"""
def _do():
Z_solvent = solvent.Zavg_C if solvent.Zavg_C is not None else solvent.Zavg_R
if not np.array_equal(solvent.probe, self.probe):
from scipy.interpolate import make_interp_spline
sol_probe = np.asarray(solvent.probe, dtype=float)
s_idx = np.argsort(sol_probe)
xp = sol_probe[s_idx]
Z_sol_sorted = Z_solvent[:, s_idx, :] if Z_solvent.ndim == 3 else Z_solvent[:, s_idx]
spl = make_interp_spline(xp, Z_sol_sorted, k=1, axis=1)
Z_solvent_aligned = spl(self.probe)
else:
Z_solvent_aligned = Z_solvent
self.Zavg_C = process.subtract_solvent(
self.Z,
self.delays,
Z_solvent_aligned,
solvent.delays,
dt=dt,
scale=scale,
)
# Provenance — keep references so the caller can inspect them.
self._solvent_dataset = solvent
self._solvent_dt = dt
self._solvent_scale = scale
params: dict[str, Any] = {
"solvent_file": getattr(solvent, "source", None),
"solvent_data_type": getattr(solvent, "data_type", None),
"dt": dt,
"scale": scale,
}
self._history.record_call(self, "subtract_solvent", _do, params=params)
return self
[docs]
def subtract_shockwave(
self,
pixels: int | Sequence[int] | slice | None = None,
probe_range: tuple[float, float] | None = None,
probe_values: float | Sequence[float] | None = None,
one_based: bool = True,
) -> Dataset1D:
"""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 :attr:`Zavg_C` (and
:attr:`Zss_C` if single-scan data is present).
Parameters
----------
pixels : int, sequence of int, slice, or None
Pixel index or indices to average over (1-based by default when ``one_based=True``).
probe_range : tuple (min_probe, max_probe) or None
Probe axis range (in native units) over which to select pixels.
probe_values : float or sequence of float or None
Probe value(s) in native units for which to find the nearest pixel(s).
one_based : bool, default True
Whether integer ``pixels`` are 1-based pixel numbers (1..Npixels).
Returns
-------
Dataset1D
``self`` — so calls can be chained.
"""
if pixels is None and probe_range is None and probe_values is None:
raise ValueError(
"Must specify at least one of 'pixels', 'probe_range', or 'probe_values'."
)
Npixels = self.probe.size
pix_0based = None
if pixels is not None:
if isinstance(pixels, slice):
step = pixels.step or 1
if one_based:
start = (pixels.start - 1) if pixels.start is not None else 0
stop = pixels.stop if pixels.stop is not None else Npixels
else:
start = pixels.start if pixels.start is not None else 0
stop = pixels.stop if pixels.stop is not None else Npixels
pix_0based = np.arange(start, stop, step)
else:
arr = np.atleast_1d(np.asarray(pixels))
if arr.dtype == bool:
pix_0based = np.where(arr)[0]
else:
pix_0based = arr - 1 if one_based else arr
elif probe_range is not None:
p_min, p_max = min(probe_range), max(probe_range)
mask = (self.probe >= p_min) & (self.probe <= p_max)
pix_0based = np.where(mask)[0]
if pix_0based.size == 0:
raise ValueError(f"No pixels found in probe range [{p_min}, {p_max}].")
elif probe_values is not None:
p_vals = np.atleast_1d(np.asarray(probe_values, dtype=float))
nearest_indices = [int(np.argmin(np.abs(self.probe - val))) for val in p_vals]
pix_0based = np.unique(np.array(nearest_indices, dtype=int))
def _do():
Z_in = self.Z
self.Zavg_C, shockwave_trace = process.subtract_shockwave(
Z_in, pix_0based, one_based=False
)
if self.has_single_scans:
Zss_in = self.Zss_C if self.Zss_C is not None else self.Zss_R
self.Zss_C, _ = process.subtract_shockwave(Zss_in, pix_0based, one_based=False)
self._shockwave_pixels = pix_0based
self._shockwave_trace = shockwave_trace
params: dict[str, Any] = {}
if pixels is not None:
if isinstance(pixels, slice):
params["pixels"] = [int(i) for i in pix_0based]
params["one_based"] = False
else:
params["pixels"] = pixels
params["one_based"] = bool(one_based)
elif probe_range is not None:
params["probe_range"] = [float(probe_range[0]), float(probe_range[1])]
elif probe_values is not None:
params["probe_values"] = probe_values
self._history.record_call(self, "subtract_shockwave", _do, params=params)
return self
[docs]
def fit_solvent_auto(
self,
solvent,
det_idx: int = 0,
per_pixel_dt: bool | None = None,
per_pixel_scale: bool | None = None,
) -> tuple[float | np.ndarray, float | np.ndarray]:
"""Automatically find optimal timing offset and scaling for solvent subtraction.
Fits a global (or per-pixel) timing offset ``dt`` and a global (or per-pixel)
amplitude scaling factors ``scale`` to match an erf-broadened step-like rise.
Parameters
----------
solvent : Dataset1D
The solvent dataset.
det_idx : int, default 0
The detector channel index to optimise for.
per_pixel_dt : bool or None
Whether to optimise a separate timing offset for each pixel. If None,
reads the default from active settings (``solvent_per_pixel_dt``).
per_pixel_scale : bool or None
Whether to optimise a separate amplitude scaling factor for each pixel.
If None, reads the default from active settings (``solvent_per_pixel_scale``).
Returns
-------
scale : float or ndarray
Optimal global scaling factor (float) or per-pixel scaling factors (ndarray).
dt : float or ndarray
Optimal global timing offset (float) or per-pixel timing offsets (ndarray).
"""
import pymorgan as pm
if per_pixel_dt is None:
per_pixel_dt = pm.get_settings().solvent_per_pixel_dt
if per_pixel_scale is None:
per_pixel_scale = pm.get_settings().solvent_per_pixel_scale
Z_solvent = solvent.Zavg_C if solvent.Zavg_C is not None else solvent.Zavg_R
if not np.array_equal(solvent.probe, self.probe):
from scipy.interpolate import make_interp_spline
sol_probe = np.asarray(solvent.probe, dtype=float)
s_idx = np.argsort(sol_probe)
xp = sol_probe[s_idx]
Z_sol_sorted = Z_solvent[:, s_idx, :] if Z_solvent.ndim == 3 else Z_solvent[:, s_idx]
spl = make_interp_spline(xp, Z_sol_sorted, k=1, axis=1)
Z_solvent_aligned = spl(self.probe)
else:
Z_solvent_aligned = Z_solvent
return process.fit_solvent_auto(
self.Z,
self.delays,
Z_solvent_aligned,
solvent.delays,
det_idx=det_idx,
per_pixel_dt=per_pixel_dt,
per_pixel_scale=per_pixel_scale,
)
[docs]
def time_derivative(
self,
*,
t_min: float | None = None,
interpolate: bool = False,
n_interp: int | None = None,
interp_kind: str = "cubic",
smooth: bool = False,
smooth_method: str = "savgol",
smooth_window: int = 7,
smooth_poly: int = 2,
) -> Dataset1D:
"""Calculate the time derivative d(Delta A)/dt along the delay axis.
Returns a new :class:`Dataset1D` holding the differentiated signals
with updated units metadata (e.g. ``d(Delta A)/dt``).
"""
from .process import time_derivative
delays_out, Zavg_dt, Zss_dt = time_derivative(
self.delays,
self.Z,
self.Zss_R,
t_min=t_min,
interpolate=interpolate,
n_interp=n_interp,
interp_kind=interp_kind,
smooth=smooth,
smooth_method=smooth_method,
smooth_window=smooth_window,
smooth_poly=smooth_poly,
)
units_out = dict(self.units)
t_unit = units_out.get("unitsT_ltx") or units_out.get("time_unit") or "ps"
units_out["unitsZ_lbl"] = r"$\mathrm{d}(\Delta A)/\mathrm{d}t$"
units_out["unitsZ_ltx"] = rf"$\mathrm{{mOD}}/\mathrm{{{t_unit}}}$"
units_out["unitsZ"] = "dZ/dt"
Zstdv_out = None
if self.Zstdv is not None and np.any(self.Zstdv):
try:
if t_min is not None:
mask = self.delays >= float(t_min)
Zstdv_out = self.Zstdv[mask, ...]
else:
Zstdv_out = self.Zstdv.copy()
except Exception:
Zstdv_out = None
new_ds = Dataset1D(
Zavg_dt,
delays_out,
self.probe.copy(),
units_out,
nscans=self.nscans,
Zss_R=Zss_dt,
Zstdv=Zstdv_out,
source=self.source,
data_type=self.data_type,
scan_ids=self.scan_ids,
counts=self.counts,
)
return new_ds
[docs]
def calculate_anisotropy(
self,
perpendicular=None,
*,
g_factor: float | np.ndarray = 1.0,
threshold: float | None = None,
return_components: bool = False,
detector_par: int = 0,
detector_perp: int = 1,
use_corrected: bool = True,
):
"""Calculate time-resolved polarization anisotropy from parallel and perpendicular signals.
Parameters
----------
perpendicular : Dataset1D, optional
Perpendicular polarization dataset. If omitted, ``self`` must
have at least 2 detectors.
g_factor : float or ndarray, default 1.0
Sensitivity correction factor G.
threshold : float, optional
Minimum value of isotropic signal below which anisotropy is set to NaN.
return_components : bool, default False
If True, returns a dict with keys ``'anisotropy'``, ``'magic_angle'``,
``'difference'``, ``'parallel'``, and ``'perpendicular'``.
detector_par : int, default 0
Channel index for parallel polarization when unpacking a single multi-detector dataset.
detector_perp : int, default 1
Channel index for perpendicular polarization when unpacking a single multi-detector dataset.
use_corrected : bool, default True
Whether to use background-corrected signal (``Dataset1D.Z``) or raw (``Dataset1D.Zavg_R``).
Returns
-------
Dataset1D or dict[str, Dataset1D]
Anisotropy dataset or dictionary of component datasets.
"""
return process.calculate_anisotropy(
self,
perpendicular,
g_factor=g_factor,
threshold=threshold,
return_components=return_components,
detector_par=detector_par,
detector_perp=detector_perp,
use_corrected=use_corrected,
)
anisotropy = calculate_anisotropy
[docs]
def svd(
self,
k: int = 2,
detector: int = 0,
array: str = "auto",
tmin: float | None = None,
tmax: float | None = None,
probe_min: float | None = None,
probe_max: float | None = None,
centering: str = "none",
handle_nan: str = "interpolate",
):
"""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, tmax : float, optional
Delay range limits for cropping prior to SVD.
probe_min, 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
-------
SVDResult
Result container with components, scree analysis, and recomposition tools.
"""
from .svd import compute_svd
if array == "raw":
data = self.Zavg_R
elif array == "corrected":
data = self.Zavg_C if self.Zavg_C is not None else self.Zavg_R
else:
data = self.Z
# Extract 2D slice for detector if 3D
if data.ndim == 3:
det = int(np.clip(detector, 0, data.shape[2] - 1))
mat = data[:, :, det]
else:
mat = data
probe_det = self._detector_probe(detector)
return compute_svd(
data=mat,
delays=self.delays,
probe=probe_det,
k=k,
tmin=tmin,
tmax=tmax,
probe_min=probe_min,
probe_max=probe_max,
centering=centering,
handle_nan=handle_nan,
units=self.units,
)
[docs]
def stitch_wavelength(
self,
other: Dataset1D,
stitch_region: tuple[float, float] | None = None,
mode: Literal["blend", "cutover"] = "blend",
blend_window: tuple[float, float] | None = None,
cutover_wl: float | None = None,
time_threshold: float = -0.1,
scale_override: float | None = None,
target_delays: Literal["ds2", "ds1"] | np.ndarray = "ds2",
detector1: int = 0,
detector2: int = 0,
):
"""Stitch this dataset with another spectral window (e.g. UV/Vis + NIR).
See :func:`pymorgan.oneD.stitch.stitch_wavelength` for parameter details.
"""
from .stitch import stitch_wavelength
return stitch_wavelength(
self,
other,
stitch_region=stitch_region,
mode=mode,
blend_window=blend_window,
cutover_wl=cutover_wl,
time_threshold=time_threshold,
scale_override=scale_override,
target_delays=target_delays,
detector1=detector1,
detector2=detector2,
)
[docs]
def stitch_time(
self,
other_ns: Dataset1D,
time_overlap: tuple[float, float] = (0.5, 2.0),
blend_window: tuple[float, float] = (1.0, 1.7),
scale_model: Literal["quadratic", "scalar"] = "quadratic",
scale_override: float | None = None,
align_wl: bool = True,
cut_scatter: bool = False,
scatter_region: tuple[float, float] = (500.0, 550.0),
detector_fs: int = 0,
detector_ns: int = 0,
):
"""Stitch this ultrafast (fs) dataset with a long-delay (ns) dataset.
See :func:`pymorgan.oneD.stitch.stitch_time` for parameter details.
"""
from .stitch import stitch_time
return stitch_time(
self,
other_ns,
time_overlap=time_overlap,
blend_window=blend_window,
scale_model=scale_model,
scale_override=scale_override,
align_wl=align_wl,
cut_scatter=cut_scatter,
scatter_region=scatter_region,
detector_fs=detector_fs,
detector_ns=detector_ns,
)
# ----------------------------------------------------------------- #
# Plot #
# ----------------------------------------------------------------- #
[docs]
def plot_contour(self, ax=None, **kwargs):
"""Delay-vs-probe contour map.
Parameters
----------
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure. When an axis is
given the figure layout is left to the caller, so the panel can be
placed in a ``GridSpec`` composite.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_contour`, which documents
them all. The ones reached for most often are ``Zscale`` (colour
limit as a percentage of the peak), ``Zmin``/``Zmax`` (explicit
limits, for putting panels on a common scale), ``Yscale``
(``"symlog"``/``"log"``/``"lin"`` delay axis), ``ShowLines``,
``Nlevels``/``Nskip``, ``cmap_ID``, ``x_axis_unit``,
``show_colorbar`` and ``show_xlabel``/``show_ylabel``. Anything not
given follows the active :class:`~pymorgan.settings.Settings`.
Returns
-------
matplotlib.axes.Axes
Examples
--------
>>> ax = data.plot_contour(ShowLines=True, Zscale=30, Yscale="symlog")
"""
from . import plot
return plot.plot_contour(self, ax, **kwargs)
[docs]
def plot_noise_3d(self, ax=None, **kwargs):
"""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 :func:`pymorgan.oneD.plot.plot_noise_3d` (``detector``,
``x_axis_unit``, ``label_style``, ...).
Returns
-------
mpl_toolkits.mplot3d.axes3d.Axes3D
Raises
------
ValueError
If the dataset carries neither a noise array nor single-scan data.
"""
from . import plot
return plot.plot_noise_3d(self, ax, **kwargs)
[docs]
def plot_noise_spectrum(self, ax=None, **kwargs):
"""Plot the delay-averaged noise spectrum against the probe axis."""
from . import plot
return plot.plot_noise_spectrum(self, ax, **kwargs)
[docs]
def plot_counts(self, ax=None, **kwargs):
"""Plot accumulation counts as a function of probe delay.
Parameters
----------
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_counts`.
Returns
-------
matplotlib.axes.Axes
"""
from . import plot
return plot.plot_counts(self, ax, **kwargs)
[docs]
def plot_surface(self, ax=None, **kwargs):
"""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 :func:`pymorgan.oneD.plot.plot_surface`; see there for the
full list (``rstride``/``cstride``, ``elev``/``azim``, ``Yscale``,
``cmap_ID``, ...).
Returns
-------
mpl_toolkits.mplot3d.axes3d.Axes3D
"""
from . import plot
return plot.plot_surface(self, ax, **kwargs)
[docs]
def plot_spectra(self, plot_delays, ax=None, fig=None, **kwargs):
"""Transient spectra at the requested delays.
Parameters
----------
plot_delays : sequence of float
Delays to cut at, in this dataset's time unit. Each is snapped to
the nearest measured delay, so approximate values are fine.
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_spectra`, which documents
them all. Commonly used: ``doSmooth`` (box-filter width; negative
also draws the raw trace), ``normY``, ``roundT``, ``x_axis_unit``,
``secondary_axis``, ``Abs``/``Em`` (steady-state overlays) and
``show_xlabel``/``show_ylabel``.
Returns
-------
matplotlib.axes.Axes
Examples
--------
>>> data.plot_spectra([0.5, 1, 5, 50, 500], doSmooth=3, roundT=True)
"""
from . import plot
return plot.plot_spectra(self, plot_delays, ax, fig, **kwargs)
[docs]
def plot_background(self, ax=None, fig=None, **kwargs):
"""Pre-zero background spectrum, drawn with the transient-spectra rules.
Parameters
----------
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_background` (``doSmooth``,
``normY``, ``colour``, ``title``, ``x_axis_unit``, ...).
Returns
-------
matplotlib.axes.Axes
Raises
------
ValueError
If no background has been computed; run :meth:`background_correct`
first (``do_correct=False`` stores it without subtracting).
"""
from . import plot
return plot.plot_background(self, ax, fig, **kwargs)
[docs]
def plot_kinetics(self, plot_wavelengths, ax=None, fig=None, **kwargs):
"""Kinetic traces at the requested probe positions.
Parameters
----------
plot_wavelengths : sequence of float
Probe positions to cut at, in this dataset's native probe unit (nm,
cm-1, ...). Each is snapped to the nearest pixel.
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_kinetics`. Commonly used:
``plotStyle`` (format string, e.g. ``"-"``), ``Xscale``, ``normY``,
``lw``/``ms`` and ``show_xlabel``/``show_ylabel``.
Returns
-------
ax : matplotlib.axes.Axes
t : numpy.ndarray
Delay axis, shape ``[Ndelays]``.
Y : numpy.ndarray
Extracted traces, shape ``[Ndelays x Ncuts]`` — the same data that
was plotted, ready to export or fit.
Examples
--------
>>> ax, t, Y = data.plot_kinetics([2132, 2218], plotStyle="-", lw=1.5)
"""
from . import plot
return plot.plot_kinetics(self, plot_wavelengths, ax, fig, **kwargs)
[docs]
def plot_scan_kinetics(self, plot_wavelengths, ax=None, fig=None, **kwargs):
"""Per-scan kinetic traces at the requested probe positions.
Diagnostic for scan-to-scan reproducibility; requires single-scan data
(see :attr:`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; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_scan_kinetics`; most often
``binsize`` (scans averaged per trace), ``Xscale`` and ``normY``.
Returns
-------
ax : matplotlib.axes.Axes
t : numpy.ndarray
Delay axis, shape ``[Ndelays]``.
Y : numpy.ndarray
Binned traces, shape ``[Ndelays x Npixels x Nbins]``.
"""
from . import plot
return plot.plot_scan_kinetics(self, plot_wavelengths, ax, fig, **kwargs)
[docs]
def plot_scan_spectra(self, plot_delays, ax=None, fig=None, **kwargs):
"""Per-scan transient spectra at the requested delays.
Spectral counterpart of :meth:`plot_scan_kinetics`; requires single-scan
data (see :attr:`has_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; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_scan_spectra`; most often
``binsize``, ``doSmooth`` and ``normY``.
Returns
-------
matplotlib.axes.Axes
"""
from . import plot
return plot.plot_scan_spectra(self, plot_delays, ax, fig, **kwargs)
[docs]
def plot_species_spectra(
self, Sfit, Taus, TauErr, isFixTau, modelType, ax=None, fig=None, **kwargs
):
"""EAS/SAS from a global-analysis fit.
Parameters
----------
Sfit : numpy.ndarray
Component amplitude spectra, shape ``[Npixels x Ncomponents]``.
Taus : sequence of float
Fitted lifetime of each component.
TauErr : sequence of float
Uncertainty on each lifetime.
isFixTau : sequence of bool
Per-component flag marking lifetimes held fixed in the fit.
modelType : str
Kinetic model used, which decides the EAS / SAS wording.
ax : matplotlib.axes.Axes, optional
Axis to draw into; ``None`` creates a new figure.
fig : matplotlib.figure.Figure, optional
Figure owning ``ax``; inferred from ``ax`` when omitted.
**kwargs
Passed to :func:`pymorgan.oneD.plot.plot_species_spectra`
(``printErrors``, ``normY``, ``doSmooth``, ``Abs``/``Em``, ...).
Returns
-------
matplotlib.axes.Axes
Notes
-----
The ``Sfit`` / ``Taus`` / ``TauErr`` inputs come from a global-analysis
fit, which PyMORGAN does not perform — see the companion project
**PyRATE-TA**. This method is the rendering half of that seam and takes
plain arrays, so it is independent of how the fit was obtained.
"""
from . import plot
return plot.plot_species_spectra(
self, Sfit, Taus, TauErr, isFixTau, modelType, ax, fig, **kwargs
)
# ----------------------------------------------------------------- #
# Chirp correction #
# ----------------------------------------------------------------- #
[docs]
def fit_chirp_automatic(self, **kwargs):
"""VARPRO coherent-artefact + Cauchy dispersion fit.
See :func:`pymorgan.oneD.chirp.fit_chirp_automatic`.
"""
from . import chirp
return chirp.fit_chirp_automatic(self, **kwargs)
[docs]
def fit_chirp_step(self, **kwargs):
"""Gaussian(+derivatives)+erf-step fit, restricted to an early-time window.
See :func:`pymorgan.oneD.chirp.fit_chirp_step`.
"""
from . import chirp
return chirp.fit_chirp_step(self, **kwargs)
[docs]
def fit_chirp_wavelet(self, **kwargs):
"""Wavelet-based edge-detection fit at every probe pixel + Cauchy dispersion fit.
See :func:`pymorgan.oneD.chirp.fit_chirp_wavelet`.
"""
from . import chirp
return chirp.fit_chirp_wavelet(self, **kwargs)
[docs]
def fit_chirp_manual(self, points, **kwargs):
"""Cauchy dispersion fit to manually-picked ``(wavelength, delay)`` points.
See :func:`pymorgan.oneD.chirp.fit_chirp_manual`.
"""
from . import chirp
return chirp.fit_chirp_manual(self, points, **kwargs)
[docs]
def plot_chirp_diagnostics(self, fit, **kwargs):
"""Review figures for a chirp fit. See :func:`pymorgan.oneD.chirp.plot_chirp_diagnostics`."""
from . import chirp
return chirp.plot_chirp_diagnostics(self, fit, **kwargs)
[docs]
def apply_chirp_correction(
self, fit, detector: int | None = None, boundary_handling: str | None = None
) -> None:
"""Apply a loaded :class:`ChirpFit` to correct the dispersion in this dataset.
Interpolates all active signals (raw, corrected, stdv, and single scans)
for the given detector onto the same time-delay grid.
Boundary handling options are:
- "crop" -> Option 2: Slices/crops the delays axis to keep only fully finite regions where all pixels are defined.
- "extrapolate" -> Option 1: Fills out-of-bound values with the nearest valid boundary endpoint value (no NaNs).
"""
import pymorgan.settings as settings_mod
if boundary_handling is None:
boundary_handling = settings_mod.get_settings().chirp_boundary_handling.value
if detector is None:
detector = getattr(fit, "detector", 0)
det = int(detector)
bh = str(boundary_handling)
def _do():
probe_det = self._detector_probe(det)
t0fit = fit(probe_det) # shape: [Npixels]
Npixels = probe_det.size
extrapolate = bh == "extrapolate"
def interpolate_array_3d(arr):
if arr is None:
return None
arr_new = arr.copy()
if arr.ndim == 2:
for i in range(Npixels):
lv = arr[0, i] if extrapolate else np.nan
rv = arr[-1, i] if extrapolate else np.nan
arr_new[:, i] = np.interp(
self.delays, self.delays - t0fit[i], arr[:, i], left=lv, right=rv
)
elif arr.ndim == 3:
for i in range(Npixels):
lv = arr[0, i, det] if extrapolate else np.nan
rv = arr[-1, i, det] if extrapolate else np.nan
arr_new[:, i, det] = np.interp(
self.delays, self.delays - t0fit[i], arr[:, i, det], left=lv, right=rv
)
return arr_new
def interpolate_array_4d(arr):
if arr is None:
return None
arr_new = arr.copy()
Nscans = arr.shape[3] if arr.ndim == 4 else arr.shape[2]
if arr.ndim == 3:
for s in range(Nscans):
for i in range(Npixels):
lv = arr[0, i, s] if extrapolate else np.nan
rv = arr[-1, i, s] if extrapolate else np.nan
arr_new[:, i, s] = np.interp(
self.delays, self.delays - t0fit[i], arr[:, i, s], left=lv, right=rv
)
elif arr.ndim == 4:
for s in range(Nscans):
for i in range(Npixels):
lv = arr[0, i, det, s] if extrapolate else np.nan
rv = arr[-1, i, det, s] if extrapolate else np.nan
arr_new[:, i, det, s] = np.interp(
self.delays,
self.delays - t0fit[i],
arr[:, i, det, s],
left=lv,
right=rv,
)
return arr_new
self.Zavg_R = interpolate_array_3d(self.Zavg_R)
if self.Zavg_C is not None:
self.Zavg_C = interpolate_array_3d(self.Zavg_C)
if self.Zstdv is not None:
self.Zstdv = interpolate_array_3d(self.Zstdv)
if self.Zss_R is not None:
self.Zss_R = interpolate_array_4d(self.Zss_R)
if self.Zss_C is not None:
self.Zss_C = interpolate_array_4d(self.Zss_C)
if bh == "crop":
# Crop/slice delays axis to fully finite region (exclude introduced NaNs)
t0_min = np.nanmin(t0fit) if np.any(np.isfinite(t0fit)) else 0.0
t0_max = np.nanmax(t0fit) if np.any(np.isfinite(t0fit)) else 0.0
valid_indices = (self.delays >= np.nanmin(self.delays) - t0_min) & (
self.delays <= np.nanmax(self.delays) - t0_max
)
self.delays = self.delays[valid_indices]
self.Zavg_R = self.Zavg_R[valid_indices, :, :]
if self.Zavg_C is not None:
self.Zavg_C = self.Zavg_C[valid_indices, :, :]
if self.Zstdv is not None:
self.Zstdv = self.Zstdv[valid_indices, :, :]
if self.Zss_R is not None:
self.Zss_R = self.Zss_R[valid_indices, :, :, :]
if self.Zss_C is not None:
self.Zss_C = self.Zss_C[valid_indices, :, :, :]
self.chirp_fit = fit
chirp_file = getattr(fit, "chirp_file", None)
if not chirp_file:
fit_src = getattr(fit, "source", None)
if (
fit_src
and fit_src != self.source
and Path(str(fit_src)).suffix.lower() in (".mat", ".h5", ".hdf5", ".json")
):
chirp_file = str(fit_src)
inline_chirp = {
"mode": str(getattr(fit, "mode", "manual")),
"coeffs": np.asarray(getattr(fit, "coeffs", []), dtype=float).tolist(),
"fit_wl": np.asarray(getattr(fit, "fit_wl", []), dtype=float).tolist(),
"n_cauchy_terms": int(getattr(fit, "n_cauchy_terms", 6)),
"lambda_ref": float(getattr(fit, "lambda_ref", 500.0)),
"detector": int(getattr(fit, "detector", 0)),
}
step_params: dict[str, Any] = {
"detector": det,
"boundary_handling": bh,
"inline_chirp": inline_chirp,
}
if chirp_file:
step_params["chirp_file"] = str(chirp_file)
self._history.record_call(self, "apply_chirp_correction", _do, params=step_params)
[docs]
def embed_calibrated_probe(
self,
csv_path: str | PathLike | None = None,
*,
backup_original: bool = True,
) -> dict[str, Any]:
"""Embed a ``CalibratedProbe.csv`` probe axis directly inside the source ``.h5`` file."""
from .. import helpers as hlp
from .load import embed_calibrated_probe_h5
if not self.source:
raise ValueError(
"Dataset source path is not set; cannot embed calibration into HDF5."
)
src = Path(self.source)
if src.suffix.lower() not in (".h5", ".hdf5"):
raise ValueError(f"Dataset source is not an HDF5 (.h5) file: {src.name}")
def _do():
res = embed_calibrated_probe_h5(src, csv_path, backup_original=backup_original)
if len(self.probe) == len(res["probe"]):
self.probe = res["probe"].copy()
cur_T = self.units.get("T") or self.units.get("unitsT_ltx", "ps")
cur_Z = self.units.get("Z") or self.units.get("unitsZ", "x1E3")
self.units.update(hlp.units2dic(res["unitsL"], cur_T, cur_Z))
self.cal_source = res["cal_source"]
self.units["cal_source"] = res["cal_source"]
self.cal_level = None
self.units.pop("cal_level", None)
return res
return self._history.record_call(
self,
"embed_calibrated_probe",
_do,
params_fn=lambda res: {
"csv_path": (
str(csv_path)
if csv_path is not None
else (str(res["csv_path"]) if isinstance(res, dict) and res.get("csv_path") else None)
),
"backup_original": bool(backup_original),
},
)
[docs]
def load_1D(path: str | PathLike, data_type: str | None = None, **loader_kwargs) -> Dataset1D:
"""Convenience wrapper for :meth:`Dataset1D.from_file`.
When ``data_type`` is ``None`` (default) or ``"auto"``, :func:`pymorgan.detect_format`
infers the format automatically (falling back to ``"PDAT"``). Extra keyword
arguments are forwarded to the selected loader.
"""
return Dataset1D.from_file(path, data_type=data_type, **loader_kwargs)