epyr.baseline module

The epyr.baseline module provides functions for correcting baseline distortions in EPR spectra.

Overview

Baseline correction is essential for EPR spectral analysis. This module provides several algorithms:

  • Polynomial correction: Fits polynomial baselines (constant, linear, quadratic, etc.)

  • Exponential correction: Fits mono- and stretched-exponential decay baselines

  • 2D correction: Specialized algorithms for 2D EPR datasets

Main Functions

1D Baseline Correction

2D Baseline Correction

Usage Examples

Polynomial Baseline Correction

from epyr.baseline import baseline_polynomial
import numpy as np

# Load your EPR data (x, y arrays)
x = np.linspace(3200, 3400, 1000)  # Magnetic field in G
y = epr_spectrum  # Your EPR data

# Linear baseline correction
y_corrected, baseline = baseline_polynomial(y, x_data=x, poly_order=1)

# Exclude signal regions from baseline fit
signal_regions = [(3340, 3360), (3380, 3400)]
y_corrected, baseline = baseline_polynomial(
    y, x_data=x, poly_order=2, exclude_regions=signal_regions
)

Exponential Baseline Correction

from epyr.baseline import baseline_mono_exponential

# For spectra with exponential baseline drift
y_corrected, baseline = baseline_mono_exponential(
    y, x_data=x, exclude_regions=[(3340, 3380)]
)

2D Baseline Correction

from epyr.baseline import baseline_polynomial_2d
import numpy as np

# 2D EPR data (e.g., field vs. angle)
field_axis = np.linspace(3200, 3400, 200)
angle_axis = np.linspace(0, 180, 37)
spectrum_2d = epr_data_2d  # Shape: (37, 200)

# 2D polynomial baseline correction
corrected_2d, baseline_2d = baseline_polynomial_2d(
    spectrum_2d, x_axis=field_axis, y_axis=angle_axis,
    poly_order_x=1, poly_order_y=1
)

Baseline Algorithms

Polynomial Baseline

Fits polynomials of specified order to the baseline:

  • Order 0: Constant offset correction

  • Order 1: Linear drift correction

  • Order 2: Quadratic baseline correction

  • Higher orders: For complex baseline shapes

Exponential Baseline

For spectra with exponential decay components:

  • Mono-exponential: y = A * exp(-x/τ) + C

  • Stretched-exponential: y = A * exp(-(x/τ)^β) + C

Utilities

Complete API

EPyR Tools - Baseline Correction Package

Modern, modular baseline correction for EPR spectroscopy data.

This package provides baseline correction methods designed for EPR data returned by epyr.eprload():

Features:

  • Polynomial correction: For smooth baseline drifts in CW EPR spectra

  • Stretched exponential: For T2 relaxation and echo decay measurements

  • Bi-exponential: For complex decay patterns with multiple components

  • Automatic model selection: Intelligent model choice using AIC/BIC/R² criteria

  • Interactive region selection: Manual region specification with matplotlib widgets

  • 2D baseline correction: Surface fitting for 2D EPR datasets

Quick Start:

```python import epyr

# Load EPR data x, y, params, filepath = epyr.eprload(“data.dsc”)

# Automatic baseline correction (recommended) corrected, baseline, info = epyr.baseline.baseline_auto_1d(x, y, params) print(f”Best model: {info[‘best_model’]}”)

# Or use specific correction methods: corrected, baseline = epyr.baseline.baseline_polynomial_1d(x, y, params, order=3) corrected, baseline = epyr.baseline.baseline_stretched_exponential_1d(x, y, params) corrected, baseline = epyr.baseline.baseline_bi_exponential_1d(x, y, params) ```

Modules:

  • models: Mathematical functions for baseline fitting

  • correction: Core baseline correction algorithms

  • selection: Region selection and masking utilities

  • interactive: Interactive matplotlib widgets for Jupyter

  • auto: Automatic model selection and comparison

