exspy.models#

EDSModel(spectrum[, auto_background, ...])

Build and fit a model of an EDS Signal1D.

EDSSEMModel(spectrum[, auto_background, ...])

Build and fit a model to EDS data acquired in the SEM.

EDSTEMModel(spectrum[, auto_background, ...])

Build and fit a model to EDS data acquired in the TEM.

EELSModel(signal1D[, auto_background, ...])

Build an EELS model.

Models

class exspy.models.EDSModel(spectrum, auto_background=True, auto_add_lines=True, *args, **kwargs)#

Bases: Model1D

Build and fit a model of an EDS Signal1D.

Parameters:
  • spectrum (EDSSpectrum (or any EDSSpectrum subclass) instance.)

  • auto_add_lines (bool) – If True, automatically add Gaussians for all X-rays generated in the energy range by an element, using the edsmodel.add_family_lines method.

  • auto_background (bool) – If True, adds automatically a polynomial order 6 to the model, using the edsmodel.add_polynomial_background method.

  • creator. (Any extra arguments are passed to the Model)

Example

>>> m = s.create_model()
>>> m.fit()
>>> m.fit_background()
>>> m.calibrate_energy_axis('resolution')
>>> m.calibrate_xray_lines('energy', ['Au_Ma'])
>>> m.calibrate_xray_lines('sub_weight',['Mn_La'], bound=10)
add_family_lines(xray_lines='from_elements')#

Create the Xray-lines instances and configure them appropiately

If a X-ray line is given, all the the lines of the familiy is added. For instance if Zn Ka is given, Zn Kb is added too. The main lines (alpha) is added to self.xray_lines

Parameters:

xray_lines ({None, 'from_elements', list of string}) – If None, if metadata contains xray_lines list of lines use those. If ‘from_elements’, add all lines from the elements contains in metadata. Alternatively, provide an iterable containing a list of valid X-ray lines symbols. (eg. (‘Al_Ka’,’Zn_Ka’)).

Raises:

NotImplementedError – If the signal axis is a non-uniform axis.

add_polynomial_background(order=6)#

Add a polynomial background.

the background is added to self.background_components

Parameters:

order (int) – The order of the polynomial

as_dictionary(fullcopy=True)#

Returns a dictionary of the model, including all components, degrees of freedom (dof) and chi-squared (chisq) with values.

Parameters:

fullcopy (bool, optional True) – Copies of objects are stored, not references. If any found, functions will be pickled and signals converted to dictionaries

Returns:

dictionary – A dictionary including at least the following fields:

  • components: a list of dictionaries of components, one per component

  • _whitelist: a dictionary with keys used as references for saved attributes, for more information, see export_to_dictionary()

  • any field from _whitelist.keys()

Return type:

dict

Examples

>>> s = hs.signals.Signal1D(np.random.random((10,100)))
>>> m = s.create_model()
>>> l1 = hs.model.components1D.Lorentzian()
>>> l2 = hs.model.components1D.Lorentzian()
>>> m.append(l1)
>>> m.append(l2)
>>> d = m.as_dictionary()
>>> m2 = s.create_model(dictionary=d)
calibrate_energy_axis(calibrate='resolution', xray_lines='all_alpha', **kwargs)#

Calibrate the resolution, the scale or the offset of the energy axis by fitting.

Parameters:
  • calibrate ('resolution' or 'scale' or 'offset') – If ‘resolution’, fits the width of Gaussians place at all x-ray lines. The width is given by a model of the detector resolution, obtained by extrapolating the energy_resolution_MnKa in metadata. This method will update the value of energy_resolution_MnKa. If ‘scale’, calibrate the scale of the energy axis. If ‘offset’, calibrate the offset of the energy axis.

  • xray_lines (list of str or 'all_alpha') – The Xray lines. If ‘all_alpha’, fit all using all alpha lines

  • **kwargs (extra key word arguments) – All extra key word arguments are passed to fit or multifit, depending on the value of kind.

