hyperspy._signals.eds_tem module

class hyperspy._signals.eds_tem.EDSTEMParametersUI(signal)

Bases: BaseSetMetadataItems

gui(display=True, toolkit=None, **kwargs)

Display or return interactive GUI element if available.

Parameters:
  • display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

  • toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.

class hyperspy._signals.eds_tem.EDSTEMSpectrum(*args, **kwards)

Bases: EDSSpectrum

1D signal class for EDS spectra measured in a TEM.

Create a Signal from a numpy array.

Parameters:
  • data (numpy.ndarray) – The signal data. It can be an array of any dimensions.

  • axes ([dict/axes], optional) – List of either dictionaries or axes objects to define the axes (see the documentation of the AxesManager class for more details).

  • attributes (dict, optional) – A dictionary whose items are stored as attributes.

  • metadata (dict, optional) – A dictionary containing a set of parameters that will to stores in the metadata attribute. Some parameters might be mandatory in some cases.

  • original_metadata (dict, optional) – A dictionary containing a set of parameters that will to stores in the original_metadata attribute. It typically contains all the parameters that has been imported from the original data file.

  • ragged (bool or None, optional) – Define whether the signal is ragged or not. Overwrite the ragged value in the attributes dictionary. If None, it does nothing. Default is None.

static CL_get_mass_thickness(weight_percent, thickness)

Creates a array of mass_thickness based on a known material composition and measured thickness. Required for absorption correction calcultions using the Cliff Lorimer method.

Parameters:
  • weight_percent (BaseSignal (or subclass)) – Stack of compositions as determined from an initial k_factor quantification.

  • thickness (float or numpy.ndarray) – Either a float value for thickness in nm or an array equal to the size of the EDX map with thickness at each position of the sample.

Returns:

mass_thickness – Mass thickness in kg/m².

Return type:

numpy.ndarray

_are_microscope_parameters_missing()

Check if the EDS parameters necessary for quantification are defined in metadata.

_get_dose(method, beam_current='auto', live_time='auto', probe_area='auto')

Calculates the total electron dose for the zeta-factor or cross section methods of quantification.

Input given by i*t*N, i the current, t the acquisition time, and N the number of electron by unit electric charge.

Parameters:
  • method ('zeta' or 'cross_section') – If ‘zeta’, the dose is given by i*t*N If ‘cross section’, the dose is given by i*t*N/A where i is the beam current, t is the acquistion time, N is the number of electrons per unit charge (1/e) and A is the illuminated beam area or pixel area.

  • beam_current (float) – Probe current in nA

  • live_time (float) – Acquisiton time in s, compensated for the dead time of the detector.

  • probe_area (float or 'auto') – The illumination area of the electron beam in nm². If ‘auto’ the value is extracted from the scale axes_manager. Therefore we assume the probe is oversampling such that the illumination area can be approximated to the pixel area of the spectrum image.

Return type:

Dose in electrons (zeta factor) or electrons per nm² (cross_section)

_set_default_param()

Set to value to default (defined in preferences)

create_model(auto_background=True, auto_add_lines=True, *args, **kwargs)

Create a model for the current TEM EDS data.

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

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

  • dictionary ({None, dict}, optional) – A dictionary to be used to recreate a model. Usually generated using hyperspy.model.as_dictionary()

Returns:

model

Return type:

EDSTEMModel instance.

decomposition(normalize_poissonian_noise=True, navigation_mask=1.0, closing=True, *args, **kwargs)

Apply a decomposition to a dataset with a choice of algorithms.

The results are stored in self.learning_results.

Read more in the User Guide.