epyr.baseline.baseline_polynomial_1d(x, y, params=None, order=2, exclude_center=True, center_fraction=0.3, manual_regions=None, region_mode='exclude', interactive=False)[source]

Polynomial baseline correction for 1D EPR data.

Fits a polynomial to selected baseline regions and subtracts it from the full dataset. Suited to CW EPR spectra with smooth drift.

Parameters:
  • x (np.ndarray or None) – Field axis from epyr.eprload(). If None or length mismatch, falls back to point indices.

  • y (np.ndarray) – 1D spectrum from epyr.eprload().

  • params (dict, optional) – Parameter dictionary from epyr.eprload() (unused for the fit itself; reserved for future axis-aware extensions).

  • order (int, optional) – Polynomial order. Typical range 1-4. Default 2.

  • exclude_center (bool, optional) – Exclude a centred fraction of the data from fitting (where the signal is expected). Default True.

  • center_fraction (float, optional) – Width of the excluded central window, as a fraction of the data. Default 0.3.

  • manual_regions (list of (float, float), optional) – Explicit (x_low, x_high) regions. Combined with region_mode.

  • region_mode ({'exclude', 'include'}, optional) – 'exclude' removes manual_regions from the fit; 'include' keeps only those regions. Default 'exclude'.

  • interactive (bool, optional) – Launch the matplotlib region selector. Requires an interactive backend. Default False.

Returns:

  • corrected (np.ndarray) – Baseline-subtracted spectrum.

  • baseline (np.ndarray) – Fitted polynomial evaluated on the full axis.

Return type:

Tuple[ndarray, ndarray]

Examples

>>> from epyr import eprload, baseline_polynomial_1d
>>> x, y, params, _ = eprload("examples/data/130406SB_CaWO4_Er_CW_5K_20.DSC")
>>> corrected, baseline = baseline_polynomial_1d(x, y, params, order=3)
>>> corrected.shape == y.shape
True

Fit only on user-defined wings (exclude resonance region):

>>> wings = [(3300, 3400), (3550, 3700)]
>>> corrected, _ = baseline_polynomial_1d(
...     x, y, params, order=2,
...     manual_regions=wings, region_mode="include",
... )
epyr.baseline.baseline_polynomial_2d(x, y, params=None, order=1, exclude_center=True, center_fraction=0.3, manual_regions=None, region_mode='exclude', interactive=False, use_real_part=False)[source]

Polynomial baseline correction for 2D EPR data.

Fits a 2D polynomial surface to selected regions and subtracts it from the full dataset. Useful for 2D experiments (DEER, Rabi 2D, etc.).

Parameters:
  • x (np.ndarray, list of np.ndarray, or None) – Axis data from epyr.eprload(). A two-element list [xa, ya] sets both axes. None falls back to indices.

  • y (np.ndarray) – 2D spectrum, shape (ny, nx).

  • params (dict, optional) – Parameter dictionary from epyr.eprload().

  • order (int or (int, int), optional) – Polynomial order. int applies the same order to both axes; a tuple sets (order_x, order_y) independently. Default 1.

  • exclude_center (bool, optional) – Exclude a centred rectangular block of the data from the fit. Default True.

  • center_fraction (float, optional) – Width of that block along each axis, as a fraction. Default 0.3.

  • manual_regions (list of ((x1, x2), (y1, y2)), optional) – Explicit rectangular regions.

  • region_mode ({'exclude', 'include'}, optional) – How to combine manual_regions with the fit mask. Default 'exclude'.

  • interactive (bool, optional) – Launch the matplotlib 2D region selector. Default False.

  • use_real_part (bool, optional) – For complex data, fit on y.real. Default False.

Returns:

  • corrected (np.ndarray) – Baseline-subtracted surface.

  • baseline (np.ndarray) – Fitted polynomial evaluated on the full grid.

Return type:

Tuple[ndarray, ndarray]

Examples