calibrate_xray_lines(calibrate='energy', xray_lines='all', bound=1, kind='single', **kwargs)#

Calibrate individually the X-ray line parameters.

The X-ray line energy, the weight of the sub-lines and the X-ray line width can be calibrated.

Parameters:
  • calibrate ('energy' or 'sub_weight' or 'width') – If ‘energy’, calibrate the X-ray line energy. If ‘sub_weight’, calibrate the ratio between the main line alpha and the other sub-lines of the family If ‘width’, calibrate the X-ray line width.

  • xray_lines (list of str or 'all') – The Xray lines. If ‘all’, fit all lines

  • bounds (float) – for ‘energy’ and ‘width’ the bound in energy, in eV for ‘sub_weight’ Bound the height of the peak to fraction of its height

  • kind ({'single', 'multi'}) – If ‘single’ fit only the current location. If ‘multi’ use multifit.

  • **kwargs (extra key word arguments) – All extra key word arguments are passed to fit or multifit, depending on the value of kind.

disable_xray_lines()#

Disable the X-ray lines components.

enable_xray_lines()#

Enable the X-ray lines components.

fit_background(start_energy=None, end_energy=None, windows_sigma=(4.0, 3.0), kind='single', **kwargs)#

Fit the background in the energy range containing no X-ray line.

After the fit, the background is fixed.

Parameters:
  • start_energy ({float, None}) – If float, limit the range of energies from the left to the given value.

  • end_energy ({float, None}) – If float, limit the range of energies from the right to the given value.

  • windows_sigma (tuple of two float) – The (lower, upper) bounds around each X-ray line, each as a float, to define the energy range free of X-ray lines.

  • kind ({'single', 'multi'}) – If ‘single’ fit only the current location. If ‘multi’ use multifit.

  • **kwargs (extra key word arguments) – All extra key word arguments are passed to fit or multifit

See also

free_background

fix_background()#

Fix the background components.

fix_sub_xray_lines_weight(xray_lines='all')#

Fix the weight of a sub X-ray lines to the main X-ray lines

Establish the twin on the height of sub-Xray lines (non alpha)

fix_xray_lines_energy(xray_lines='all')#

Fix the X-ray line energy (shift or centre of the Gaussian)

Parameters:
  • xray_lines (list of str, 'all', or 'all_alpha') – The Xray lines. If ‘all’, fit all lines. If ‘all_alpha’ fit all using all alpha lines.

  • bound (float) – the bound around the actual energy, in keV or eV

fix_xray_lines_width(xray_lines='all')#

Fix the X-ray line width (sigma of the Gaussian)

Parameters:
  • xray_lines (list of str, 'all', or 'all_alpha') – The Xray lines. If ‘all’, fit all lines. If ‘all_alpha’ fit all using all alpha lines.

  • bound (float) – the bound around the actual energy, in keV or eV

free_background()#

Free the yscale of the background components.

free_sub_xray_lines_weight(xray_lines='all', bound=0.01)#

Free the weight of a sub X-ray lines

Remove the twin on the height of sub-Xray lines (non alpha)

Parameters:
  • xray_lines (list of str or 'all') – The Xray lines. If ‘all’, fit all lines

  • bound (float) – Bound the height of the peak to a fraction of its height

free_xray_lines_energy(xray_lines='all', bound=0.001)#

Free the X-ray line energy (shift or centre of the Gaussian)

Parameters:
  • xray_lines (list of str or 'all') – The Xray lines. If ‘all’, fit all lines

  • bound (float) – the bound around the actual energy, in keV or eV

free_xray_lines_width(xray_lines='all', bound=0.01)#

Free the X-ray line width (sigma of the Gaussian)

Parameters:
  • xray_lines (list of str or 'all') – The Xray lines. If ‘all’, fit all lines

  • bound (float) – the bound around the actual energy, in keV or eV

get_lines_intensity(xray_lines=None, plot_result=False, only_one=True, only_lines=('a',), **kwargs)#

Return the fitted intensity of the X-ray lines.

