Settings, Display & Helpers API#

Settings (pymorgan.settings)#

Centralised plotting/aesthetics settings for PyMORGAN.

This module is the single source of truth for presentation choices that are not intrinsic to the data: the matplotlib style profile, font scaling, axis- label convention, the delta-absorbance unit convention, the default colourmap and the default time-axis scale.

Design notes#

  • Framework-agnostic. Nothing here imports Qt. The PyQt6 GUI binds to the fields described by Settings.field_specs() (each field carries its type and, for enums, its allowed values), so combo boxes can be generated automatically. pymorgan never depends on the GUI; the GUI depends on pymorgan.

  • Wraps the ``.mplstyle`` files, does not replace them. A profile selects one of the tuned style files in plot_styles/ and Settings.apply() overlays a light font_scale multiplier on top.

  • matplotlib mathtext only. Settings.apply() always forces text.usetex = False; LaTeX text rendering is never enabled.

  • Global default + per-call override. A module-level active settings object is read by the plotting methods; individual calls may still override any field locally.

class pymorgan.settings.LabelStyle(*values)[source]#

Bases: StrEnum

Delimiter convention for axis labels, e.g. Wavelength (nm).

PAREN = '()'#
BRACKET = '[]'#
SLASH = '/'#
BARE = ''#
class pymorgan.settings.DeltaAUnits(*values)[source]#

Bases: StrEnum

Display convention for the (numerically identical) signal axis.

The stored data is always in mOD; this toggle only changes the label.

MOD = 'mOD'#
SCALED = 'x1E3'#
class pymorgan.settings.StyleProfile(*values)[source]#

Bases: StrEnum

Named matplotlib style profile, mapped to a file in plot_styles/.

REGULAR = 'regular'#
POSTER = 'poster'#
INSET = 'inset'#
class pymorgan.settings.TimeAxisScale(*values)[source]#

Bases: StrEnum

Default scaling of the delay (time) axis.

SYMLOG = 'symlog'#
LOG = 'log'#
LINEAR = 'lin'#
class pymorgan.settings.TimeAxisLabel(*values)[source]#

Bases: StrEnum

Tick-label format for the (log/symlog) delay axis of 1-D contour plots.

Only affects how powers of ten are rendered; the scale itself is set by TimeAxisScale.

POWER -> 10^0, 10^1, 10^2 … DECIMAL -> 0.1, 1, 10, 100 … MIXED -> 1, 10^1, 10^2 … (10^0 shown as a plain “1”)

POWER = 'power'#
DECIMAL = 'decimal'#
MIXED = 'mixed'#
class pymorgan.settings.FreqLabel(*values)[source]#

Bases: StrEnum

2-D frequency-axis labelling convention (pump = omega_1, probe = omega_3).

OMEGA_N = 'Omega_n'#
OMEGA_PP = 'Omega_PP'#
PUMP_PROBE = 'Pump-Probe'#
OMEGA_2PIC = 'Omega_n/2pic'#
class pymorgan.settings.XAxisUnit(*values)[source]#

Bases: StrEnum

Display unit for the spectral (probe/pump) X axis of spectra/contours.

NATIVE keeps each dataset’s stored unit; the others convert the axis to nm / cm-1 / eV / THz (see helpers.convert_spectral()).

NATIVE = 'native'#
NM = 'nm'#
WAVENUMBER = 'cm-1'#
EV = 'eV'#
THZ = 'THz'#
class pymorgan.settings.TwoDFreqUnit(*values)[source]#

Bases: StrEnum

Display unit for the pump/probe axes of 2-D spectra.

The data is stored in wavenumbers; the axes are converted on the fly (see helpers.to_display_axis()). Axes whose values exceed helpers.DISPLAY_SCALE_THRESHOLD are additionally divided by 1000 and the label gains a 10^3 prefix, so visible/UV maps read 20 rather than 20000.

WAVENUMBER = 'cm-1'#
RECIPROCAL_INCH = 'in-1'#
NM = 'nm'#
THZ = 'THz'#
EV = 'eV'#
class pymorgan.settings.PumpAxis(*values)[source]#

Bases: StrEnum

Orientation of the pump frequency axis: horizontal (default) or vertical.

HORIZONTAL = 'Horizontal'#
VERTICAL = 'Vertical'#
class pymorgan.settings.ChirpBoundaryHandling(*values)[source]#