>>> from epyr import eprload, baseline_polynomial_2d
>>> x, y, params, _ = eprload("examples/data/Rabi2D_GdCaWO4_13dB_3057G.DSC")
>>> corrected, baseline = baseline_polynomial_2d(x, y, params, order=(2, 1))
>>> corrected.shape == y.shape
True
epyr.baseline.baseline_stretched_exponential_1d(x, y, params=None, use_real_part=True, exclude_initial=0, exclude_final=0, manual_regions=None, region_mode='exclude', interactive=False, beta_range=(0.01, 5.0), initial_guess=None)[source]

Stretched-exponential baseline correction for 1D EPR data.

Fits and removes a baseline of the form

\[b(x) = \mathrm{offset} + A \exp\!\left[-(x/\tau)^{\beta}\right]\]

Typical use: T2 echo decay envelope removal before peak analysis.

Parameters:
  • x (np.ndarray or None) – Time axis from epyr.eprload(). Falls back to indices if None or length mismatch.

  • y (np.ndarray) – 1D signal from epyr.eprload().

  • params (dict, optional) – Parameter dictionary from epyr.eprload().

  • use_real_part (bool, optional) – For complex y, fit on y.real. Default True.

  • exclude_initial (int, optional) – Drop the first / last N points from the fit. Default 0.

  • exclude_final (int, optional) – Drop the first / last N points from the fit. Default 0.

  • manual_regions (list of (float, float), optional) – Explicit (x_low, x_high) windows.

  • region_mode ({'exclude', 'include'}, optional) – Combine manual_regions with the fit mask. Default 'exclude'.

  • interactive (bool, optional) – Launch the matplotlib region selector. Default False.

  • beta_range ((float, float), optional) – Bounds on the stretching exponent. Default (0.01, 5.0).

  • initial_guess (dict, optional) – Seed values, any subset of {'A', 'tau', 'beta', 'offset'}.

Returns:

  • corrected (np.ndarray) – Baseline-subtracted signal.

  • baseline (np.ndarray) – Fitted baseline on the full axis.

Return type:

Tuple[ndarray, ndarray]

Examples

>>> from epyr import eprload, baseline_stretched_exponential_1d
>>> path = "examples/data/ESEdecay_2D_rotgon_035_07.3K_h80_9.73687GHz_B3.DSC"
>>> x, y, params, _ = eprload(path)
>>> # take a single trace from the 2D dataset
>>> trace = y[0]
>>> corrected, baseline = baseline_stretched_exponential_1d(
...     x[0], trace, params, exclude_initial=5,
... )
>>> corrected.shape == trace.shape
True
epyr.baseline.baseline_bi_exponential_1d(x, y, params=None, use_real_part=True, exclude_initial=0, exclude_final=0, manual_regions=None, region_mode='exclude', interactive=False, tau_ratio_min=2.5, initial_guess=None)[source]

Bi-exponential baseline correction for 1D EPR data.

Fits and removes a baseline of the form

\[b(x) = \mathrm{offset} + A_1 e^{-x/\tau_1} + A_2 e^{-x/\tau_2}\]

Suited to decays with two well-separated relaxation channels.

Parameters:
  • x (np.ndarray or None) – Time axis from epyr.eprload(). Falls back to indices if None.

  • y (np.ndarray) – 1D signal from epyr.eprload().

  • params (dict, optional) – Parameter dictionary from epyr.eprload().

  • use_real_part (bool, optional) – For complex y, fit on y.real. Default True.

  • exclude_initial (int, optional) – Drop the first / last N points from the fit. Default 0.

  • exclude_final (int, optional) – Drop the first / last N points from the fit. Default 0.

  • manual_regions (list of (float, float), optional) – Explicit (x_low, x_high) windows.

  • region_mode ({'exclude', 'include'}, optional) – How to combine manual_regions with the fit mask.

  • interactive (bool, optional) – Launch the matplotlib region selector. Default False.

  • tau_ratio_min (float, optional) – Minimum ratio tau2 / tau1 enforced during fitting to keep the two components separable. Default 2.5.

  • initial_guess (dict, optional) – Seed values, any subset of {'A1', 'tau1', 'A2', 'tau2', 'offset'}.

