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.pymorgannever depends on the GUI; the GUI depends onpymorgan.Wraps the ``.mplstyle`` files, does not replace them. A profile selects one of the tuned style files in
plot_styles/andSettings.apply()overlays a lightfont_scalemultiplier on top.matplotlib mathtext only.
Settings.apply()always forcestext.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:
StrEnumDelimiter convention for axis labels, e.g.
Wavelength (nm).- PAREN = '()'#
- BRACKET = '[]'#
- SLASH = '/'#
- BARE = ''#
- class pymorgan.settings.DeltaAUnits(*values)[source]#
Bases:
StrEnumDisplay 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:
StrEnumNamed matplotlib style profile, mapped to a file in
plot_styles/.- REGULAR = 'regular'#
- POSTER = 'poster'#
- INSET = 'inset'#
- class pymorgan.settings.TimeAxisScale(*values)[source]#
Bases:
StrEnumDefault scaling of the delay (time) axis.
- SYMLOG = 'symlog'#
- LOG = 'log'#
- LINEAR = 'lin'#
- class pymorgan.settings.TimeAxisLabel(*values)[source]#
Bases:
StrEnumTick-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:
StrEnum2-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:
StrEnumDisplay unit for the spectral (probe/pump) X axis of spectra/contours.
NATIVEkeeps each dataset’s stored unit; the others convert the axis to nm / cm-1 / eV / THz (seehelpers.convert_spectral()).- NATIVE = 'native'#
- NM = 'nm'#
- WAVENUMBER = 'cm-1'#
- EV = 'eV'#
- THZ = 'THz'#
- class pymorgan.settings.TwoDFreqUnit(*values)[source]#
Bases:
StrEnumDisplay 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 exceedhelpers.DISPLAY_SCALE_THRESHOLDare additionally divided by 1000 and the label gains a10^3prefix, so visible/UV maps read20rather than20000.- WAVENUMBER = 'cm-1'#
- RECIPROCAL_INCH = 'in-1'#
- NM = 'nm'#
- THZ = 'THz'#
- EV = 'eV'#
- class pymorgan.settings.PumpAxis(*values)[source]#
Bases:
StrEnumOrientation of the pump frequency axis: horizontal (default) or vertical.
- HORIZONTAL = 'Horizontal'#
- VERTICAL = 'Vertical'#
- class pymorgan.settings.ChirpBoundaryHandling(*values)[source]#
Bases:
StrEnumBoundary handling convention for chirp correction: crop or extrapolate.
- CROP = 'crop'#
- EXTRAPOLATE = 'extrapolate'#
- class pymorgan.settings.ParallelFittingMode(*values)[source]#
Bases:
StrEnumExecution mode for pixel-by-pixel chirp fitting.
- THREADPOOL = 'threadpool'#
- PROCESSPOOL = 'processpool'#
- DISABLED = 'disabled'#
- class pymorgan.settings.OverlayDrawStyle(*values)[source]#
Bases:
StrEnumDraw style for spectral diffusion (CLS/IvCLS/NLS) overlays.
- POINTS = 'Points'#
- LINES = 'Lines'#
- BOTH = 'Both'#
- class pymorgan.settings.PeakType(*values)[source]#
Bases:
StrEnumTarget peak type for spectral diffusion analysis: min (bleach/SE) or max (ESA).
- MIN = 'min'#
- MAX = 'max'#
- class pymorgan.settings.PeakInterpolation(*values)[source]#
Bases:
StrEnumInterpolation 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:
StrEnumFormat 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 just1.0 ps(number and unit only)- T2_EQ = 't2='#
- PLAIN = 'plain'#
- class pymorgan.settings.TracesCmap(*values)[source]#
Bases:
StrEnumColourmap 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:
StrEnumPlotting 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_specscan offer real choices instead of a hard-coded list. KeepsGUI_THEMESas the fallback for headless use.
- 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:
objectContainer 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)
font_scale (float)
label_style (LabelStyle)
delta_a_units (DeltaAUnits)
cmap (str)
traces_cmap (TracesCmap)
white_levels (float)
asinh_pct (float)
n_contours (int)
show_uncertainties (bool)
round_uncertainties (bool)
time_axis_scale (TimeAxisScale)
time_axis_label (TimeAxisLabel)
freq_label (FreqLabel)
pump_axis (PumpAxis)
t2_label_style (T2LabelStyle)
twoD_freq_unit (TwoDFreqUnit)
x_axis_unit (XAxisUnit)
secondary_axis (bool)
round_labels (bool)
quick_plots (bool)
inherit_cut_limits (bool)
load_single_scans (bool)
kinetics_marker_size (float)
kinetics_line_width (float)
label_digits (int)
legend_label_spacing (float)
legend_location (str)
ss_abs_color (str)
ss_em_color (str)
ss_line_width (float)
ss_line_alpha (float)
ss_fill_alpha (float)
ss_plot_mode (SteadyStatePlotMode)
gui_theme (str)
splash_duration (float)
default_datadir (str)
default_oneD_datatype (str)
default_twoD_datatype (str)
default_calibration_datatype (str)
styles_dir (Path | None)
chirp_boundary_handling (ChirpBoundaryHandling)
parallel_fitting (ParallelFittingMode)
prune_legend (bool)
max_legend_entries (float)
solvent_per_pixel_dt (bool)
solvent_per_pixel_scale (bool)
error_shading (bool)
error_shading_alpha (float)
cls_color (str)
ivcls_color (str)
nls_color (str)
overlay_draw_style (OverlayDrawStyle)
overlay_linewidth (float)
sd_intensity_threshold (float)
sd_peak_range (float)
sd_peak_type (PeakType)
sd_interpolation (PeakInterpolation)
sd_interpolation_factor (int)
kubo_ftir_weight (float)
max_recent_dirs (int)
- profile: StyleProfile = 'regular'#
- label_style: LabelStyle = '()'#
- delta_a_units: DeltaAUnits = 'x1E3'#
- traces_cmap: TracesCmap = 'rainbow'#
- time_axis_scale: TimeAxisScale = 'symlog'#
- time_axis_label: TimeAxisLabel = 'power'#
- t2_label_style: T2LabelStyle = 't2='#
- twoD_freq_unit: TwoDFreqUnit = 'cm-1'#
- ss_plot_mode: SteadyStatePlotMode = 'Double Y axis'#
- chirp_boundary_handling: ChirpBoundaryHandling = 'crop'#
- parallel_fitting: ParallelFittingMode = 'processpool'#
- overlay_draw_style: OverlayDrawStyle = 'Both'#
- sd_interpolation: PeakInterpolation = 'quadratic'#
- apply()[source]#
Apply the profile to matplotlib’s global rcParams.
Resets to the profile’s
.mplstyle, overlays thefont_scalemultiplier, and forcestext.usetex = False(mathtext only).- Return type:
None
- units_with_convention(units, delta_a_units=None)[source]#
Return a copy of
unitswith 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:
units (dict)
delta_a_units (DeltaAUnits | None)
- Return type:
- 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:
- classmethod from_dict(data)[source]#
Build a
Settingsfrom a mapping, ignoring unknown keys.Each value is coerced to the field’s declared type (see
_coerce_field());Noneand empty optional paths fall back to the field default.
- classmethod load(path=None)[source]#
Read a
Settingsfrom 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.
- static field_sections()[source]#
Which section of
settings.tomleach 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.
- 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.
- pymorgan.settings.get_default_settings_text()[source]#
Return the raw text of the canonical default settings template.
- Return type:
- 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:
- pymorgan.settings.ensure_settings_file(path=None)[source]#
Ensure that
path(defaulting tosettings_path()) exists and is up to date.If the file does not exist, it is generated from
settings.default.toml. If the file exists, it is checked for any newly introduced settings from the default template. If missing keys are found, they are merged into the file along with their section comments while preserving all existing user modifications.
- 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:
- pymorgan.settings.use_settings(**changes)[source]#
Temporarily override the active settings within a
withblock.
- pymorgan.settings.load_settings(path=None)[source]#
Load settings from
path(defaulting tosettings_path()) and make them active.
- pymorgan.settings.save_settings(path, settings=None)[source]#
Write
settings(or the active settings) topathas TOML.
- pymorgan.settings.apply_style(settings=None)[source]#
Apply
settings(or the active settings) to matplotlib.- Parameters:
settings (Settings | None)
- Return type:
None
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(). Withblock=Falsethe 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": numbers1),2), …"I": uppercase Roman numerals(I),(II), …"i": lowercase Roman numerals(i),(ii), …
Delimiters in
fmtare 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
Textinstances attached to each axis.- Return type:
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(). Withblock=Falsethe 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.
- 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.
- pymorgan.fonts.install_fonts(quiet=False, force_rebuild=True)[source]#
Copy TeX Gyre Heros fonts into Matplotlib’s font directory and update the cache.
- pymorgan.fonts.install_fonts_twice(quiet=False)[source]#
Run font installation twice back-to-back to ensure Matplotlib font cache is rebuilt and verified.
- 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:
- 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.
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.fmt2Dlabel_wavelength(labelStyle, freqLabel, unitsF='nm')[source]#
Format complementary 2-D wavelength axis labels matching
freqLabel.
- pymorgan.helpers.convert_spectral(x, unit_in, unit_out)[source]#
Convert spectral-axis values between nm / cm-1 / eV / THz.
xmay be a scalar or array. Conversion pivots through the wavelength in nm;nmis 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:
- 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:
objectUnit of one dataset axis.
quantityis what the axis measures (“Wavenumber”, “Delay”, …),unitthe machine-readable token (“cm-1”, “ps”, “mOD”),latexthe mathtext used on plots, andscalethe factor the stored values were divided by for display (1000 for an axis shown as 10^3 cm-1, otherwise 1).
- class pymorgan.helpers.DatasetUnits(x, y, z, t2=None)[source]#
Bases:
objectUnits of the axes of a dataset, as reported by
axis_units().x/yare the plotted axes,zthe signal, andt2the population-time axis of a 2-D dataset (Nonein 1-D, where the delay is already one of the plotted axes).
- pymorgan.helpers.signal_axis_unit(units)[source]#
Signal (Z) unit of a dataset, from its unit dictionary.
- Return type:
- pymorgan.helpers.spectral_axis_unit(unit_token, scale=1.0)[source]#
Spectral (probe/pump) axis unit for a unit token such as
"cm-1".
- pymorgan.helpers.delay_axis_unit(units, quantity='Delay')[source]#
Delay / population-time axis unit of a dataset.
- 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.
- 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 withconvert_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.
- 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_unitmay beNoneor"native"(use the dataset’s own unit) or one ofSPECTRAL_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.
- pymorgan.helpers.spectral_precision(values, *, unit=None)[source]#
Return an appropriate decimal-place count for displaying
valuesinunit.
- pymorgan.helpers.format_spectral_value(value, *, unit=None, scaled=False, rounded=True)[source]#
Format a spectral position for trace legends and titles.
- pymorgan.helpers.zero_center_cmap(cmap, n, k)[source]#
Sample
cmapintonbands and force the centralkto the midpoint/zero colour.Can accept a colourmap object or a colourmap name string.
- 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:
- pymorgan.helpers.plain_time_unit(units_or_token)[source]#
Return a clean plain-text time unit label (e.g.
'ps','ns','µs').- Return type:
- 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.
- 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 as8beside an uncertainty of0.02, suggesting a different precision than it has.
- 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
%sof 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_labelsrounds to two significant figures andSettings.label_digitscaps the rest, so a fitted320.95763496398745prints as320, 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’sunitsT_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=Falsegivest_2 = 1.0 ps;Truegives1.0 ps(seeSettings.t2_label_style). The unit follows the magnitude (fs / ps / ns / us).
- 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.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), orall.Accepts
1900, 1950,1:0.1:5(start:step:stop),1:5(unit step, descending allowed) and the wordall, which returns every value ofall_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_unitis provided (e.g.'ps'or'ns'), explicit time-unit suffixes on individual entries (such as500 fs, 1 nsor500fs) are converted intotarget_time_unit. Plain numbers andstart:step:stopranges are interpreted intarget_time_unit.Returns
Nonewhenallwas asked for but noall_valueswas given.