Bases: StrEnum

Boundary handling convention for chirp correction: crop or extrapolate.

CROP = 'crop'#
EXTRAPOLATE = 'extrapolate'#
class pymorgan.settings.ParallelFittingMode(*values)[source]#

Bases: StrEnum

Execution mode for pixel-by-pixel chirp fitting.

THREADPOOL = 'threadpool'#
PROCESSPOOL = 'processpool'#
DISABLED = 'disabled'#
class pymorgan.settings.OverlayDrawStyle(*values)[source]#

Bases: StrEnum

Draw style for spectral diffusion (CLS/IvCLS/NLS) overlays.

POINTS = 'Points'#
LINES = 'Lines'#
BOTH = 'Both'#
class pymorgan.settings.PeakType(*values)[source]#

Bases: StrEnum

Target peak type for spectral diffusion analysis: min (bleach/SE) or max (ESA).

MIN = 'min'#
MAX = 'max'#
class pymorgan.settings.PeakInterpolation(*values)[source]#

Bases: StrEnum

Interpolation method to locate sub-pixel peaks.

QUADRATIC = 'quadratic'#
CUBIC = 'cubic'#
QUARTIC = 'quartic'#
GAUSSIAN = 'gaussian'#
LORENTZIAN = 'lorentzian'#
NONE = 'none'#
class pymorgan.settings.T2LabelStyle(*values)[source]#

Bases: StrEnum

Format of the t_2 delay indicator text box in 2-D contour plots.

T2_EQ -> shows t_2 = 1.0 ps (full equation notation) PLAIN -> shows just 1.0 ps (number and unit only)

T2_EQ = 't2='#
PLAIN = 'plain'#
class pymorgan.settings.TracesCmap(*values)[source]#

Bases: StrEnum

Colourmap convention for kinetic and spectral trace plots.

RAINBOW -> rainbow RAINBOW_REVERSED -> rainbow reversed RED_PURPLE_BLUE -> red-purple-blue

RAINBOW = 'rainbow'#
RAINBOW_REVERSED = 'rainbow reversed'#
RED_PURPLE_BLUE = 'red-purple-blue'#
class pymorgan.settings.SteadyStatePlotMode(*values)[source]#

Bases: StrEnum

Plotting mode when both steady-state absorption and emission are displayed.

DOUBLE_Y -> Twin X with separate Y axes (left absorbance, right emission intensity) NORMALISED -> Both spectra normalised to their maximum (1.0) on a single shared Y axis

DOUBLE_Y = 'Double Y axis'#
NORMALISED = 'Normalise to maximum'#
pymorgan.settings.register_gui_themes(names)[source]#

Publish the Qt styles available on this machine to the settings panel.

Called by the GUI (which owns the Qt dependency) so field_specs can offer real choices instead of a hard-coded list. Keeps GUI_THEMES as the fallback for headless use.

Return type:

list[str]

pymorgan.settings.gui_theme_choices()[source]#

Qt styles currently offered in the settings panel.

Return type:

list[str]

class pymorgan.settings.Settings(profile=StyleProfile.REGULAR, font_scale=1.0, label_style=LabelStyle.PAREN, delta_a_units=DeltaAUnits.SCALED, cmap='DkRd/Wh/DkBu', traces_cmap=TracesCmap.RAINBOW, white_levels=2.0, asinh_pct=5.0, n_contours=40, show_uncertainties=True, round_uncertainties=True, time_axis_scale=TimeAxisScale.SYMLOG, time_axis_label=TimeAxisLabel.POWER, freq_label=FreqLabel.OMEGA_N, pump_axis=PumpAxis.HORIZONTAL, t2_label_style=T2LabelStyle.T2_EQ, twoD_freq_unit=TwoDFreqUnit.WAVENUMBER, x_axis_unit=XAxisUnit.NATIVE, secondary_axis=False, round_labels=True, quick_plots=False, inherit_cut_limits=True, load_single_scans=True, kinetics_marker_size=4.0, kinetics_line_width=1.5, label_digits=3, legend_label_spacing=0.25, legend_location='outside right', contour_figsize=(7.5, 5.5), kinetics_figsize=(7.5, 4.375), spectra_figsize=(7.5, 4.375), ss_abs_color='b', ss_em_color='r', ss_line_width=1.5, ss_line_alpha=0.15, ss_fill_alpha=0.05, ss_line_dashes=(4.0, 3.0), ss_plot_mode=SteadyStatePlotMode.DOUBLE_Y, gui_theme='Fusion', splash_duration=0.0, default_datadir='', default_oneD_datatype='MESS_TRIR', default_twoD_datatype='MESS_2DIR', default_calibration_datatype='UniGE TRIR (Intensity)', styles_dir=None, chirp_boundary_handling=ChirpBoundaryHandling.CROP, parallel_fitting=ParallelFittingMode.PROCESSPOOL, prune_legend=True, max_legend_entries=15.0, solvent_per_pixel_dt=False, solvent_per_pixel_scale=True, error_shading=False, error_shading_alpha=0.2, cls_color='w', ivcls_color='y', nls_color='r', overlay_draw_style=OverlayDrawStyle.BOTH, overlay_linewidth=1.5, sd_intensity_threshold=0.5, sd_peak_range=30.0, sd_peak_type=PeakType.MIN, sd_interpolation=PeakInterpolation.QUADRATIC, sd_interpolation_factor=2, kubo_ftir_weight=1.0, recent_dirs=<factory>, max_recent_dirs=12)[source]#