Returns:

  • corrected (np.ndarray) – Baseline-subtracted signal.

  • baseline (np.ndarray) – Fitted baseline on the full axis.

Return type:

Tuple[ndarray, ndarray]

Examples

>>> from epyr import eprload, baseline_bi_exponential_1d
>>> path = "examples/data/ESEdecay_2D_rotgon_035_07.3K_h80_9.73687GHz_B3.DSC"
>>> x, y, params, _ = eprload(path)
>>> trace = y[0]
>>> corrected, baseline = baseline_bi_exponential_1d(
...     x[0], trace, params, tau_ratio_min=3.0,
... )
>>> corrected.shape == trace.shape
True
epyr.baseline.baseline_auto_1d(x, y, params=None, models=None, selection_criterion='aic', use_real_part=True, exclude_initial=0, exclude_final=0, manual_regions=None, region_mode='exclude', interactive=False, verbose=True)[source]

Automatic baseline model selection and correction for 1D EPR data.

This function tests multiple baseline models and automatically selects the best one based on information criteria (AIC/BIC) or other metrics.

Parameters:
  • x (ndarray | None) – X-axis data from eprload (can be None)

  • y (ndarray) – 1D spectral data array from eprload

  • params (Dict[str, Any] | None) – Parameter dictionary from eprload (optional)

  • models (List[str] | None) – List of models to test. Options: ‘polynomial’, ‘stretched_exponential’, ‘bi_exponential’

  • selection_criterion (str) – ‘aic’ (Akaike), ‘bic’ (Bayesian), or ‘r2’ (R-squared)

  • use_real_part (bool) – If True, fit only real part of complex data

  • exclude_initial (int) – Number of initial points to exclude from fitting

  • exclude_final (int) – Number of final points to exclude from fitting

  • manual_regions (List[Tuple[float, float]] | None) – List of manually selected regions as [(x1, x2), …]

  • region_mode (str) – ‘exclude’ to exclude manual_regions, ‘include’ to use only manual_regions

  • interactive (bool) – If True, open interactive region selector

  • verbose (bool) – If True, print detailed model comparison

Returns:

(corrected_data, best_baseline,

model_info) where model_info contains: {‘best_model’: str, ‘criteria’: dict, ‘parameters’: dict}

Return type:

tuple

Examples

# Automatic model selection corrected, baseline, info = baseline_auto_1d(

x, y, params)

print(f”Best model: {info[‘best_model’]}”)

# Restrict to specific models corrected, baseline, info = baseline_auto_1d(

x, y, params, models=[‘polynomial’,

‘stretched_exponential’])

# Use BIC for model selection corrected, baseline, info = baseline_auto_1d(

x, y, params, selection_criterion=’bic’)

epyr.baseline.stretched_exponential_1d(x, A, tau, beta, offset=0.0)[source]

Stretched-exponential (Kohlrausch-Williams-Watts) decay.

\[y(x) = \mathrm{offset} + A \exp\!\left[-(x/\tau)^{\beta}\right]\]

Commonly used for T2 echo decay in disordered systems.

Parameters:
  • x (np.ndarray) – Independent variable (time, often in microseconds).

  • A (float) – Amplitude.

  • tau (float) – Characteristic decay time, same unit as x.

  • beta (float) – Stretching exponent in (0, 5]. beta = 1 recovers a pure exponential; beta < 1 is sub-exponential; beta > 1 super.

  • offset (float, optional) – Constant baseline. Default 0.

Returns:

Decay values, same shape as x.

Return type:

np.ndarray

Examples

