Calibration Engine API (pymorgan.cal)#

Package Overview (pymorgan.cal)#

Spectrometer & Wavelength Calibration routines for PyMORGAN.

This package handles:
  • Optical dispersion mathematical models (Grating, Polynomial Grating, Prism Sellmeier)

  • Non-linear parameter optimisation and axis inversion (scipy.optimize.least_squares)

  • Gaussian probe spectral distribution diagnostics (w0, FWHM)

  • Reference spectra library and experimental spectrum file parsers

  • Multi-detector split & merge calibration tools

Data Structures & Optical Dispersion Models (pymorgan.cal.models)#

Mathematical optical dispersion models and fitting functions for spectrometer calibration.

Supports:
  1. Linear Grating Dispersion Model (UV-Vis and Mid-IR)

  2. Non-Linear Polynomial Grating Model (UniGE TRUVIS-II)

  3. Non-Linear Prism Dispersion Model via Sellmeier Equation for SF10 Glass (UniGE NIR-TA)

pymorgan.cal.models.n_sellmeier_sf10(wavelength_nm)[source]#

Calculate refractive index n(lambda) for SF10 glass using Sellmeier equation.

Parameters:

wavelength_nm (array-like or float) – Wavelength(s) in nanometers.

Returns:

Refractive index n(lambda).

Return type:

array-like or float

pymorgan.cal.models.prism_output_angle(wavelength_nm, theta_in_deg)[source]#

Calculate exit angle theta_out(lambda) from SF10 prism via Snell’s law.

Parameters:
  • wavelength_nm (array-like or float) – Wavelength in nanometers.

  • theta_in_deg (float) – Input incidence angle in degrees.

Returns:

Output deflection angle theta_out in radians.

Return type:

array-like or float

pymorgan.cal.models.prism_pixel_mapping(wavelength_nm, focal_mm, x_shift, theta_in_deg)[source]#

Map reference wavelengths (nm) to pixel indices for SF10 prism spectrometer.

Parameters:
  • wavelength_nm (np.ndarray) – Wavelength values in nm.

  • focal_mm (float) – Effective focal distance in mm (p[0]).

  • x_shift (float) – Pixel offset / shift (p[1]).

  • theta_in_deg (float) – Input incidence angle in degrees (p[2]).

Returns:

Corresponding pixel position array.

Return type:

np.ndarray

pymorgan.cal.models.linear_grating_pixel_mapping(wavelength_nm, central_wl, ppnm, n_pix=128)[source]#

Map reference wavelengths (nm) to pixel indices for a linear diffraction grating.

Parameters:
  • wavelength_nm (np.ndarray) – Wavelength values in nm.

  • central_wl (float) – Central reference wavelength at middle pixel (nm).

  • ppnm (float) – Dispersion in pixels per nm.

  • n_pix (int, default 128) – Total number of pixels on detector.

Returns:

Pixel index values.

Return type:

np.ndarray

pymorgan.cal.models.polynomial_grating_pixel_mapping(wavelength_nm, central_wl, ppnm, c2, c3, n_pix=128)[source]#

Map reference wavelengths (nm) to pixel indices for higher-order grating (TRUVIS-II).

Parameters:
  • wavelength_nm (np.ndarray) – Wavelength values in nm.

  • central_wl (float) – Central / starting reference wavelength (nm).

  • ppnm (float) – Linear dispersion in pixels per nm.

  • c2 (float) – Quadratic dispersion coefficient (x 1e-4).

  • c3 (float) – Cubic dispersion coefficient (x 1e-7).

  • n_pix (int, default 128) – Total number of pixels on detector.

Returns:

Pixel index values.

Return type:

np.ndarray

pymorgan.cal.models.fit_model_eval(params, ref_x, meas_pixels, meas_y, cal_type_code, grating_degree=1, interp_kind='linear')[source]#

Evaluate synthetic measured absorbance from reference spectrum given fit parameters.

Parameters:
  • params (np.ndarray) – Optimisation parameters vector p.

  • ref_x (np.ndarray) – Cut reference spectrum wavelength grid (nm).

  • meas_pixels (np.ndarray) – Experimental pixel numbers (1..Npix).

  • meas_y (np.ndarray) – Experimental absorbance/intensity array.

  • cal_type_code (int) – Calibration type indicator (1..10).

  • grating_degree (int, default 1) – Degree of grating dispersion polynomial (1=Linear, 2=Quadratic, 3=Cubic).

  • interp_kind (str, default "linear") – Pixel interpolator type ("linear" or monotonicity-preserving "pchip").

Returns:

Evaluated model spectrum matched to ref_x wavelength points.

Return type:

np.ndarray