Bases: object

Container for all presentation-level settings.

All fields are plain values or enums so the object round-trips cleanly to TOML and is trivially introspectable by the GUI.

Parameters:
profile: StyleProfile = 'regular'#
font_scale: float = 1.0#
label_style: LabelStyle = '()'#
delta_a_units: DeltaAUnits = 'x1E3'#
cmap: str = 'DkRd/Wh/DkBu'#
traces_cmap: TracesCmap = 'rainbow'#
white_levels: float = 2.0#
asinh_pct: float = 5.0#
n_contours: int = 40#
show_uncertainties: bool = True#
round_uncertainties: bool = True#
time_axis_scale: TimeAxisScale = 'symlog'#
time_axis_label: TimeAxisLabel = 'power'#
freq_label: FreqLabel = 'Omega_n'#
pump_axis: PumpAxis = 'Horizontal'#
t2_label_style: T2LabelStyle = 't2='#
twoD_freq_unit: TwoDFreqUnit = 'cm-1'#
x_axis_unit: XAxisUnit = 'native'#
secondary_axis: bool = False#
round_labels: bool = True#
quick_plots: bool = False#
inherit_cut_limits: bool = True#
load_single_scans: bool = True#
kinetics_marker_size: float = 4.0#
kinetics_line_width: float = 1.5#
label_digits: int = 3#
legend_label_spacing: float = 0.25#
legend_location: str = 'outside right'#
contour_figsize: tuple[float, float] = (7.5, 5.5)#
kinetics_figsize: tuple[float, float] = (7.5, 4.375)#
spectra_figsize: tuple[float, float] = (7.5, 4.375)#
ss_abs_color: str = 'b'#
ss_em_color: str = 'r'#
ss_line_width: float = 1.5#
ss_line_alpha: float = 0.15#
ss_fill_alpha: float = 0.05#
ss_line_dashes: tuple[float, float] = (4.0, 3.0)#
ss_plot_mode: SteadyStatePlotMode = 'Double Y axis'#
gui_theme: str = 'Fusion'#
splash_duration: float = 0.0#
default_datadir: str = ''#
default_oneD_datatype: str = 'MESS_TRIR'#
default_twoD_datatype: str = 'MESS_2DIR'#
default_calibration_datatype: str = 'UniGE TRIR (Intensity)'#
styles_dir: Path | None = None#
chirp_boundary_handling: ChirpBoundaryHandling = 'crop'#
parallel_fitting: ParallelFittingMode = 'processpool'#
prune_legend: bool = True#
max_legend_entries: float = 15.0#
solvent_per_pixel_dt: bool = False#
solvent_per_pixel_scale: bool = True#
error_shading: bool = False#
error_shading_alpha: float = 0.2#
cls_color: str = 'w'#
ivcls_color: str = 'y'#
nls_color: str = 'r'#
overlay_draw_style: OverlayDrawStyle = 'Both'#
overlay_linewidth: float = 1.5#
sd_intensity_threshold: float = 0.5#
sd_peak_range: float = 30.0#
sd_peak_type: PeakType = 'min'#
sd_interpolation: PeakInterpolation = 'quadratic'#
sd_interpolation_factor: int = 2#
kubo_ftir_weight: float = 1.0#
recent_dirs: list[str]#
max_recent_dirs: int = 12#
property style_path: Path#