Return the area under the gaussian corresping to the X-ray lines

Parameters:
  • xray_lines ({None, list of string}) – If None, if metadata.Sample.elements.xray_lines contains a list of lines use those. If metadata.Sample.elements.xray_lines is undefined or empty but metadata.Sample.elements is defined, use the same syntax as add_line to select a subset of lines for the operation. Alternatively, provide an iterable containing a list of valid X-ray lines symbols.

  • plot_result (bool) – If True, plot the calculated line intensities. If the current object is a single spectrum it prints the result instead.

  • only_one (bool) – If False, use all the lines of each element in the data spectral range. If True use only the line at the highest energy above an overvoltage of 2 (< beam energy / 2).

  • only_lines ({None, list of strings}) – If not None, use only the given lines.

  • kwargs – The extra keyword arguments for plotting. See utils.plot.plot_signals

Returns:

intensities – A list containing the intensities as Signal subclasses.

Return type:

list

Examples

>>> m.multifit()
>>> m.get_lines_intensity(["C_Ka", "Ta_Ma"])
remove(thing)#

Remove component from model.

Examples

>>> s = hs.signals.Signal1D(np.empty(1))
>>> m = s.create_model()
>>> g1 = hs.model.components1D.Gaussian()
>>> g2 = hs.model.components1D.Gaussian()
>>> m.extend([g1, g2])

You could remove g1 like this

>>> m.remove(g1)

Or like this:

>>> m.remove(0)
class exspy.models.EDSSEMModel(spectrum, auto_background=True, auto_add_lines=True, *args, **kwargs)#

Bases: EDSModel

Build and fit a model to EDS data acquired in the SEM.

Parameters:
  • spectrum (EDSSEMSpectrum)

  • auto_add_lines (bool) – If True, automatically add Gaussians for all X-rays generated in the energy range by an element, using the edsmodel.add_family_lines method.

  • auto_background (bool) – If True, adds automatically a polynomial order 6 to the model, using the edsmodel.add_polynomial_background method.

  • constructor. (Any extra arguments are passed to the Model)

class exspy.models.EDSTEMModel(spectrum, auto_background=True, auto_add_lines=True, *args, **kwargs)#

Bases: EDSModel

Build and fit a model to EDS data acquired in the TEM.

Parameters:
  • spectrum (EDSTEMSpectrum)

  • auto_add_lines (bool) – If True, automatically add Gaussians for all X-rays generated in the energy range by an element, using the edsmodel.add_family_lines method.

  • auto_background (bool) – If True, adds automatically a polynomial order 6 to the model, using the edsmodel.add_polynomial_background method.

  • constructor. (Any extra arguments are passed to the Model)

class exspy.models.EELSModel(signal1D, auto_background=True, auto_add_edges=True, low_loss=None, GOS='gosh', dictionary=None)#

Bases: Model1D

Build an EELS model.

Parameters:
  • spectrum (a EELSSpectrum instance)

  • ll (None or EELSSpectrum) – If an EELSSpectrum is provided, it will be assumed that it is a low-loss EELS spectrum, and it will be used to simulate the effect of multiple scattering by convolving it with the EELS spectrum.

  • auto_background (bool) – If True, and if spectrum is an EELS instance adds automatically a powerlaw to the model and estimate the parameters by the two-area method.

  • auto_add_edges (bool) – If True, and if spectrum is an EELS instance, it will automatically add the ionization edges as defined in the EELSSpectrum instance. Adding a new element to the spectrum using the add_elements() method automatically add the corresponding ionisation edges to the model.

  • GOS ('hydrogenic', 'gosh', 'Hartree-Slater'.) – The GOS to use. Default is 'gosh'.

  • gos_file_path (str, None) – Only with GOS=’gosh’. Specify the file path of the gosh file to use. If None, use the file from doi:10.5281/zenodo.7645765

  • dictionary (None or dict) – A dictionary to be used to recreate a model. Usually generated using as_dictionary()

append(component)#

Add component to Model.

Parameters:

thing (Component) – The component to add to the model.

disable_background()#

Disable the background components.

disable_edges(edges_list=None)#

Disable the edges listed in edges_list. If edges_list is None (default) all the edges with onset in the spectrum energy region will be disabled.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

disable_fine_structure(edges_list=None)#

Disable the fine structure of the edges listed in edges_list. If edges_list is None (default) the fine structure of all the edges with onset in the spectrum energy region will be disabled.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

disable_free_onset_energy(edges_list=None)#

Disable the automatic freeing of the onset_energy parameter during a smart fit for the edges listed in edges_list. If edges_list is None (default) the onset_energy of all the edges with onset in the spectrum energy region will not be freed. Note that if their attribute edge.onset_energy.free is True, the parameter will be free during the smart fit.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

enable_background()#

Enable the background components.

enable_edges(edges_list=None)#

Enable the edges listed in edges_list. If edges_list is None (default) all the edges with onset in the spectrum energy region will be enabled.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

enable_fine_structure(edges_list=None)#

Enable the fine structure of the edges listed in edges_list.

If edges_list is None (default) the fine structure of all the edges with onset in the spectrum energy region will be enabled.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

enable_free_onset_energy(edges_list=None)#

Enable the automatic freeing of the onset_energy parameter during a smart fit for the edges listed in edges_list. If edges_list is None (default) the onset_energy of all the edges with onset in the spectrum energy region will be freed.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

fit(kind='std', **kwargs)#

Fits the model to the experimental data.

Read more in the User Guide.

Parameters:
  • kind ({"std", "smart"}, default "std") – If “std”, performs standard fit. If “smart”, performs a smart_fit - for more details see the User Guide.

  • optimizer (str or None, default None) –

    The optimization algorithm used to perform the fitting.

    • "lm" performs least-squares optimization using the Levenberg-Marquardt algorithm, and supports bounds on parameters.

    • "trf" performs least-squares optimization using the Trust Region Reflective algorithm, and supports bounds on parameters.

    • "dogbox" performs least-squares optimization using the dogleg algorithm with rectangular trust regions, and supports bounds on parameters.

    • "odr" performs the optimization using the orthogonal distance regression (ODR) algorithm. It does not support bounds on parameters. See scipy.odr for more details.

    • All of the available methods for scipy.optimize.minimize() can be used here. See the User Guide documentation for more details.

    • "Differential Evolution" is a global optimization method. It does support bounds on parameters. See scipy.optimize.differential_evolution() for more details on available options.

    • "Dual Annealing" is a global optimization method. It does support bounds on parameters. See scipy.optimize.dual_annealing() for more details on available options. Requires scipy >= 1.2.0.

    • "SHGO" (simplicial homology global optimization) is a global optimization method. It does support bounds on parameters. See scipy.optimize.shgo() for more details on available options. Requires scipy >= 1.2.0.

  • loss_function ({"ls", "ML-poisson", "huber", callable}, default "ls") –

    The loss function to use for minimization. Only "ls" is available if optimizer is one of "lm", "trf", "dogbox" or "odr".

    • "ls" minimizes the least-squares loss function.

    • "ML-poisson" minimizes the negative log-likelihood for Poisson-distributed data. Also known as Poisson maximum likelihood estimation (MLE).

    • "huber" minimize the Huber loss function. The delta value of the Huber function is controlled by the huber_delta keyword argument (the default value is 1.0).

    • callable supports passing your own minimization function.

  • grad ({"fd", "analytical", callable, None}, default "fd") –

    Whether to use information about the gradient of the loss function as part of the optimization. This parameter has no effect if optimizer is a derivative-free or global optimization method.

    • "fd" uses a finite difference scheme (if available) for numerical estimation of the gradient. The scheme can be further controlled with the fd_scheme keyword argument.

    • "analytical" uses the analytical gradient (if available) to speed up the optimization, since the gradient does not need to be estimated.

    • callable should be a function that returns the gradient vector.

    • None means that no gradient information is used or estimated. Not available if optimizer is one of "lm", "trf" or "dogbox".

  • bounded (bool, default False) – If True, performs bounded parameter optimization if supported by optimizer.

  • update_plot (bool, default False) – If True, the plot is updated during the optimization process. It slows down the optimization, but it enables visualization of the optimization progress.

  • print_info (bool, default False) – If True, print information about the fitting results, which are also stored in model.fit_output in the form of a scipy.optimize.OptimizeResult object.

  • return_info (bool, default True) – If True, returns the fitting results in the form of a scipy.optimize.OptimizeResult object.

  • fd_scheme (str {"2-point", "3-point", "cs"}, default "2-point") – If grad='fd', selects the finite difference scheme to use. See scipy.optimize.minimize() for details. Ignored if optimizer is one of "lm", "trf" or "dogbox".

  • **kwargs (dict) – Any extra keyword argument will be passed to the chosen optimizer. For more information, read the docstring of the optimizer of your choice in scipy.optimize.