pymorgan.cal.models.convolve_spectrum_gaussian(y, sigma)[source]#

Convolve 1D spectrum intensity/absorbance array with a Gaussian kernel of standard deviation sigma.

Parameters:
  • y (np.ndarray) – Spectral intensity/absorbance values.

  • sigma (float) – Standard deviation of Gaussian smoothing kernel (in samples/pixels).

Returns:

Convolved spectrum array.

Return type:

np.ndarray

Reference & Experimental Spectrum Loaders (pymorgan.cal.load)#

File loaders for reference spectra libraries and experimental calibration measurement files.

class pymorgan.cal.load.ExperimentalData(detector_data, gratings, cwl, file_path, min_wl=None, max_wl=None, wavenumbers=None, wavelengths=None, spectral_range=None)[source]#

Bases: NamedTuple

Container for loaded experimental calibration raw/absorbance spectra.

Parameters:
detector_data: list[ndarray]#

Alias for field number 0

gratings: list[float]#

Alias for field number 1

cwl: list[float]#

Alias for field number 2

file_path: Path#

Alias for field number 3

min_wl: float | None#

Alias for field number 4

max_wl: float | None#

Alias for field number 5

wavenumbers: ndarray | None#

Alias for field number 6

wavelengths: ndarray | None#

Alias for field number 7

spectral_range: str | None#

Alias for field number 8

pymorgan.cal.load.available_calibration_types(name=None, as_dict=False)[source]#

Return available calibration setup types or look up the integer code for a given setup name.

Parameters:
  • name (str, optional) – Setup display name or search query (e.g. “HARPIA”, “fsTA”, “UoS TRIR”) to look up the magic integer code for.

  • as_dict (bool, default False) – If True, return dictionary mapping integer setup code -> display name.

Returns:

  • If name is provided: returns integer calibration code (1..11).

  • If as_dict=True: returns dict mapping {code: display_name}.

  • Otherwise: returns list of display names.

Return type:

int, dict[int, str], or list[str]

class pymorgan.cal.load.ReferenceSpectrum(name, spectral_axis, absorbance, axis_unit)[source]#

Bases: NamedTuple

Container for a standard calibration reference spectrum.

Parameters:
name: str#

Alias for field number 0

spectral_axis: ndarray#

Alias for field number 1

absorbance: ndarray#

Alias for field number 2

axis_unit: str#

Alias for field number 3

pymorgan.cal.load.load_reference_spectrum(file_path)[source]#

Load reference spectrum from CSV/TSV/text file with automatic delimiter and unit detection.

Parameters:

file_path (str or Path) – Path to reference spectrum CSV/text file.

Returns:

Reference spectrum object containing name, spectral axis, absorbance, and unit (“nm” or “cm-1”).

Return type:

ReferenceSpectrum

pymorgan.cal.load.read_numeric_matrix(file_path, default_delimiter=None)[source]#

Read numeric array data from text file, automatically skipping header and metadata rows.

Parameters:
  • file_path (str | Path)

  • default_delimiter (str | None)

Return type:

ndarray

pymorgan.cal.load.parse_meta_file(meta_path, is_ir)[source]#

Parse MESS or generic setup metadata text file (_meta.txt) for grating position, CWL, and axis arrays.

Parameters:
Return type:

dict

pymorgan.cal.load.normalize_spectral_range(spectral_range)[source]#

Normalize spectral range string to canonical form (‘mid-ir’, ‘uv-vis’, ‘nir’, ‘uv’, ‘vis’).

Parameters:

spectral_range (str | None)

Return type:

str | None

pymorgan.cal.load.parse_pymess_calibration_h5(h5_path, spectral_range=None)[source]#

Parse a PyMESS HDF5 (.h5) file for calibration spectrum, grating, CWL, and spectral range.

Parameters:
  • h5_path (Path) – Path to PyMESS .h5 measurement file.

  • spectral_range (str, optional) – Explicit spectral range override (‘mid-ir’, ‘uv-vis’, ‘nir’). If None, auto-detected from HDF5 metadata and axis.

Returns:

Parsed dictionary containing detector_data, grating, cwl, min_wl, max_wl, wn_axis, wl_axis, and spectral_range.

Return type:

dict

pymorgan.cal.load.load_experimental_spectrum(file_path, cal_type_code, blank_file_path=None, spectral_range=None)[source]#

Parse raw measurement data file based on setup type (1..12).

Parameters:
  • file_path (str or Path) – Path to experimental spectrum file.

  • cal_type_code (int) – Calibration setup type code (1..12).

  • blank_file_path (str or Path, optional) – Optional path to blank measurement file for UniGE TA setups.

  • spectral_range (str, optional) – Optional spectral range override for PyMESS (‘mid-ir’, ‘uv-vis’, ‘nir’) or HARPIA (‘uv’, ‘vis’).