Absolute path to the .mplstyle file for the active profile.

apply()[source]#

Apply the profile to matplotlib’s global rcParams.

Resets to the profile’s .mplstyle, overlays the font_scale multiplier, and forces text.usetex = False (mathtext only).

Return type:

None

units_with_convention(units, delta_a_units=None)[source]#

Return a copy of units with the delta-A label convention applied.

Only the signal-axis labels are changed; the data is never rescaled. Non delta-absorbance signals (e.g. intensity) are returned unchanged.

Parameters:
Return type:

dict

to_dict()[source]#

Return a JSON/TOML-friendly mapping of the settings.

Derived from the dataclass fields: enums are written as their value, paths and tuples as strings / lists. Optional fields that are None (styles_dir) are omitted so they keep their default when read back.

Return type:

dict

classmethod from_dict(data)[source]#

Build a Settings from a mapping, ignoring unknown keys.

Each value is coerced to the field’s declared type (see _coerce_field()); None and empty optional paths fall back to the field default.

Parameters:

data (dict)

Return type:

Settings

save(path)[source]#

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

Parameters:

path (str | Path)

Return type:

None

classmethod load(path=None)[source]#

Read a Settings from a TOML file.

Ensures the settings file exists (creating from defaults if absent) and merges any newly introduced settings while keeping user modifications. Accepts both the sectioned layout ([plot], [axes], …) and the older flat one, so an existing settings.toml keeps working.

Parameters:

path (str | Path | None)

Return type:

Settings

static field_sections()[source]#

Which section of settings.toml each field is written to.

The grouping is the one the file already used as comment headers, so a hand-edited file keeps its shape when the GUI saves over it. A field missing from this map is written at the top level, which an older flat file also produces and load() still reads.

Return type:

dict[str, str]

classmethod field_specs()[source]#

Describe the editable fields for GUI widget generation.

Each entry gives a human label, the widget kind, and (for choices) the allowed values, so a PyQt6 front-end can build combo boxes / spin boxes without hard-coding the option lists. An optional "tooltip" is shown on the generated widget.

Return type:

dict[str, dict]

pymorgan.settings.get_default_settings_text()[source]#

Return the raw text of the canonical default settings template.

Return type:

str

pymorgan.settings.get_default_settings_doc()[source]#

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

pymorgan.settings.settings_path()[source]#

Locate or determine the standard path for settings.toml.

Checks the current working directory first. If not found, checks the project root (if running from a repository source tree). When running as a packaged standalone executable without a local settings.toml, uses ~/.config/pymorgan/settings.toml.

Return type:

Path

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

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

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

Parameters:

path (str | Path | None)

Return type:

Path

pymorgan.settings.get_settings()[source]#

Return the active Settings object.

Return type:

Settings

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

Replace the active settings and return it.

Parameters:

settings (Settings)

Return type:

Settings

pymorgan.settings.update_settings(**changes)[source]#

Mutate the active settings in place via keyword overrides.

Enum fields accept either an enum member or its string value (the GUI settings panel passes the string). The mapping of field to enum class is derived from the dataclass annotations, so it cannot fall out of date.

Return type:

Settings

pymorgan.settings.use_settings(**changes)[source]#

Temporarily override the active settings within a with block.

Return type:

Iterator[Settings]

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

Load settings from path (defaulting to settings_path()) and make them active.

Parameters:

path (str | Path | None)

Return type:

Settings

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

Write settings (or the active settings) to path as TOML.

Parameters:
Return type:

None

pymorgan.settings.apply_style(settings=None)[source]#

Apply settings (or the active settings) to matplotlib.

Parameters:

settings (Settings | None)

Return type:

None

pymorgan.settings.record_recent_dir(path, *, save=True)[source]#

Record path as most-recently used in settings.recent_dirs.

Parameters:
Return type:

list[str]

pymorgan.settings.clear_recent_dirs(*, save=True)[source]#

Clear settings.recent_dirs and optionally persist to disk.

Parameters:

save (bool)

Return type:

list[str]

Display & Fonts (pymorgan.display, pymorgan.fonts)#

Thin convenience wrappers around matplotlib’s figure display.

Kept tiny and import-light: matplotlib is only imported when a function is actually called.

pymorgan.display.show_plots(*, block=True)[source]#