>>> import numpy as np
>>> from epyr.baseline.models import stretched_exponential_1d
>>> t = np.linspace(0, 5, 100)  # microseconds
>>> y = stretched_exponential_1d(t, A=1.0, tau=1.5, beta=0.7)
>>> y[0], round(y[-1], 4)
(1.0, 0.098)
epyr.baseline.bi_exponential_1d(x, A1, tau1, A2, tau2, offset=0.0)[source]

Sum of two exponential decays.

\[y(x) = \mathrm{offset} + A_1 e^{-x/\tau_1} + A_2 e^{-x/\tau_2}\]

Useful when a system has two well-separated relaxation channels.

Parameters:
  • x (np.ndarray) – Independent variable.

  • A1 (float) – Component amplitudes.

  • A2 (float) – Component amplitudes.

  • tau1 (float) – Component decay times, same unit as x. Order does not matter.

  • tau2 (float) – Component decay times, same unit as x. Order does not matter.

  • offset (float, optional) – Constant baseline. Default 0.

Returns:

Decay values.

Return type:

np.ndarray

Examples

>>> import numpy as np
>>> from epyr.baseline.models import bi_exponential_1d
>>> t = np.linspace(0, 10, 200)
>>> y = bi_exponential_1d(t, A1=0.7, tau1=0.5, A2=0.3, tau2=4.0, offset=0.05)
>>> round(y[0], 3), round(y[-1], 4)
(1.05, 0.0747)
epyr.baseline.polynomial_1d(x, *coeffs)[source]

Evaluate a 1D polynomial.

\[y(x) = a_0 + a_1 x + a_2 x^2 + \ldots + a_n x^n\]
Parameters:
  • x (np.ndarray) – Independent variable.

  • *coeffs (float) – Coefficients in ascending order of degree, [a0, a1, ..., an].

Returns:

Polynomial values (float).

Return type:

np.ndarray

Examples

>>> import numpy as np
>>> from epyr.baseline.models import polynomial_1d
>>> x = np.linspace(-1, 1, 5)
>>> polynomial_1d(x, 1.0, 0.0, 2.0)  # 1 + 2*x**2
array([3. , 1.5, 1. , 1.5, 3. ])
epyr.baseline.polynomial_2d(xy, *coeffs)[source]

Evaluate a 2D polynomial surface on flattened coordinates.

The polynomial order is inferred from the number of coefficients: a square layout (order+1)**2 is tried first, falling back to a rectangular (nx+1)*(ny+1) decomposition.

Parameters:
  • xy (tuple of (np.ndarray, np.ndarray)) – Flattened x and y coordinate arrays of identical shape.

  • *coeffs (float) – Polynomial coefficients, ordered as c[i*(order_y+1)+j] for the x**i * y**j term.

Returns:

Flattened surface values, same shape as xy[0].

Return type:

np.ndarray

Raises:

ValueError – If len(coeffs) does not factor as (nx+1)*(ny+1) with nx, ny < 10.

Examples

>>> import numpy as np
>>> from epyr.baseline.models import polynomial_2d
>>> x, y = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5))
>>> z = polynomial_2d((x.ravel(), y.ravel()), 1.0, 2.0, 3.0, 4.0)  # bilinear
>>> z.shape
(25,)
epyr.baseline.exponential_1d(x, A, tau, offset=0.0)[source]

Single exponential decay.

\[y(x) = \mathrm{offset} + A \exp(-x/\tau)\]
Parameters:
  • x (np.ndarray) – Independent variable.

  • A (float) – Amplitude.

  • tau (float) – Decay time, same unit as x.

  • offset (float, optional) – Constant baseline. Default 0.

Returns:

Decay values.

Return type:

np.ndarray

Examples

>>> import numpy as np
>>> from epyr.baseline.models import exponential_1d
>>> t = np.linspace(0, 5, 50)
>>> y = exponential_1d(t, A=1.0, tau=1.0)
>>> round(y[0], 3), round(y[-1], 4)
(1.0, 0.0067)
epyr.baseline.create_region_mask_1d(x, regions, mode='exclude')[source]

Boolean mask for 1D data, marking which points to keep for a fit.