Parameters:
  • normalize_poissonian_noise (bool, default True) – If True, scale the signal to normalize Poissonian noise using the approach described in [Keenan2004].

  • navigation_mask (None or float or boolean numpy array, default 1.0) – The navigation locations marked as True are not used in the decomposition. If float is given the vacuum_mask method is used to generate a mask with the float value as threshold.

  • closing (bool, default True) – If true, applied a morphologic closing to the mask obtained by vacuum_mask.

  • algorithm ({"SVD", "MLPCA", "sklearn_pca", "NMF", "sparse_pca", "mini_batch_sparse_pca", "RPCA", "ORPCA", "ORNMF", custom object}, default "SVD") – The decomposition algorithm to use. If algorithm is an object, it must implement a fit_transform() method or fit() and transform() methods, in the same manner as a scikit-learn estimator.

  • output_dimension (None or int) – Number of components to keep/calculate. Default is None, i.e. min(data.shape).

  • centre ({None, "navigation", "signal"}, default None) –

    • If None, the data is not centered prior to decomposition.

    • If “navigation”, the data is centered along the navigation axis. Only used by the “SVD” algorithm.

    • If “signal”, the data is centered along the signal axis. Only used by the “SVD” algorithm.

  • auto_transpose (bool, default True) – If True, automatically transposes the data to boost performance. Only used by the “SVD” algorithm.

  • signal_mask (boolean numpy array) – The signal locations marked as True are not used in the decomposition.

  • var_array (numpy array) – Array of variance for the maximum likelihood PCA algorithm. Only used by the “MLPCA” algorithm.

  • var_func (None or function or numpy array, default None) –

    • If None, ignored

    • If function, applies the function to the data to obtain var_array. Only used by the “MLPCA” algorithm.

    • If numpy array, creates var_array by applying a polynomial function defined by the array of coefficients to the data. Only used by the “MLPCA” algorithm.

  • reproject ({None, "signal", "navigation", "both"}, default None) – If not None, the results of the decomposition will be projected in the selected masked area.

  • return_info (bool, default False) – The result of the decomposition is stored internally. However, some algorithms generate some extra information that is not stored. If True, return any extra information if available. In the case of sklearn.decomposition objects, this includes the sklearn Estimator object.

  • print_info (bool, default True) – If True, print information about the decomposition being performed. In the case of sklearn.decomposition objects, this includes the values of all arguments of the chosen sklearn algorithm.

  • svd_solver ({"auto", "full", "arpack", "randomized"}, default "auto") –

    If auto:

    The solver is selected by a default policy based on data.shape and output_dimension: if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient “randomized” method is enabled. Otherwise the exact full SVD is computed and optionally truncated afterwards.

    If full:

    run exact SVD, calling the standard LAPACK solver via scipy.linalg.svd(), and select the components by postprocessing

    If arpack:

    use truncated SVD, calling ARPACK solver via scipy.sparse.linalg.svds(). It requires strictly 0 < output_dimension < min(data.shape)

    If randomized:

    use truncated SVD, calling sklearn.utils.extmath.randomized_svd() to estimate a limited number of components

  • copy (bool, default True) –

    • If True, stores a copy of the data before any pre-treatments such as normalization in s._data_before_treatments. The original data can then be restored by calling s.undo_treatments().

    • If False, no copy is made. This can be beneficial for memory usage, but care must be taken since data will be overwritten.

  • **kwargs (extra keyword arguments) – Any keyword arguments are passed to the decomposition algorithm.

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> si = hs.stack([s]*3)
>>> si.change_dtype(float)
>>> si.decomposition()

See also

vacuum_mask

get_calibration_from(ref, nb_pix=1)

Copy the calibration and all metadata of a reference.

Primary use: To add a calibration to ripple file from INCA software

Parameters:
  • ref (signal) – The reference contains the calibration in its metadata

  • nb_pix (int) – The live time (real time corrected from the “dead time”) is divided by the number of pixel (spectrums), giving an average live time.

Raises:

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

Examples

>>> ref = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s = hs.signals.EDSTEMSpectrum(
>>>     hs.datasets.example_signals.EDS_TEM_Spectrum().data)
>>> print(s.axes_manager[0].scale)
>>> s.get_calibration_from(ref)
>>> print(s.axes_manager[0].scale)
1.0
0.020028
get_probe_area(navigation_axes=None)

Calculates a pixel area which can be approximated to probe area, when the beam is larger than or equal to pixel size. The probe area can be calculated only when the number of navigation dimension are less than 2 and all the units have the dimensions of length.

Parameters:

navigation_axes (DataAxis, string or integer (or list of)) – Navigation axes corresponding to the probe area. If string or integer, the provided value is used to index the axes_manager.

Return type:

probe area in nm².

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> si = hs.stack([s]*3)
>>> si.axes_manager.navigation_axes[0].scale = 0.01
>>> si.axes_manager.navigation_axes[0].units = 'μm'
>>> si.get_probe_area()
100.0
quantification(intensities, method, factors, composition_units='atomic', absorption_correction=False, take_off_angle='auto', thickness='auto', convergence_criterion=0.5, navigation_mask=1.0, closing=True, plot_result=False, probe_area='auto', max_iterations=30, show_progressbar=None, **kwargs)

Absorption corrected quantification using Cliff-Lorimer, the zeta-factor method, or ionization cross sections. The function iterates through quantification function until two successive interations don’t change the final composition by a defined percentage critera (0.5% by default).