Display all open matplotlib figures.

Equivalent to matplotlib.pyplot.show(). With block=False the call returns immediately (useful inside an event loop / GUI), otherwise it blocks until the figure windows are closed.

Parameters:

block (bool)

Return type:

None

pymorgan.display.close_plots()[source]#

Close all open matplotlib figures (plt.close('all')).

Return type:

None

pymorgan.display.add_subplot_labels(axes, *, fmt='(a)', position='top-left', inside=True, pad=0.05, size=None, order='row-first', bbox=None, **kwargs)[source]#

Automatically add subplot labels like (a), (b), (c) to a sequence or grid of matplotlib axes.

Parameters:
  • axes (sequence of matplotlib.axes.Axes or ndarray of Axes) – Target axes to label. Can be a 1D sequence or a multidimensional array returned by plt.subplots(...).

  • fmt (str, default "(a)") –

    Label format template. Recognized format tokens:

    • "a" : lowercase letters (a), (b), … (aa)

    • "A" : uppercase letters (A), (B), …

    • "1" : numbers 1), 2), …

    • "I" : uppercase Roman numerals (I), (II), …

    • "i" : lowercase Roman numerals (i), (ii), …

    Delimiters in fmt are preserved (e.g. "a)", "A.", "[1]").

  • position (str, default "top-left") – Position of the label relative to the axes boundary. Allowed values: "top-left" (or "tl"), "top-right" ("tr"), "bottom-left" ("bl"), "bottom-right" ("br"), "top-centre" ("tc"), "bottom-centre" ("bc").

  • inside (bool, default True) – If True, place the label inside the axes frame using inward padding. If False, place the label outside the axes frame.

  • pad (float or tuple of float, default 0.05) – Padding distance from axes edges in fractional axes units (0.0 to 1.0). Can be a single float or a (x_pad, y_pad) tuple.

  • size (float or str, optional) – Font size of the labels. Defaults to plt.rcParams["axes.labelsize"] (matching the current plot’s axis label size setting).

  • order (str, default "row-first") –

    Order to traverse 2D arrays of axes:

    • "row-first" / "C" : row by row (top to bottom, left to right)

    • "column-first" / "F" : column by column (top to bottom, left to right)

  • bbox (dict, optional) – Dictionary of bounding box properties passed to ax.text (e.g., dict(boxstyle="square,pad=0.2", facecolor="white", edgecolor="none")).

  • **kwargs – Additional keyword arguments forwarded to matplotlib.axes.Axes.text (e.g., fontweight="bold", color="black", zorder=10).

Returns:

List of created Text instances attached to each axis.

Return type:

list of matplotlib.text.Text

Examples

>>> import matplotlib.pyplot as plt
>>> import pymorgan as pm
>>> fig, axes = plt.subplots(2, 2)
>>> pm.add_subplot_labels(axes, fmt="(a)", position="top-left")
>>> pm.add_subplot_labels(axes, fmt="A)", position="top-right", inside=False)
pymorgan.display.show(*, block=True)#

Display all open matplotlib figures.

Equivalent to matplotlib.pyplot.show(). With block=False the call returns immediately (useful inside an event loop / GUI), otherwise it blocks until the figure windows are closed.

Parameters:

block (bool)

Return type:

None

Font installation helper for PyMORGAN.

Locates TeX Gyre Heros fonts from a MiKTeX / TeX Live installation or the rinoh-typeface-texgyreheros package and copies them into Matplotlib’s font directory, then clears the font cache.

Usage#

After installing PyMORGAN:

pymorgan-install-fonts

Or from Python:

from pymorgan.fonts import install_fonts
install_fonts()
pymorgan.fonts.ensure_persistent_mplconfigdir()[source]#

Override PyInstaller’s ephemeral MPLCONFIGDIR so Matplotlib’s font cache persists.

Return type:

None

pymorgan.fonts.available_preferred_fonts()[source]#

Return which of PREFERRED_FONTS Matplotlib can currently resolve.

Return type:

list[str]

pymorgan.fonts.find_heros_fonts()[source]#

Locate TeX Gyre Heros font files.

First searches PyMORGAN’s bundled package assets. Next searches system LaTeX installations (MiKTeX, TeX Live). If none are found, falls back to the rinoh-typeface-texgyreheros package.

Return type:

list[Path]

pymorgan.fonts.install_fonts(quiet=False, force_rebuild=True)[source]#