Parameters:
  • x (np.ndarray) – Field or time axis.

  • regions (list of (float, float)) – [(x_low, x_high), ...]. Bounds are inclusive; order within a pair does not matter.

  • mode ({'exclude', 'include'}, optional) – 'exclude' masks out the listed regions (default); 'include' keeps only those regions.

Returns:

True where the point should be used for fitting.

Return type:

np.ndarray of bool

Examples

>>> import numpy as np
>>> from epyr.baseline import create_region_mask_1d
>>> x = np.arange(10)
>>> mask = create_region_mask_1d(x, [(3, 5)], mode="exclude")
>>> mask.astype(int)
array([1, 1, 1, 0, 0, 0, 1, 1, 1, 1])
epyr.baseline.create_region_mask_2d(X, Y, regions, mode='exclude')[source]

Boolean mask for 2D data, marking which points to keep for a fit.

Parameters:
  • X (np.ndarray) – Coordinate meshgrids, identical shape.

  • Y (np.ndarray) – Coordinate meshgrids, identical shape.

  • regions (list of ((float, float), (float, float))) – [((x_lo, x_hi), (y_lo, y_hi)), ...]. Inclusive bounds.

  • mode ({'exclude', 'include'}, optional) – 'exclude' masks out the listed rectangles (default); 'include' keeps only those rectangles.

Returns:

Same shape as X. True where the point should be used.

Return type:

np.ndarray of bool

Examples

>>> import numpy as np
>>> from epyr.baseline import create_region_mask_2d
>>> X, Y = np.meshgrid(np.arange(5), np.arange(5))
>>> mask = create_region_mask_2d(X, Y, [((1, 3), (1, 3))], mode="exclude")
>>> int(mask.sum())  # 25 - 3*3 inner block
16
class epyr.baseline.RegionSelector[source]

Bases: object

Interactive region selector for baseline correction.

This class provides matplotlib-based interactive region selection for both 1D and 2D EPR data. It handles matplotlib version compatibility and provides multiple methods to close selection windows.

__init__()[source]
finish_selection()[source]

Manually finish selection and close plot.

select_regions_1d(x, y, title='Select regions to EXCLUDE from baseline fitting')[source]

Interactive selection of 1D regions.

Parameters:
  • x – X-axis data

  • y – Y-axis data

  • title – Plot title with instructions

Returns:

Selected regions as [(x1, x2), …]

Return type:

list

select_regions_2d(x, y, z, title='Select regions to EXCLUDE from baseline fitting')[source]

Interactive selection of 2D regions.

Parameters:
  • x – X-axis coordinates (1D array or meshgrid)

  • y – Y-axis coordinates (1D array or meshgrid)

  • z – 2D data array

  • title – Plot title with instructions

Returns:

Selected regions as [((x1,x2), (y1,y2)), …]

Return type:

list

epyr.baseline.interactive_select_regions_1d(x, y, title='Select regions to EXCLUDE from baseline fitting')[source]

Convenience function for interactive 1D region selection.

Parameters:
  • x – X-axis data

  • y – Y-axis data

  • title – Plot title

Returns:

Selected regions as [(x1, x2), …]

Return type:

list

epyr.baseline.interactive_select_regions_2d(x, y, z, title='Select regions to EXCLUDE from baseline fitting')[source]

Convenience function for interactive 2D region selection.

Parameters:
  • x – X-axis coordinates

  • y – Y-axis coordinates

  • z – 2D data array

  • title – Plot title

Returns:

Selected regions as [((x1,x2), (y1,y2)), …]

Return type:

list

epyr.baseline.close_selector_window()[source]

Utility function to close RegionSelector windows in Jupyter notebooks.

Use this if the interactive region selector gets stuck or won’t close.

epyr.baseline.jupyter_help()[source]

Display help for using interactive region selection in Jupyter notebooks.

epyr.baseline.is_interactive_available()[source]

Check if interactive selection is available in the current environment.