Return type:

None

See also

fit_background(start_energy=None, only_current=True, **kwargs)#

Fit the background to the first active ionization edge in the energy range.

Parameters:
  • start_energy ({float, None}, optional) – If float, limit the range of energies from the left to the given value. Default None.

  • only_current (bool, optional) – If True, only fit the background at the current coordinates. Default True.

  • **kwargs (extra key word arguments) – All extra key word arguments are passed to fit or multifit.

fix_edges(edges_list=None)#

Fixes all the parameters of the edges given in edges_list. If edges_list is None (default) all the edges will be fixed.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

fix_fine_structure(edges_list=None)#

Fixes the fine structure of the edges given in edges_list. If edges_list is None (default) all the edges will be fixed.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

free_edges(edges_list=None)#

Frees all the parameters of the edges given in edges_list. If edges_list is None (default) all the edges will be freed.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

free_fine_structure(edges_list=None)#

Frees the fine structure of the edges given in edges_list. If edges_list is None (default) all the edges will be freed.

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

quantify()#

Prints the value of the intensity of all the independent active EELS core loss edges defined in the model

remove(component)#

Remove component from model.

Examples

>>> s = hs.signals.Signal1D(np.empty(1))
>>> m = s.create_model()
>>> g1 = hs.model.components1D.Gaussian()
>>> g2 = hs.model.components1D.Gaussian()
>>> m.extend([g1, g2])

You could remove g1 like this

>>> m.remove(g1)

Or like this:

>>> m.remove(0)
remove_fine_structure_data(edges_list=None)#

Remove the fine structure data from the fitting routine as defined in the fine_structure_width parameter of the component.EELSCLEdge

Parameters:

edges_list (None or list of EELSCLEdge or list of edge names) – If None, the operation is performed on all the edges in the model. Otherwise, it will be performed only on the listed components.

resolve_fine_structure(preedge_safe_window_width=2, i1=0)#

Adjust the fine structure of all edges to avoid overlapping

This function is called automatically every time the position of an edge changes

Parameters:

preedge_safe_window_width (float) – minimum distance between the fine structure of an ionization edge and that of the following one. Default 2 (eV).

resume_auto_fine_structure_width(update=True)#

Enable the automatic adjustment of the core-loss edges fine structure width.

Parameters:

update (bool, optional) – If True, also execute the automatic adjustment (default).

set_all_edges_intensities_positive()#

Set all edges intensities positive by setting ext_force_positive and ext_bounded to True.

Return type:

None.

set_convolution_axis()#

Creates an axis to use to generate the data of the model in the precise scale to obtain the correct axis and origin after convolution.

property signal#

The signal data to fit.

smart_fit(start_energy=None, **kwargs)#

Fits EELS edges in a cascade style.

The fitting procedure acts in iterative manner along the energy-loss-axis. First it fits only the background up to the first edge. It continues by deactivating all edges except the first one, then performs the fit. Then it only activates the first two, fits, and repeats this until all edges are fitted simultaneously.