Copy TeX Gyre Heros fonts into Matplotlib’s font directory and update the cache.

Parameters:
Return type:

None

pymorgan.fonts.install_fonts_twice(quiet=False)[source]#

Run font installation twice back-to-back to ensure Matplotlib font cache is rebuilt and verified.

Parameters:

quiet (bool)

Return type:

bool

pymorgan.fonts.are_fonts_installed()[source]#

Check whether TeX Gyre Heros fonts have already been installed for Matplotlib.

Performs a fast multi-stage check: 1. Checks for a receipt flag in Matplotlib’s cache directory (< 0.1 ms). 2. Checks whether TeX Gyre Heros files exist in Matplotlib’s fonts directory (< 1 ms). 3. Checks whether TeX Gyre Heros is loaded in Matplotlib’s active font manager.

Return type:

bool

pymorgan.fonts.ensure_fonts_installed(quiet=True)[source]#

Ensure TeX Gyre Heros fonts are available in Matplotlib.

If fonts are already verified, does nothing. Otherwise, runs the font installation twice from bundled package assets, rinoh dependency, or system TeX installations to ensure the font cache is completely rebuilt.

Returns True if at least one preferred font is available, False otherwise.

Parameters:

quiet (bool)

Return type:

bool

pymorgan.fonts.main()[source]#
Return type:

None

Helpers (pymorgan.helpers)#

pymorgan.helpers.find_nearest(X, q, unique=False)[source]#

Find the closest element in vector X from the query vector q.

Parameters: - X: numpy array, the vector to search in. - q: scalar or numpy array, the query vector.

Returns: - Xq: scalar or numpy array, the closest element(s) in X to q. - ID: integer or numpy array, the index(es) of the closest element(s) in X.

pymorgan.helpers.setXYlabels(where, labelStyle, XUnits, YUnits, normX=False, normY=False, setXLabel=True, setYLabel=True)[source]#
pymorgan.helpers.fmtZlabel(labelStyle, unitsZ_lbl, unitsZ_ltx, twoLines=False)[source]#
pymorgan.helpers.fmt2Dlabel(labelStyle, freqLabel, unitsF)[source]#
pymorgan.helpers.fmt2Dlabel_wavelength(labelStyle, freqLabel, unitsF='nm')[source]#

Format complementary 2-D wavelength axis labels matching freqLabel.

pymorgan.helpers.units2dic(unitsL, unitsT, unitsZ)[source]#
pymorgan.helpers.convert_spectral(x, unit_in, unit_out)[source]#

Convert spectral-axis values between nm / cm-1 / eV / THz.

x may be a scalar or array. Conversion pivots through the wavelength in nm; nm is reciprocal to the energy-like units, the others are mutually proportional. Non-positive entries map to +/-inf (guarded, no warning).

pymorgan.helpers.native_x_unit(Units)[source]#

Return the dataset’s native spectral-axis unit token from its Units dict.

pymorgan.helpers.is_uncalibrated_probe(units_or_dataset)[source]#

Return True when a dataset or Units dict uses uncalibrated pixel indices for its probe axis.

Return type:

bool

pymorgan.helpers.complementary_unit(unit)[source]#

Complementary unit for the secondary axis.

cm-1 <-> nm; every other unit (nm, eV, THz) pairs with nm.

class pymorgan.helpers.AxisUnit(quantity, unit, latex, scale=1.0)[source]#

Bases: object

Unit of one dataset axis.

quantity is what the axis measures (“Wavenumber”, “Delay”, …), unit the machine-readable token (“cm-1”, “ps”, “mOD”), latex the mathtext used on plots, and scale the factor the stored values were divided by for display (1000 for an axis shown as 10^3 cm-1, otherwise 1).

Parameters:
quantity: str#
unit: str#
latex: str#
scale: float = 1.0#
label(style='()')[source]#

Axis label in the delimiter convention of Settings.label_style.

Parameters:

style (str)

Return type:

str

class pymorgan.helpers.DatasetUnits(x, y, z, t2=None)[source]#

Bases: object

Units of the axes of a dataset, as reported by axis_units().

x/y are the plotted axes, z the signal, and t2 the population-time axis of a 2-D dataset (None in 1-D, where the delay is already one of the plotted axes).

Parameters:
x: AxisUnit#
y: AxisUnit#
z: AxisUnit#
t2: AxisUnit | None = None#
as_dict()[source]#