Returns:

True if interactive selection should work

Return type:

bool

epyr.baseline.setup_interactive_backend()[source]

Set up the best available interactive backend for the current environment.

epyr.baseline.compare_models_detailed(x, y, params=None, models=None, **kwargs)[source]

Fit every candidate baseline model and return detailed metrics.

Parameters:
  • x (np.ndarray or None) – Axis from epyr.eprload(). Falls back to indices if None.

  • y (np.ndarray) – 1D signal.

  • params (dict, optional) – Parameter dictionary from epyr.eprload().

  • models (list of str, optional) – Subset of ['polynomial', 'stretched_exponential', 'bi_exponential']. Default: all three.

  • **kwargs – Passed through to the underlying baseline_* functions (use_real_part, exclude_initial, manual_regions, etc.).

Returns:

{model_name: {'aic': ..., 'r_squared': ..., 'parameters': ...}} for each model that converged.

Return type:

dict

Examples

>>> from epyr import eprload
>>> from epyr.baseline import compare_models_detailed
>>> path = "examples/data/ESEdecay_2D_rotgon_035_07.3K_h80_9.73687GHz_B3.DSC"
>>> x, y, params, _ = eprload(path)
>>> results = compare_models_detailed(x[0], y[0], params)
>>> set(results) <= {"polynomial", "stretched_exponential", "bi_exponential"}
True
epyr.baseline.get_model_recommendations(data_type=None, experiment_type=None)[source]

Suggest baseline models given the experiment type.

Parameters:
  • data_type ({'cw', 'pulsed'}, optional) – Continuous-wave or pulsed EPR.

  • experiment_type (str, optional) – Sub-type when data_type='pulsed'. Known values: 't1', 't2', 'echo', 'rabi', 'nutation'.

Returns:

Recommended model names, in order of preference.

Return type:

list of str

Examples

>>> from epyr.baseline import get_model_recommendations
>>> get_model_recommendations("cw")
['polynomial']
>>> get_model_recommendations("pulsed", "t2")
['stretched_exponential', 'bi_exponential', 'polynomial']
epyr.baseline.auto_baseline_with_recommendations(x, y, params=None, data_type=None, experiment_type=None, **kwargs)[source]

Automatic baseline correction, restricted to models that fit the experiment.

Wraps baseline_auto_1d() after pruning the candidate-model list via get_model_recommendations().

Parameters:
  • x (np.ndarray or None) – Axis from epyr.eprload().

  • y (np.ndarray) – 1D signal.

  • params (dict, optional) – Parameter dictionary from epyr.eprload().

  • data_type ({'cw', 'pulsed'}, optional) – Used to filter the candidate models.

  • experiment_type (str, optional) – Refines the filter for pulsed experiments.

  • **kwargs – Passed through to baseline_auto_1d().

Returns:

  • corrected (np.ndarray)

  • baseline (np.ndarray)

  • info (dict) – Best-model metadata (name, score, parameters, fit metrics).

Return type:

Tuple[ndarray, ndarray, Dict[str, Any]]

Examples

>>> from epyr import eprload
>>> from epyr.baseline import auto_baseline_with_recommendations
>>> x, y, params, _ = eprload(
...     "examples/data/ESEdecay_2D_rotgon_035_07.3K_h80_9.73687GHz_B3.DSC"
... )
>>> corrected, baseline, info = auto_baseline_with_recommendations(
...     x[0], y[0], params, data_type="pulsed", experiment_type="t2", verbose=False,
... )
>>> info["best_model"] in {"polynomial", "stretched_exponential", "bi_exponential"}
True
epyr.baseline.get_model_function(model_name, dimension='1d')[source]

Return the callable for a registered model.

Parameters:
  • model_name (str) – Key from MODEL_INFO ('polynomial', 'stretched_exponential', 'bi_exponential', 'exponential').

  • dimension ({'1d', '2d'}, optional) – Function variant. Most models only provide '1d'; only the polynomial model supports '2d'. Default '1d'.