Other, non-EELSCLEdge components, are never deactivated, and fitted on every iteration.

Parameters:
  • start_energy ({float, None}) – If float, limit the range of energies from the left to the given value.

  • optimizer (str or None, default None) –

    The optimization algorithm used to perform the fitting.

    • "lm" performs least-squares optimization using the Levenberg-Marquardt algorithm, and supports bounds on parameters.

    • "trf" performs least-squares optimization using the Trust Region Reflective algorithm, and supports bounds on parameters.

    • "dogbox" performs least-squares optimization using the dogleg algorithm with rectangular trust regions, and supports bounds on parameters.

    • "odr" performs the optimization using the orthogonal distance regression (ODR) algorithm. It does not support bounds on parameters. See scipy.odr for more details.

    • All of the available methods for scipy.optimize.minimize() can be used here. See the User Guide documentation for more details.

    • "Differential Evolution" is a global optimization method. It does support bounds on parameters. See scipy.optimize.differential_evolution() for more details on available options.

    • "Dual Annealing" is a global optimization method. It does support bounds on parameters. See scipy.optimize.dual_annealing() for more details on available options. Requires scipy >= 1.2.0.

    • "SHGO" (simplicial homology global optimization) is a global optimization method. It does support bounds on parameters. See scipy.optimize.shgo() for more details on available options. Requires scipy >= 1.2.0.

  • loss_function ({"ls", "ML-poisson", "huber", callable}, default "ls") –

    The loss function to use for minimization. Only "ls" is available if optimizer is one of "lm", "trf", "dogbox" or "odr".

    • "ls" minimizes the least-squares loss function.

    • "ML-poisson" minimizes the negative log-likelihood for Poisson-distributed data. Also known as Poisson maximum likelihood estimation (MLE).

    • "huber" minimize the Huber loss function. The delta value of the Huber function is controlled by the huber_delta keyword argument (the default value is 1.0).

    • callable supports passing your own minimization function.

  • grad ({"fd", "analytical", callable, None}, default "fd") –

    Whether to use information about the gradient of the loss function as part of the optimization. This parameter has no effect if optimizer is a derivative-free or global optimization method.

    • "fd" uses a finite difference scheme (if available) for numerical estimation of the gradient. The scheme can be further controlled with the fd_scheme keyword argument.

    • "analytical" uses the analytical gradient (if available) to speed up the optimization, since the gradient does not need to be estimated.

    • callable should be a function that returns the gradient vector.

    • None means that no gradient information is used or estimated. Not available if optimizer is one of "lm", "trf" or "dogbox".

  • bounded (bool, default False) – If True, performs bounded parameter optimization if supported by optimizer.

  • update_plot (bool, default False) – If True, the plot is updated during the optimization process. It slows down the optimization, but it enables visualization of the optimization progress.

  • print_info (bool, default False) – If True, print information about the fitting results, which are also stored in model.fit_output in the form of a scipy.optimize.OptimizeResult object.

  • return_info (bool, default True) – If True, returns the fitting results in the form of a scipy.optimize.OptimizeResult object.

  • fd_scheme (str {"2-point", "3-point", "cs"}, default "2-point") – If grad='fd', selects the finite difference scheme to use. See scipy.optimize.minimize() for details. Ignored if optimizer is one of "lm", "trf" or "dogbox".

  • **kwargs (dict) – Any extra keyword argument will be passed to the chosen optimizer. For more information, read the docstring of the optimizer of your choice in scipy.optimize.

See also

suspend_auto_fine_structure_width()#

Disable the automatic adjustment of the core-loss edges fine structure width.

two_area_background_estimation(E1=None, E2=None, powerlaw=None)#

Estimates the parameters of a power law background with the two area method.

Parameters:
  • E1 (float)

  • E2 (float)

  • powerlaw (PowerLaw component or None) – If None, it will try to guess the right component from the background components of the model

unset_all_edges_intensities_positive()#

Unset all edges intensities positive by setting ext_force_positive and ext_bounded to False.

Return type:

None.