Plain nested mapping, e.g. for export or serialisation.

Return type:

dict[str, dict]

pymorgan.helpers.signal_axis_unit(units)[source]#

Signal (Z) unit of a dataset, from its unit dictionary.

Return type:

AxisUnit

pymorgan.helpers.spectral_axis_unit(unit_token, scale=1.0)[source]#

Spectral (probe/pump) axis unit for a unit token such as "cm-1".

Parameters:
Return type:

AxisUnit

pymorgan.helpers.delay_axis_unit(units, quantity='Delay')[source]#

Delay / population-time axis unit of a dataset.

Parameters:

quantity (str)

Return type:

AxisUnit

pymorgan.helpers.display_scale(values, threshold=5000.0)[source]#

Return the 1e3 display factor for an axis, or 1.0.

Visible/UV axes run to a few 10^4 cm-1 (or in-1); dividing them by 1000 keeps the tick labels readable. Wavelength/energy/frequency axes stay well below the threshold and are therefore never rescaled.

Parameters:

threshold (float)

pymorgan.helpers.scaled_unit_label(unit, factor=1.0)[source]#

Mathtext unit string, prefixed with the 1e3 factor when one is applied.

Parameters:

factor (float)

Return type:

str

pymorgan.helpers.to_display_axis(values, unit_in, unit_out=None, threshold=5000.0)[source]#

Convert a spectral axis for display and apply the 1e3 rule.

Returns (values_out, factor, unit_ltx): the converted and rescaled values, the factor they were divided by, and the mathtext unit string to put in the axis label. Coordinates that must share the axis (limits, overlay points) are converted with convert_spectral() and divided by the same factor.

Parameters:

threshold (float)

pymorgan.helpers.is_electronic_2d(pump, probe, native_unit='cm-1', *, threshold=5000.0)[source]#

Return True when a 2-D dataset spans the electronic (NIR/Vis/UV) spectral range.

Parameters:
Return type:

bool

pymorgan.helpers.x_unit_label(unit)[source]#

Return (quantity_label, mathtext_unit) for a spectral-unit token.

pymorgan.helpers.resolve_x_unit(x_axis_unit, native_unit)[source]#

Resolve the effective display unit from a setting and the native unit.

x_axis_unit may be None or "native" (use the dataset’s own unit) or one of SPECTRAL_UNITS.

pymorgan.helpers.plain_spectral_unit(unit_token, *, scaled=False)[source]#

Return a clean plain-text spectral unit label for GUI prompts and read-outs.

Parameters:
Return type:

str

pymorgan.helpers.spectral_precision(values, *, unit=None)[source]#

Return an appropriate decimal-place count for displaying values in unit.

Parameters:

unit (str | None)

Return type:

int

pymorgan.helpers.format_spectral_value(value, *, unit=None, scaled=False, rounded=True)[source]#

Format a spectral position for trace legends and titles.

Parameters:
Return type:

str

pymorgan.helpers.zero_center_cmap(cmap, n, k)[source]#

Sample cmap into n bands and force the central k to the midpoint/zero colour.

Can accept a colourmap object or a colourmap name string.

pymorgan.helpers.CalcCMAP(cmap_str='DkRd/Wh/DkBu', Ntot=40, Nwhite=2)[source]#
pymorgan.helpers.get_trace_cmap(cmap_spec='rainbow', n_colors=10, reverse=False)[source]#

Return an array of RGBA colours for plotting N trace lines.

Parameters:
  • cmap_spec (str or TracesCmap, default "rainbow") – Colourmap specification: "rainbow", "rainbow reversed", or "red-purple-blue". Can also be any valid Matplotlib colourmap name.

  • n_colors (int, default 10) – Number of colours to sample.

  • reverse (bool, default False) – Reverse the colour sampling order.

Returns:

Array of shape (n_colors, 4) containing RGBA colours.

Return type:

numpy.ndarray

pymorgan.helpers.plain_time_unit(units_or_token)[source]#

Return a clean plain-text time unit label (e.g. 'ps', 'ns', 'µs').

Return type:

str

pymorgan.helpers.ConvertTimeUnits(t_in, Unit_in, Unit_out=None, roundT=False)[source]#
pymorgan.helpers.round_to_uncertainty(value, err)[source]#

Round a value and its uncertainty so the pair reads sensibly.