Returns:

The model function, ready to pass to scipy.optimize.curve_fit.

Return type:

callable

Raises:

ValueError – If model_name is unknown or the requested dimension variant does not exist.

Examples

>>> from epyr.baseline.models import get_model_function
>>> f = get_model_function("stretched_exponential")
>>> f.__name__
'stretched_exponential_1d'
epyr.baseline.list_available_models()[source]

Return the names of registered baseline models.

Returns:

Model keys usable with get_model_function() and MODEL_INFO.

Return type:

list of str

Examples

>>> from epyr.baseline.models import list_available_models
>>> sorted(list_available_models())
['bi_exponential', 'exponential', 'polynomial', 'stretched_exponential']
epyr.baseline.get_baseline_regions_1d(x, y, exclude_center=True, center_fraction=0.3, exclude_initial=0, exclude_final=0, manual_regions=None, region_mode='exclude')[source]

Build a 1D baseline mask combining all exclusion criteria.

Parameters:
  • x (ndarray) – X-coordinate array

  • y (ndarray) – Y-data array

  • exclude_center (bool) – Whether to exclude center region

  • center_fraction (float) – Fraction of center to exclude

  • exclude_initial (int) – Number of initial points to exclude

  • exclude_final (int) – Number of final points to exclude

  • manual_regions (List[Tuple[float, float]] | None) – List of manually specified regions

  • region_mode (str) – How to handle manual_regions (‘exclude’ or ‘include’)

Returns:

Boolean mask array for baseline fitting

Return type:

ndarray

epyr.baseline.get_baseline_regions_2d(X, Y, Z, exclude_center=True, center_fraction=0.3, manual_regions=None, region_mode='exclude')[source]

Build a 2D baseline mask combining all exclusion criteria.

Parameters:
  • X (ndarray) – X-coordinate meshgrid

  • Y (ndarray) – Y-coordinate meshgrid

  • Z (ndarray) – Z-data array

  • exclude_center (bool) – Whether to exclude center region

  • center_fraction (float) – Fraction of center to exclude

  • manual_regions (List[Tuple[Tuple[float, float], Tuple[float, float]]] | None) – List of manually specified regions

  • region_mode (str) – How to handle manual_regions (‘exclude’ or ‘include’)

Returns:

Boolean mask array for baseline fitting

Return type:

ndarray

epyr.baseline.validate_regions_1d(regions, x_min, x_max)[source]

Validate that 1D regions are within data bounds and properly formatted.

Parameters:
  • regions (List[Tuple[float, float]]) – List of region tuples

  • x_min (float) – Minimum x value in data

  • x_max (float) – Maximum x value in data

Returns:

True if all regions are valid

Raises:

ValueError – If regions are invalid

Return type:

bool

epyr.baseline.validate_regions_2d(regions, x_min, x_max, y_min, y_max)[source]

Validate that 2D regions are within data bounds and properly formatted.

Parameters:
Returns:

True if all regions are valid

Raises:

ValueError – If regions are invalid

Return type:

bool

epyr.baseline.setup_inline_backend()[source]

Set up inline backend for static plots in Jupyter.

epyr.baseline.setup_widget_backend()[source]

Set up widget backend for interactive plots in Jupyter.

epyr.baseline.setup_notebook_backend()[source]

Set up notebook backend for interactive plots in Jupyter.

epyr.baseline.configure(**kwargs)[source]

Configure default settings for baseline correction.

Parameters:
  • polynomial_order – Default polynomial order (default: 2)

  • beta_range – Default beta range for stretched exponentials (default: (0.01, 5.0))

  • selection_criterion – Default criterion for automatic selection (default: ‘aic’)

  • center_fraction – Default center exclusion fraction (default: 0.3)

  • interactive_backend – Preferred matplotlib backend (default: ‘auto’)

epyr.baseline.get_configuration()[source]

Get current default settings.