Returns:

Loaded detector data arrays, grating settings, and central wavelengths.

Return type:

ExperimentalData

pymorgan.cal.load.load_HARPIA_calibration_spectrum(file_path, spectral_range=None)[source]#

Load Light Conversion HARPIA-TA spectral calibration measurement text file.

Parameters:
  • file_path (str | Path)

  • spectral_range (str | None)

Return type:

ExperimentalData

pymorgan.cal.load.load_PyMESS_calibration_spectrum(file_path, spectral_range=None)[source]#

Load PyMESS HDF5 (.h5) spectral calibration measurement file.

Parameters:
  • file_path (str | Path)

  • spectral_range (str | None)

Return type:

ExperimentalData

Wavelength Axis Fitting & Routing (pymorgan.cal.fit)#

Spectral axis fitting engine using scipy.optimize.least_squares and VARPRO.

class pymorgan.cal.fit.CalibrationResult(wavelength_nm, wavenumber_cm1, fit_params, residuals, ref_x_cut, ref_y_cut, model_y_fit, convolved_ref_y=None, sigma_opt=0.0, exp_corr_y_fit=None, ref_x_full=None, ref_y_full=None, baseline_fit=None, ref_y_corr=None, sample_baseline_px=None, ref_baseline_cut=None, baseline_method='arpls', baseline_target='both', exp_raw_y_fit=None)[source]#

Bases: NamedTuple

Result container for spectrometer wavelength/wavenumber axis calibration.

Parameters:
wavelength_nm: ndarray#

Alias for field number 0

wavenumber_cm1: ndarray#

Alias for field number 1

fit_params: ndarray#

Alias for field number 2

residuals: ndarray#

Alias for field number 3

ref_x_cut: ndarray#

Alias for field number 4

ref_y_cut: ndarray#

Alias for field number 5

model_y_fit: ndarray#

Alias for field number 6

convolved_ref_y: ndarray | None#

Alias for field number 7

sigma_opt: float#

Alias for field number 8

exp_corr_y_fit: ndarray | None#

Alias for field number 9

ref_x_full: ndarray | None#

Alias for field number 10

ref_y_full: ndarray | None#

Alias for field number 11

baseline_fit: ndarray | None#

Alias for field number 12

ref_y_corr: ndarray | None#

Alias for field number 13

sample_baseline_px: ndarray | None#

Alias for field number 14

ref_baseline_cut: ndarray | None#

Alias for field number 15

baseline_method: str#

Alias for field number 16

baseline_target: str#

Alias for field number 17

exp_raw_y_fit: ndarray | None#

Alias for field number 18

pymorgan.cal.fit.prealign_peaks_cross_correlation(meas_y, ref_x_full, ref_y_full, cwl, ppnm_guess)[source]#

Pre-align experimental and reference spectra via template scanning.

Combines normalized 0th-order and 1st-derivative template correlation over ±half-detector-width around cwl so pre-alignment remains robust even under residual baseline curvature.

Parameters:
Return type:

tuple[float, float]

pymorgan.cal.fit.get_default_calibration_params(cal_type_code, spectral_range=None)[source]#

Return default hardware parameters and relative nm bounds for setup (1..12).

Parameters:
  • cal_type_code (int)

  • spectral_range (str | None)

Return type:

dict

pymorgan.cal.fit.fit_wavelength_axis(meas_y, ref_x, ref_y, cal_type_code=2, cwl=None, ppnm_guess=None, min_wl=None, max_wl=None, rel_min_nm=None, rel_max_nm=None, do_fit=True, grating_degree=None, use_cross_corr=False, use_derivative='global', savgol_window=9, convolve_ref=False, spectral_range=None, baseline_method='arpls', baseline_target='both', baseline_smoothness=0.2, baseline_asym_p=0.005, probe_weights=None)[source]#

Optimise dispersion parameters and compute calibrated wavelength/wavenumber axes.

Parameters:
Return type:

CalibrationResult

Gaussian Spectrum Diagnostics & Utilities (pymorgan.cal.spectrum_fit, pymorgan.cal.utils)#

Spectral distribution Gaussian fitting for pump and probe beam profiles.

Extracts peak amplitude, central frequency w0, and Full-Width at Half-Maximum (FWHM) bandwidth.

class pymorgan.cal.spectrum_fit.SpectrumFitResult(amplitude, w0, fwhm, fit_curve, axis_fit)[source]#

Bases: NamedTuple

Result container for pump/probe spectrum Gaussian fit.