The uncertainty goes to one significant figure and the value to that same decimal place, so a fitted constant is never quoted with more precision than its own uncertainty supports:

325.3 +/- 2.5   ->  325 +/- 3
326.3 +/- 3     ->  326 +/- 3
297.5 +/- 1.38  ->  298 +/- 1
8.036 +/- 0.023 ->  8.04 +/- 0.02

A non-finite or non-positive uncertainty leaves both untouched: there is nothing to round to.

Returns:

The rounded value and uncertainty.

Return type:

(float, float)

pymorgan.helpers.format_uncertainty_pair(value, err)[source]#

(value, uncertainty) as strings, rounded together and matched.

Both are written to the same decimal place, so the pair reads as one measurement: ("325", "3"), ("8.04", "0.02"). Without this the value would print as 8 beside an uncertainty of 0.02, suggesting a different precision than it has.

Return type:

tuple[str, str | None]

pymorgan.helpers.format_lifetime_label(tau, unit_in, err=None, *, roundT=None, fixed=False, pair_round=False, settings=None)[source]#

A lifetime as it should appear in a legend: 320 fs, 8.0 ± 0.2 ps.

Handles the three things a raw %s of the number does not:

  • the unit follows the magnitude (via ConvertTimeUnits()), so a sub-picosecond lifetime of a picosecond dataset reads in fs;

  • the digits are bounded – Settings.round_labels rounds to two significant figures and Settings.label_digits caps the rest, so a fitted 320.95763496398745 prints as 320, not as the full float;

  • a non-decaying component prints as \(\infty\), since it has no lifetime to round.

The uncertainty is converted into the same unit as the value before it is shown, and is omitted for a fixed parameter – a fixed lifetime has no uncertainty, and printing one would invent a result.

Parameters:
  • tau (float) – Lifetime in unit_in. Non-finite means non-decaying.

  • unit_in (str) – Time unit of tau (the dataset’s unitsT_ltx).

  • err (float, optional) – 1-sigma uncertainty, in the same unit as tau.

  • roundT (bool, optional) – Round to two significant figures. Defaults to Settings.round_labels.

  • fixed (bool, default False) – Suppress the uncertainty (the parameter was not fitted).

  • pair_round (bool, default False) – Round the value together with its uncertainty (round_to_uncertainty()), so neither is quoted more precisely than the other supports. Applied after the unit conversion, since the rounding depends on the displayed magnitude.

pymorgan.helpers.print2Ddelay(t2_ps, onlyNumbers=False)[source]#

Format a t2 delay for the 2-D contour text box.

onlyNumbers=False gives t_2 = 1.0 ps; True gives 1.0 ps (see Settings.t2_label_style). The unit follows the magnitude (fs / ps / ns / us).

pymorgan.helpers.box_smooth(y, box_pts)[source]#
pymorgan.helpers.uniform_smooth(y, npts)[source]#
pymorgan.helpers.adjust_lightness(colour, scale=1)[source]#

Scale the lightness of an RGB(A) colour, keeping hue and saturation.

Equivalent to seaborn.set_hls_values(colour, l=lightness), without the seaborn import (which pulls in scipy.stats and pandas at start-up).

pymorgan.helpers.adjust_cmap(cmap, scale=1)[source]#
pymorgan.helpers.ApplyMasks(mask_rgns, X)[source]#
pymorgan.helpers.add_glow(ax, x, y, colour=None, base_frac=0.04, *, color=None)[source]#

Adds a soft glow around a curve. Thickness adapts automatically to axis y-range.

pymorgan.helpers.parse_value_list(text, all_values=None, *, target_time_unit=None)[source]#

Parse the cut-list syntax: numbers, range expressions (start:step:stop), or all.

Accepts 1900, 1950, 1:0.1:5 (start:step:stop), 1:5 (unit step, descending allowed) and the word all, which returns every value of all_values. Unparseable tokens are logged and skipped rather than aborting the whole list – a typo in one of five cuts should not throw away the other four.

When target_time_unit is provided (e.g. 'ps' or 'ns'), explicit time-unit suffixes on individual entries (such as 500 fs, 1 ns or 500fs) are converted into target_time_unit. Plain numbers and start:step:stop ranges are interpreted in target_time_unit.

Returns None when all was asked for but no all_values was given.

Parameters:
  • text (str)

  • target_time_unit (str | None)

Return type:

list[float] | None