autoemx.core.quantifier.quantifier module
X-ray Spectrum Quantification Module
Created on Thu Jun 27 14:23:22 2024
@author: Andrea Giunto
This module provides classes and functions for matrix correction and quantitative analysis of X-ray spectra, implementing the peak-to-background (P/B) method and related ZAF corrections for scanning electron microscopy (SEM) energy-dispersive X-ray spectroscopy (EDS).
Class Structure and Interactions
The main classes are:
XSp_Quantifier Performs quantification of X-ray spectra using matrix corrections. Interfaces with spectral fitting routines from XSp_Fitter to extract peak/background intensities and applies the full suite of correction factors from Quant_Corrections to obtain quantitative elemental concentrations. Additionally provides functions to plot and print the results.
Quant_Corrections Provides methods for calculating matrix correction factors (Z, A, R) for the P/B method. This class is instanced by XSp_Quantifier to calculate the matrix correction factors.
Typical Usage
- Initialize the quantifier object:
quantifier = XSp_Quantifier(…) # See class docs for initialization
- Quantify a spectrum:
- quant_result = quantifier.quantify_spectrum()
quant_result contains quantified atomic and weight fractions, analytical error, and spectral fitting metrics (reduced chi-square, and R-squared).
- Print quantification results:
quantifier.print_quant_result(quant_result)
- Plot spectrum:
quantifier.plot_quantified_spectrum()
Customization & Calibration
Detector calibration, physical constants, and mass absorption coefficients are handled via the calibs module and supporting utility functions. Users should calibrate the values in the calibs module corresponding to their microscope and EDS settings prior usage.
Dependencies
numpy, scipy, sympy, pandas lmfit, pymatgen.core.Element (from supporting libraries) XSp_Fitter (required for spectral fitting; see separate module) calibs, lib modules
How the classes interact
XSp_Quantifier is the main user-facing class for quantification. It uses Quant_Corrections to compute all correction factors and matrix effects, and relies on the XSp_Fitter module to extract peak/background intensities from measured spectra. Quant_Corrections provides the core physical models for all matrix corrections, and is initialized with the relevant sample and measurement parameters. The XSp_Fitter module must be installed and available for spectral fitting and deconvolution.
- class autoemx.core.quantifier.quantifier.XSp_Quantifier(spectrum_vals, spectrum_lims, microscope_ID, meas_type, meas_mode, det_ch_offset, det_ch_width, beam_e, emergence_angle, energy_vals=None, background_vals=None, els_sample=None, els_substrate=None, els_w_fr=None, is_particle=False, sp_collection_time=None, max_undetectable_w_fr=0.1, fit_tol=0.0001, standards_dict=None, verbose=False, fitting_verbose=False, free_area_el_lines=None, free_peak_shape_els=None, free_peak_shape_params=None, free_background_params=None, identify_missing_elements=False, identification_pool=None, identification_settings=None)[source]
Bases:
objectClass for quantitative analysis of EDS spectra.
- Variables:
spectrum_vals (numpy.ndarray) – The measured EDS spectrum (counts per channel).
energy_vals (numpy.ndarray) – Energy scale corresponding to spectrum_vals.
spectrum_lims (tuple of int) – Start and end indices for the spectrum region to analyze.
fit_background (bool) – Whether to fit a background model. True, if background_vals are not provided.
background_vals (numpy.ndarray) – Fitted or provided background spectrum counts.
els_sample (list of str) – All elements present in the sample, including undetectable elements.
els_to_quantify (list of str) – Elements to be quantified (excluding undetectable).
els_substrate (list of str) – Elements present in the substrate or sample holder appearing in spectra (excluding undetectable).
els_w_fr (dict or None, optional) – Dictionary of fixed elemental mass fractions, by element symbol, e.g. {‘Si’:0.33, ‘O’:0.67}.
max_undetectable_w_fr (float) – Maximum allowed total mass fraction for undetectable elements during fitting.
force_total_w_fr (bool) – Whether total mass fraction is normalized 1 during fitting. False, if undetectable elements are present in the sample. True otherwise.
is_particle (bool) – Whether the sample is a particle (affects fitting and quantification corrections).
sp_collection_time (float or None) – Live time of spectrum acquisition (in seconds).
fit_tol (float) – Tolerance for spectrum fitting convergence.
bad_quant_flag (int or None) – Flag indicating quantification issues, or None if successful.
microscope_ID (str) – Microscope identifier for calibration.
meas_type (str) – Measurement type (e.g., ‘EDS’).
meas_mode (str) – Measurement mode, defining detector calibrations and (optionally) beam current (e.g., ‘point’).
det_ch_offset (float) – Detector channel energy offset (keV).
det_ch_width (float) – Detector channel width (keV).
beam_energy (float) – Electron beam energy (keV).
emergence_angle (float) – Detector emergence (take-off) angle (degrees).
verbose (bool) – Print information during quantification.
fitting_verbose (bool) – If True, print detailed information during each fitting step.
attributes (Class)
----------------
xray_quant_ref_lines (list(str)) – List of X-ray lines used as reference
initial_fit_tol (float) – Fit tolerance of the first iteration when quantifying iteratively
ideal_ref_line_energy_threshold (ideal_ref_line_overvoltage,) – Minimum overvoltage and energy (keV) of the reference lines preferred for quantification
- xray_quant_ref_lines = ['Ka1', 'La1', 'Ma1', 'Mz1']
- initial_fit_tol = 0.01
- ideal_ref_line_energy_threshold = 2
- ideal_ref_line_overvoltage = 1.65
- classmethod format_measured_pb(peaks: Iterable[Tuple[str, str, float | None]], standard_elements: Iterable[str] | None = None) List[str][source]
Format the measured P/B ratios of the reference lines of a fitted standard.
- Parameters:
peaks (iterable of tuple) – Fitted peaks, as (element, line, pb_ratio). Lines that are not reference lines, and missing or non-positive P/B ratios, are skipped.
standard_elements (iterable of str, optional) – If given, only peaks of these elements are reported.
- Returns:
Lines “El_line: PB”, ordered by reference-line priority. Empty if no peak can be reported.
- Return type:
list of str
- initialize_and_fit_spectrum(params: Parameters | None = None, print_results: bool | None = False) None[source]
Perform a complete fit of the spectrum provided to the instance of XSp_Quantifier. This method is intended for single-iteration fits where sample composition is known and constrained (e.g., EDS standards).
The fit results and all relevant fitted parameters are stored as instance attributes.
- Parameters:
params (Optional[lmfit.Parameters], optional) – Parameters object to pass to the spectrum fitter. If None, default parameters are used.
print_result (bool, optional) – If True, prints the fitting results.
- Returns:
None
Nested Calls
————
Calls the following methods to further store values extracted from the fit –
self._initialize_spectrum_fitter(): initializes the spectrum fitter
self._fit_spectrum(): fits the spectrum and stores the fit results
- get_starting_K_val() float | None[source]
Estimate the initial background scaling factor K by fitting the high-energy portion of the spectrum.
This method fits only the region of the spectrum above a threshold energy to avoid regions heavily affected by absorption. It is intended to provide an optimal starting value for K, especially for particle spectra, to prevent the algorithm from compensating for background intensity via particle geometry parameters, which are only intended for background shape fitting.
- Returns:
K_val – Estimated initial value for the background scaling factor K, or None if a suitable value could not be determined.
- Return type:
Optional[float]
Notes
Uses XSp_Fitter with particle geometry disabled for this quick fit.
Prints diagnostic information if self.verbose is True.
- classmethod get_candidate_quant_lines(lines_energies: Dict[str, float], beam_energy: float) List[str][source]
Returns the lines that may be used to quantify an element, among its fitted reference lines (lines in xray_quant_ref_lines): those above ideal_ref_line_energy_threshold keV and with overvoltage above ideal_ref_line_overvoltage if any, otherwise all of them. The line used for quantification is the candidate with the largest fitted peak area.
- Parameters:
lines_energies (dict) – Energy (keV) of each fitted reference line of the element, keyed by line name.
beam_energy (float) – Beam energy (keV).
- Returns:
Candidate lines (keys of lines_energies).
- Return type:
list of str
- quantify_spectrum(force_single_iteration=False, interrupt_fits_bad_spectra=True, print_result=True)[source]
Quantifies a spectrum, using iterative fitting to refine elemental fractions. At each iteration, elemental fractions are quantified and enforced in the next iteration. Algorithm converges when quantified elemental fractions all change by less than 0.01%.
Instead, if elemental fractions are provided (i.e., fitting of experimental standards), background values are provided, or if force_single_iteration = True, only a single iteration is performed.
- Parameters:
force_single_iteration (bool, optional) – If True, only a single fit iteration is performed, even if some elemental fractions are undefined.
interrupt_fits_bad_spectra (bool, optional) – If True, fitting is interrupted early if the spectrum is deemed unreliable.
print_result (bool, optional) – If True, prints the quantification results.
- Returns:
quant_result (dict or None) – Dictionary with quantification results, or None if fit failed.
min_bckgrnd_ref_lines (float) – Minimum background counts across reference peaks, or 0 if fit failed.
bad_quant_flag (int or None) – Flag indicating quantification issues, or None if successful.
- export_fit_result() FitResult[source]
Build a schema-ready fit summary from the current fitted peak state.
- export_quantification_result(quantification_id: int, quant_result: Dict[str, Any] | None, quant_flag: int | None = None, comment: str | None = None) QuantificationResult[source]
Build a persisted quantification result for the current fitted spectrum.
- print_quant_result(quant_result: dict, Z_sample: dict = None, quant_flag: int | None = None) None[source]
Print the quantification results, including fit quality metrics and elemental composition.
- Parameters:
quant_result (dict) –
- Dictionary containing quantification results with keys:
cnst.REDCHI_SQ_KEY: Reduced Chi-square of the fit.
cnst.R_SQ_KEY: R-squared of the fit.
cnst.COMP_W_FR_KEY: Weight fractions (as decimals).
cnst.COMP_AT_FR_KEY: Atomic fractions (as decimals).
cnst.AN_ER_KEY: Analytical error (as decimal).
Z_sample (dict, optional) –
- Dictionary containing mean atomic numbers (optional), e.g.:
’Statham2016’: Mean atomic number (Z̅) calculated according to Statham (2016).
’mass-averaged’: Mean atomic number (Z̅) weighted by composition.
quant_flag (int | None, optional) – Flag signaling reliability of quantification. Anything different than 0 signals potential unreliability of the quantified composition. See the user documentation page “Quantification flags (quant_flag)”.
- Return type:
None
References
Statham P, Penman C, Duncumb P. IOP Conf Ser Mater Sci Eng. 2016;109(1):0–10.
- get_bckgrnd_cnts_ref_lines() Dict[str, Tuple[float, float]][source]
Background counts under each reference line used for quantification, as plotted by
plot_quantified_spectrum.The value is taken at the theoretical line energy from the fitted background without detector response (when the background is fitted), so it generally differs from the plotted fitted background at that energy.
- Returns:
{el_line: (energy_keV, background_counts)}.- Return type:
dict
- plot_quantified_spectrum(annotate_peaks: str = 'all', plot_bckgrnd_cnts_ref_peaks: bool = True, plot_initial_guess: bool = False, plot_title: str | None = None, peaks_to_zoom: str | List[str] | None = None, show: bool = True, save_path: str | None = None) Any | None[source]
Plot the quantified spectrum. The background counts under reference peaks are highlighted for spectra used for quantification.
- Parameters:
annotate_peaks (str, optional) – Which peaks to annotate. Options: ‘all’, ‘most’, ‘main’, ‘none’. Default is ‘all’.
plot_bckgrnd_cnts_ref_peaks (bool, optional) – If True, plot vertical lines that illustrate value of background counts used for quantification. This is shown underneath the corresponding reference characteristic peaks for each element.
plot_initial_guess (bool, optional) – If True, plot the initial guess as well. Default is False.
plot_title (str, optional) – Title printed at the top of the plot. Default is None.
peaks_to_zoom (str or list of str, optional) – Peak label (e.g. ‘Si_Ka1’) or list of labels to zoom in on. If provided, creates a new figure for each.
show (bool, optional) – If True (default), display the figure with
plt.show(). Set False for headless export or embedding in a GUI.save_path (str, optional) – If given, save the main figure to this path (PNG recommended).
- Returns:
The main figure. Callers that pass
show=Falseshould close it.- Return type:
matplotlib.figure.Figure or None