autoemx.core.fitter.fitter module

X-ray Spectrum Fitting Module

Created on Thu Jun 27 10:17:26 2024

@author: Andrea Giunto

This module provides classes and functions for physically-accurate modeling, fitting, and analysis of X-ray energy-dispersive spectroscopy (EDS) spectra.

Overview

The module is designed to enable robust, quantitative analysis of EDS spectra, including background continuum, detector response, and detailed peak shapes (including escape and pileup peaks, ICC effects, and low-energy tails). It is suitable for both bulk and particle samples, and supports flexible calibration and constraint schemes.

Class Structure and Interactions

The main classes are:

  • XSp_Fitter The main workflow class. Given a measured spectrum, calibration information, and a list of elements, it builds the complete lmfit model (background + peaks), sets up all parameters and constraints, and runs the fit. It provides methods for plotting, reporting, and extracting fit results. This class orchestrates the use of all other classes and should be the main entry point for typical users.

  • Peaks_Model Manages the construction and parameterization of all spectral peaks (characteristic X-ray lines, escape peaks, pileup peaks, etc.). It supports advanced peak shapes (e.g., skewed/tail Gaussians, ICC convolution), constraints between related peaks, and caching for efficient repeated use. It is typically instantiated by the spectrum fitter and used to build the composite peak model.

  • Background_Model Handles the computation and parameterization of the spectral background, including physical effects such as X-ray generation, absorption, detector efficiency, and backscattering. Used to build the background component of the overall spectral model.

  • DetectorResponseFunction Provides static and class methods for handling the detector’s instrumental response, including convolution matrices for energy resolution and incomplete charge collection (ICC). This class is initialized with calibration data and is used by both background and peak models to accurately simulate detector effects.

Typical Usage

  1. Initialize the fitter:

    fitter = XSp_Fitter(
        spectrum_vals, energy_vals, els_to_quantify=['Fe', 'Ni'], microscope_ID='PhenomXL'
    )
    
  2. Fit the spectrum:

    fit_result, fitted_lines = fitter.fit_spectrum(plot_result=True, print_result=True)
    
  3. Inspect and use results: Use fit_result for detailed analysis. Plot or print results using fitter.plot_result() and fitter.print_result(). Access fitted parameters, background components, and diagnostic information.

Customization & Calibration

Detector calibration, physical constants, and peak shape calibration are handled via the calibs module and are loaded automatically based on the specified microscope and EDS mode. Advanced users may customize which peaks are freely calibrated, which are constrained, and how background/peak models are parameterized by modifying the relevant class parameters or by subclassing.

Dependencies

numpy, scipy, lmfit, matplotlib, and supporting modules for calibration and physical constants.

How the classes interact

  • XSp_Fitter is the main user-facing class. It creates and coordinates instances of Background_Model and Peaks_Model, and uses DetectorResponseFunction to ensure all detector effects are handled consistently.

  • DetectorResponseFunction is a utility class used by both Background_Model and Peaks_Model to convolve model components with the detector response.

  • Peaks_Model and Background_Model each build their respective parts of the overall spectrum model, which are then combined by the fitter for the full fit.

In short

Instantiate XSp_Fitter with your data and settings, then call fit_spectrum(). The module will handle background, detector response, and peak modeling for you, providing a comprehensive, physically-based EDS spectrum fit.

autoemx.core.fitter.fitter.patch_lmfit_fast_mode(verbose=False)[source]

Disable all covariance/uncertainty computations globally in lmfit.

autoemx.core.fitter.fitter.get_reference_xray_line(el, line, el_xRays_dict, xray_quant_ref_lines)[source]

Determines the reference X-ray line of a given characteristic line, i.e. the line of the same family whose fitted area sets the area of line through the line weights. Reference lines are their own reference, and their area is fitted freely.

Parameters:
  • el (str) – Element symbol.

  • line (str) – Line name (e.g. ‘Kb1’).

  • el_xRays_dict (dict) – X-ray lines of the element (from get_el_xray_lines).

  • xray_quant_ref_lines (sequence of str) – Reference lines used for quantification (e.g. XSp_Quantifier.xray_quant_ref_lines).

Returns:

Reference line, as ‘{el}_{line}’.

Return type:

str

class autoemx.core.fitter.fitter.XSp_Fitter(spectrum_vals, energy_vals, spectrum_lims, microscope_ID, meas_mode, det_ch_offset, det_ch_width, beam_e, emergence_angle, fit_background=True, is_particle=False, els_to_quantify=None, els_substrate=None, els_w_fr=None, force_fr_total=True, tot_sp_counts=None, sp_collection_time=None, xray_quant_ref_lines=None, print_evolving_params=False, verbose=False, free_area_el_lines=None, free_peak_shape_els=None, free_peak_shape_params=None, free_background_params=None)[source]

Bases: object

Fitter for EDS spectra.

Handles EDS spectral fitting, including background modeling, element quantification, and correction for experimental conditions.

Variables:
  • spectrum_vals (array-like) – Measured spectrum intensity values.

  • energy_vals (array-like) – Corresponding energy values (in keV).

  • els_to_quantify (list of str) – Elements to quantify in the sample.

  • els_w_fr (dict) – Elements with fixed mass fractions.

  • els_substrate (list of str) – Elements present in the substrate.

  • fit_background (bool) – Whether to fit a background continuum.

  • xray_quant_ref_lines (tuple of str) – X-ray lines used for quantification.

  • is_particle (bool) – If True, fit considers absorption and mass effect of particles.

  • microscope_ID (str) – Identifier for microscope calibration and detector efficiency.

  • meas_mode (str) – EDS acquisition mode.

  • spectrum_lims (tuple) – Spectrum limits.

  • force_fr_total (bool) – Normalize total fitted elemental fraction to 1 if True.

  • beam_energy (float) – Beam energy in keV.

  • emergence_angle (float) – X-ray emergence angle in degrees.

  • tot_sp_counts (int or None) – Total spectrum counts.

  • sp_collection_time (float or None) – Spectrum collection time in seconds.

  • print_evolving_params (bool) – Print evolving fit parameters (for debugging).

  • verbose (bool) – Verbose output.

escape_peaks_str = '_escSiKa'
pileup_peaks_str = '_pileup'
fit_spectrum(parameters=None, initial_par_vals=None, function_tolerance=0.001, plot_result=False, print_result=False, print_result_extended=False, n_iter=None)[source]

Fit the EDS spectrum using lmfit.

Parameters:
  • parameters (lmfit.Parameters, optional) – Parameters object to use for fitting. If None, parameters are generated internally.

  • initial_par_vals (dict, optional) – Dictionary of initial parameter values to override defaults.

  • function_tolerance (float, optional) – ftol used in scipy.optimize.leastsq (default: 1e-3).

  • plot_result (bool, optional) – Whether to plot the fitted spectrum (total fit and background).

  • print_result (bool, optional) – Whether to print the quality of the fit.

  • print_result_extended (bool, optional) – Whether to print extended fit results.

  • n_iter (int, optional) – Iteration number (for display purposes).

Returns:

  • fit_result (lmfit.ModelResult) – Contains all information about the result of the fit.

  • fitted_lines (list of str) – List of fitted X-ray lines.

plot_result()[source]

Plot the fitted EDS spectrum and its individual background components.

print_result(extended=False, print_only_independent_params=False)[source]

Print a summary of the fit results.