Parameters:
amplitude: float#

Alias for field number 0

w0: float#

Alias for field number 1

fwhm: float#

Alias for field number 2

fit_curve: ndarray#

Alias for field number 3

axis_fit: ndarray#

Alias for field number 4

pymorgan.cal.spectrum_fit.gaussian_1d(x, amp, w0, fwhm)[source]#

1D Gaussian profile with full-width at half-maximum (FWHM) parametrization.

Parameters:
  • x (np.ndarray) – Spectral axis (wavenumber or wavelength).

  • amp (float) – Peak amplitude.

  • w0 (float) – Centre frequency / wavelength.

  • fwhm (float) – Full-Width at Half-Maximum.

Returns:

Evaluated Gaussian values.

Return type:

np.ndarray

pymorgan.cal.spectrum_fit.fit_spectrum_gaussian(intensity, spectral_axis, w0_guess=None, fwhm_guess=250.0)[source]#

Fit a 1D Gaussian to a pump or probe spectrum intensity array.

Parameters:
  • intensity (np.ndarray) – Raw or reference intensity array I(x).

  • spectral_axis (np.ndarray) – Spectral axis values x (wavenumbers cm-1 or wavelength nm).

  • w0_guess (float, optional) – Starting estimate for central frequency/wavelength. If None, uses peak location.

  • fwhm_guess (float, default 250.0) – Starting estimate for FWHM bandwidth.

Returns:

Fit amplitude, w0, FWHM, high-density fit curve, and fit axis.

Return type:

SpectrumFitResult

pymorgan.cal.spectrum_fit.fit_probe_spectrum(intensity, spectral_axis, w0_guess=None, fwhm_guess=250.0)#

Fit a 1D Gaussian to a pump or probe spectrum intensity array.

Parameters:
  • intensity (np.ndarray) – Raw or reference intensity array I(x).

  • spectral_axis (np.ndarray) – Spectral axis values x (wavenumbers cm-1 or wavelength nm).

  • w0_guess (float, optional) – Starting estimate for central frequency/wavelength. If None, uses peak location.

  • fwhm_guess (float, default 250.0) – Starting estimate for FWHM bandwidth.

Returns:

Fit amplitude, w0, FWHM, high-density fit curve, and fit axis.

Return type:

SpectrumFitResult

pymorgan.cal.spectrum_fit.ProbeFitResult#

alias of SpectrumFitResult

Utility functions for splitting and merging multi-detector calibration arrays.

pymorgan.cal.utils.split_calibration(merged_cm, split_pixel_idx=None)[source]#

Split a multi-detector merged calibration vector into LHS (Detector 1) and RHS (Detector 2).

Parameters:
  • merged_cm (np.ndarray) – Continuous 1D array of calibrated wavenumbers/wavelengths for combined detectors.

  • split_pixel_idx (int, optional) – Pixel index split boundary. If None, splits at mid-point len(merged_cm) // 2.

Returns:

(lhs_cal, rhs_cal) split calibration arrays.

Return type:

tuple[np.ndarray, np.ndarray]

pymorgan.cal.utils.merge_calibration(det1_cm, det2_cm)[source]#

Merge Detector 1 (LHS) and Detector 2 (RHS) calibration vectors into a single probe array.

Parameters:
  • det1_cm (np.ndarray) – Detector 1 (LHS) calibrated wavenumber/wavelength array.

  • det2_cm (np.ndarray) – Detector 2 (RHS) calibrated wavenumber/wavelength array.

Returns:

Combined merged calibration vector.

Return type:

np.ndarray

pymorgan.cal.utils.save_calibration_file(probe_axis, output_dir, filename='CalibratedProbe.csv', save_timestamped=False, cal_type_code=None, save_mat=None)[source]#

Save calibrated probe vector to CSV file (CalibratedProbe.csv).

When save_mat is True or cal_type_code is in (2, 3, 5) (UniGE fsTA / nsTA / NIR-TA), also writes pix2lam.mat.

Parameters:
  • probe_axis (np.ndarray) – Calibrated wavenumber or wavelength vector (in native detector units).

  • output_dir (str or Path) – Target export directory.

  • filename (str, default "CalibratedProbe.csv") – Primary file name.

  • save_timestamped (bool, default False) – If True, also saves a timestamped copy (e.g. CalibProbe_20260722-2119.csv).

  • cal_type_code (int, optional) – Calibration setup type code (1..11).

  • save_mat (bool, optional) – Explicit override to save pix2lam.mat. If None, auto-activates for UniGE fsTA/nsTA (codes 2, 3, 5).

Returns:

(primary_path, timestamped_path) output file paths.

Return type:

tuple[Path, Path | None]