Parameters:
  • intensities (list of signal) – the intensitiy for each X-ray lines.

  • method ({'CL', 'zeta', 'cross_section'}) – Set the quantification method: Cliff-Lorimer, zeta-factor, or ionization cross sections.

  • factors (list of float) – The list of kfactors, zeta-factors or cross sections in same order as intensities. Note that intensities provided by Hyperspy are sorted by the alphabetical order of the X-ray lines. eg. factors =[0.982, 1.32, 1.60] for [‘Al_Ka’, ‘Cr_Ka’, ‘Ni_Ka’].

  • composition_units ({'atomic', 'weight'}) – The quantification returns the composition in ‘atomic’ percent by default, but can also return weight percent if specified.

  • absorption_correction (bool) – Specify whether or not an absorption correction should be applied. ‘False’ by default so absorption will not be applied unless specfied.

  • take_off_angle ({'auto'}) – The angle between the sample surface and the vector along which X-rays travel to reach the centre of the detector.

  • thickness ({'auto'}) – thickness in nm (can be a single value or have the same navigation dimension as the signal). NB: Must be specified for ‘CL’ method. For ‘zeta’ or ‘cross_section’ methods, first quantification step provides a mass_thickness internally during quantification.

  • convergence_criterion (The convergence criterium defined as the percentage) – difference between 2 successive iterations. 0.5% by default.

  • navigation_mask (None or float or signal) – The navigation locations marked as True are not used in the quantification. If float is given the vacuum_mask method is used to generate a mask with the float value as threhsold. Else provides a signal with the navigation shape. Only for the ‘Cliff-Lorimer’ method.

  • closing (bool) – If true, applied a morphologic closing to the mask obtained by vacuum_mask.

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

  • {'auto'} (probe_area =) – This allows the user to specify the probe_area for interaction with the sample needed specifically for the cross_section method of quantification. When left as ‘auto’ the pixel area is used, calculated from the navigation axes information.

  • max_iterations (int) – An upper limit to the number of calculations for absorption correction.

  • kwargs – The extra keyword arguments are passed to plot.

Returns:

  • A list of quantified elemental maps (signal) giving the composition of

  • the sample in weight or atomic percent with absorption correciton taken

  • into account based on the sample thickness estimate provided.

  • If the method is ‘zeta’ this function also returns the mass thickness

  • profile for the data.

  • If the method is ‘cross_section’ this function also returns the atom

  • counts for each element.

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s.add_lines()
>>> kfactors = [1.450226, 5.075602] #For Fe Ka and Pt La
>>> bw = s.estimate_background_windows(line_width=[5.0, 2.0])
>>> s.plot(background_windows=bw)
>>> intensities = s.get_lines_intensity(background_windows=bw)
>>> res = s.quantification(intensities, kfactors, plot_result=True,
>>>                        composition_units='atomic')
Fe (Fe_Ka): Composition = 15.41 atomic percent
Pt (Pt_La): Composition = 84.59 atomic percent

See also

vacuum_mask

set_microscope_parameters(beam_energy=None, live_time=None, tilt_stage=None, azimuth_angle=None, elevation_angle=None, energy_resolution_MnKa=None, beam_current=None, probe_area=None, real_time=None, display=True, toolkit=None)

Set the microscope parameters.

If no arguments are given, raises an interactive mode to fill the values.

Parameters:
  • beam_energy (float) – The energy of the electron beam in keV

  • live_time (float) – In seconds

  • tilt_stage (float) – In degree

  • azimuth_angle (float) – In degree

  • elevation_angle (float) – In degree

  • energy_resolution_MnKa (float) – In eV

  • beam_current (float) – In nA

  • probe_area (float) – In nm²

  • real_time (float) – In seconds

  • display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

  • toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> print(s.metadata.Acquisition_instrument.
>>>       TEM.Detector.EDS.energy_resolution_MnKa)
>>> s.set_microscope_parameters(energy_resolution_MnKa=135.)
>>> print(s.metadata.Acquisition_instrument.
>>>       TEM.Detector.EDS.energy_resolution_MnKa)
133.312296
135.0
vacuum_mask(threshold=1.0, closing=True, opening=False)

Generate mask of the vacuum region

Parameters:
  • threshold (float) – For a given pixel, maximum value in the energy axis below which the pixel is considered as vacuum.

  • closing (bool) – If true, applied a morphologic closing to the mask

  • opnening (bool) – If true, applied a morphologic opening to the mask

Returns:

mask – The mask of the region

Return type:

signal

Examples

>>> # Simulate a spectrum image with vacuum region
>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s_vac = hs.signals.BaseSignal(
        np.ones_like(s.data, dtype=float))*0.005
>>> s_vac.add_poissonian_noise()
>>> si = hs.stack([s]*3 + [s_vac])
>>> si.vacuum_mask().data
array([False, False, False,  True], dtype=bool)
class hyperspy._signals.eds_tem.LazyEDSTEMSpectrum(*args, **kwards)

Bases: EDSTEMSpectrum, LazyEDSSpectrum

Create a Signal from a numpy array.

Parameters:
  • data (numpy.ndarray) – The signal data. It can be an array of any dimensions.

  • axes ([dict/axes], optional) – List of either dictionaries or axes objects to define the axes (see the documentation of the AxesManager class for more details).

  • attributes (dict, optional) – A dictionary whose items are stored as attributes.

  • metadata (dict, optional) – A dictionary containing a set of parameters that will to stores in the metadata attribute. Some parameters might be mandatory in some cases.

  • original_metadata (dict, optional) – A dictionary containing a set of parameters that will to stores in the original_metadata attribute. It typically contains all the parameters that has been imported from the original data file.

  • ragged (bool or None, optional) – Define whether the signal is ragged or not. Overwrite the ragged value in the attributes dictionary. If None, it does nothing. Default is None.