hyperspy._signals package

Submodules

hyperspy._signals.common_signal1d module

class hyperspy._signals.common_signal1d.CommonSignal1D

Bases: object

Common functions for 1-dimensional signals.

to_signal2D()

Returns the one dimensional signal as a two dimensional signal.

See also

as_signal2D()
a method for the same purpose with more options.
signals.Signal1D.to_signal2D()
performs the inverse operation on images.
Raises:DataDimensionError: when data.ndim < 2

hyperspy._signals.common_signal2d module

class hyperspy._signals.common_signal2d.CommonSignal2D

Bases: object

Common functions for 2-dimensional signals.

to_signal1D()

Returns the image as a spectrum.

See also

as_signal1D()
a method for the same purpose with more options.
signals.Signal1D.to_signal1D()
performs the inverse operation on one

dimensional()

hyperspy._signals.complex_signal module

class hyperspy._signals.complex_signal.ComplexSignal(*args, **kwargs)

Bases: hyperspy.signal.BaseSignal

BaseSignal subclass for complex data.

amplitude

Get/set the amplitude of the data. Returns an appropriate HyperSpy signal.

angle(deg=False)

Return the angle (also known as phase or argument). If the data is real, the angle is 0 for positive values and 2$pi$ for negative values.

Parameters:deg (bool, optional) – Return angle in degrees if True, radians if False (default).
Returns:angle – The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64.
Return type:HyperSpy signal
change_dtype(dtype)

Change the data type.

Parameters:dtype (str or dtype) – Typecode or data-type to which the array is cast. For complex signals only other complex dtypes are allowed. If real valued properties are required use real, imag, amplitude and phase instead.
imag

Get/set imaginary part of the data. Returns an appropriate HyperSpy signal.

phase

Get/set the phase of the data. Returns an appropriate HyperSpy signal.

plot(navigator='auto', axes_manager=None, representation='cartesian', same_axes=True, **kwargs)

Plot the signal at the current coordinates.

For multidimensional datasets an optional figure, the “navigator”, with a cursor to navigate that data is raised. In any case it is possible to navigate the data using the sliders. Currently only signals with signal_dimension equal to 0, 1 and 2 can be plotted.

Parameters:
  • navigator ({"auto", None, "slider", "spectrum", Signal}) – If “auto”, if navigation_dimension > 0, a navigator is provided to explore the data. If navigation_dimension is 1 and the signal is an image the navigator is a spectrum obtained by integrating over the signal axes (the image). If navigation_dimension is 1 and the signal is a spectrum the navigator is an image obtained by stacking horizontally all the spectra in the dataset. If navigation_dimension is > 1, the navigator is an image obtained by integrating the data over the signal axes. Additionaly, if navigation_dimension > 2 a window with one slider per axis is raised to navigate the data. For example, if the dataset consists of 3 navigation axes X, Y, Z and one signal axis, E, the default navigator will be an image obtained by integrating the data over E at the current Z index and a window with sliders for the X, Y and Z axes will be raised. Notice that changing the Z-axis index changes the navigator in this case. If “slider” and the navigation dimension > 0 a window with one slider per axis is raised to navigate the data. If “spectrum” and navigation_dimension > 0 the navigator is always a spectrum obtained by integrating the data over all other axes. If None, no navigator will be provided. Alternatively a Signal instance can be provided. The signal dimension must be 1 (for a spectrum navigator) or 2 (for a image navigator) and navigation_shape must be 0 (for a static navigator) or navigation_shape + signal_shape must be equal to the navigator_shape of the current object (for a dynamic navigator). If the signal dtype is RGB or RGBA this parameters has no effect and is always “slider”.
  • axes_manager ({None, axes_manager}) – If None axes_manager is used.
  • representation ({'cartesian' or 'polar'}) – Determines if the real and imaginary part of the complex data is plotted (‘cartesian’, default), or if the amplitude and phase should be used (‘polar’).
  • same_axes (bool, default True) – If True (default) plot the real and imaginary parts (or amplitude and phase) in the same figure if the signal is one-dimensional.
**kwargs, optional
Additional key word arguments passed to matplotlib.imshow()
real

Get/set the real part of the data. Returns an appropriate HyperSpy signal.

unwrapped_phase(wrap_around=False, seed=None, show_progressbar=None)

Return the unwrapped phase as an appropriate HyperSpy signal.

Parameters:
  • wrap_around (bool or sequence of bool, optional) – When an element of the sequence is True, the unwrapping process will regard the edges along the corresponding axis of the image to be connected and use this connectivity to guide the phase unwrapping process. If only a single boolean is given, it will apply to all axes. Wrap around is not supported for 1D arrays.
  • seed (int, optional) – Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

phase_image – Unwrapped phase.

Return type:

BaseSignal subclass

Notes

Uses the unwrap_phase() function from skimage. The algorithm is based on Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, and Munther A. Gdeisat, “Fast two-dimensional phase-unwrapping algorithm based on sorting by reliability following a noncontinuous path”, Journal Applied Optics, Vol. 41, No. 35, pp. 7437, 2002

hyperspy._signals.complex_signal1d module

class hyperspy._signals.complex_signal1d.ComplexSignal1D(*args, **kwargs)

Bases: hyperspy._signals.complex_signal.ComplexSignal, hyperspy._signals.common_signal1d.CommonSignal1D

BaseSignal subclass for complex 1-dimensional data.

hyperspy._signals.complex_signal2d module

class hyperspy._signals.complex_signal2d.ComplexSignal2D(*args, **kw)

Bases: hyperspy._signals.complex_signal.ComplexSignal, hyperspy._signals.common_signal2d.CommonSignal2D

BaseSignal subclass for complex 2-dimensional data.

add_phase_ramp(ramp_x, ramp_y, offset=0)

Add a linear phase ramp to the wave.

Parameters:
  • ramp_x (float) – Slope of the ramp in x-direction.
  • ramp_y (float) – Slope of the ramp in y-direction.
  • offset (float, optional) – Offset of the ramp at the fulcrum.

Notes

The fulcrum of the linear ramp is at the origin and the slopes are given in units of the axis with the according scale taken into account. Both are available via the axes_manager of the signal.

plot(colorbar=True, scalebar=True, scalebar_color='white', axes_ticks=None, saturated_pixels=0, vmin=None, vmax=None, no_nans=False, centre_colormap='auto', **kwargs)

Plot the signal at the current coordinates.

For multidimensional datasets an optional figure, the “navigator”, with a cursor to navigate that data is raised. In any case it is possible to navigate the data using the sliders. Currently only signals with signal_dimension equal to 0, 1 and 2 can be plotted.

Parameters:
  • navigator ({"auto", None, "slider", "spectrum", Signal}) – If “auto”, if navigation_dimension > 0, a navigator is provided to explore the data. If navigation_dimension is 1 and the signal is an image the navigator is a spectrum obtained by integrating over the signal axes (the image). If navigation_dimension is 1 and the signal is a spectrum the navigator is an image obtained by stacking horizontally all the spectra in the dataset. If navigation_dimension is > 1, the navigator is an image obtained by integrating the data over the signal axes. Additionaly, if navigation_dimension > 2 a window with one slider per axis is raised to navigate the data. For example, if the dataset consists of 3 navigation axes X, Y, Z and one signal axis, E, the default navigator will be an image obtained by integrating the data over E at the current Z index and a window with sliders for the X, Y and Z axes will be raised. Notice that changing the Z-axis index changes the navigator in this case. If “slider” and the navigation dimension > 0 a window with one slider per axis is raised to navigate the data. If “spectrum” and navigation_dimension > 0 the navigator is always a spectrum obtained by integrating the data over all other axes. If None, no navigator will be provided. Alternatively a Signal instance can be provided. The signal dimension must be 1 (for a spectrum navigator) or 2 (for a image navigator) and navigation_shape must be 0 (for a static navigator) or navigation_shape + signal_shape must be equal to the navigator_shape of the current object (for a dynamic navigator). If the signal dtype is RGB or RGBA this parameters has no effect and is always “slider”.
  • axes_manager ({None, axes_manager}) – If None axes_manager is used.
  • colorbar (bool, optional) – If true, a colorbar is plotted for non-RGB images.
  • scalebar (bool, optional) – If True and the units and scale of the x and y axes are the same a scale bar is plotted.
  • scalebar_color (str, optional) – A valid MPL color string; will be used as the scalebar color.
  • axes_ticks ({None, bool}, optional) – If True, plot the axes ticks. If None axes_ticks are only plotted when the scale bar is not plotted. If False the axes ticks are never plotted.
  • saturated_pixels (scalar) – The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range.
  • vmax (vmin,) – vmin and vmax are used to normalize luminance data.
  • no_nans (bool, optional) – If True, set nans to zero for plotting.
  • centre_colormap ({"auto", True, False}) – If True the centre of the color scheme is set to zero. This is specially useful when using diverging color schemes. If “auto” (default), diverging color schemes are automatically centred.
  • representation ({'cartesian' or 'polar'}) – Determines if the real and imaginary part of the complex data is plotted (‘cartesian’, default), or if the amplitude and phase should be used (‘polar’).
  • same_axes (bool, default True) – If True (default) plot the real and imaginary parts (or amplitude and phase) in the same figure if the signal is one-dimensional.
**kwargs, optional
Additional key word arguments passed to matplotlib.imshow()

hyperspy._signals.dielectric_function module

class hyperspy._signals.dielectric_function.DielectricFunction(*args, **kwargs)

Bases: hyperspy._signals.complex_signal1d.ComplexSignal1D

get_electron_energy_loss_spectrum(zlp, t)
get_number_of_effective_electrons(nat, cumulative=False)
Compute the number of effective electrons using the Bethe f-sum

rule.

The Bethe f-sum rule gives rise to two definitions of the effective number (see [Egerton2011]): $n_{mathrm{eff}}left(-Imleft(epsilon^{-1}

ight) ight)$ that

we’ll call neff1 and $n_{mathrm{eff}}left(epsilon_{2}
ight)$ that we’ll call neff2. This

method computes both.

nat: float
Number of atoms (or molecules) per unit volume of the sample.
cumulative : bool
If False calculate the number of effective electrons up to the higher energy-loss of the spectrum. If True, calculate the number of effective electrons as a function of the energy-loss up to the higher energy-loss of the spectrum. True is only supported by SciPy newer than 0.13.2.
neff1, neff2: Signal1D
Signal1D instances containing neff1 and neff2. The signal and navigation dimensions are the same as the current signal if cumulative is True, otherwise the signal dimension is 0 and the navigation dimension is the same as the current signal.
[Egerton2011]Ray Egerton, “Electron Energy-Loss

Spectroscopy in the Electron Microscope”, Springer-Verlag, 2011.

hyperspy._signals.eds module

class hyperspy._signals.eds.EDSSpectrum(*args, **kwards)

Bases: hyperspy._signals.signal1d.Signal1D

add_elements(elements)

Add elements and the corresponding X-ray lines.

The list of elements is stored in metadata.Sample.elements

Parameters:elements (list of strings) – The symbol of the elements.

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> print(s.metadata.Sample.elements)
>>> s.add_elements(['Ar'])
>>> print(s.metadata.Sample.elements)
['Al' 'C' 'Cu' 'Mn' 'Zr']
['Al', 'Ar', 'C', 'Cu', 'Mn', 'Zr']
add_lines(lines=(), only_one=True, only_lines=('a', ))

Add X-rays lines to the internal list.

Although most functions do not require an internal list of X-ray lines because they can be calculated from the internal list of elements, ocassionally it might be useful to customize the X-ray lines to be use by all functions by default using this method. The list of X-ray lines is stored in metadata.Sample.xray_lines

Parameters:
  • lines (list of strings) – A list of valid element X-ray lines to add e.g. Fe_Kb. Additionally, if metadata.Sample.elements is defined, add the lines of those elements that where not given in this list. If the list is empty (default), and metadata.Sample.elements is defined, add the lines of all those elements.
  • only_one (bool) – If False, add all the lines of each element in metadata.Sample.elements that has not line defined in lines. If True (default), only add the line at the highest energy above an overvoltage of 2 (< beam energy / 2).
  • only_lines ({None, list of strings}) – If not None, only the given lines will be added.

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.add_lines()
>>> print(s.metadata.Sample.xray_lines)
['Al_Ka', 'C_Ka', 'Cu_La', 'Mn_La', 'Zr_La']
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.set_microscope_parameters(beam_energy=30)
>>> s.add_lines()
>>> print(s.metadata.Sample.xray_lines)
['Al_Ka', 'C_Ka', 'Cu_Ka', 'Mn_Ka', 'Zr_La']
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.add_lines()
>>> print(s.metadata.Sample.xray_lines)
>>> s.add_lines(['Cu_Ka'])
>>> print(s.metadata.Sample.xray_lines)
['Al_Ka', 'C_Ka', 'Cu_La', 'Mn_La', 'Zr_La']
['Al_Ka', 'C_Ka', 'Cu_Ka', 'Cu_La', 'Mn_La', 'Zr_La']
add_xray_lines_markers(xray_lines)

Add marker on a spec.plot() with the name of the selected X-ray lines

Parameters:xray_lines (list of string) – A valid list of X-ray lines
estimate_background_windows(line_width=[2, 2], windows_width=1, xray_lines=None)

Estimate two windows around each X-ray line containing only the background.

Parameters:
  • line_width (list of two floats) – The position of the two windows around the X-ray line is given by the line_width (left and right) times the calculated FWHM of the line.
  • windows_width (float) – The width of the windows is is the windows_width times the calculated FWHM of the line.
  • xray_lines (None or list of string) – If None, use metadata.Sample.elements.xray_lines. Else, provide an iterable containing a list of valid X-ray lines symbols.
Returns:

windows_position – The position of the windows in energy. Each line corresponds to a X-ray line. In a line, the two first values correspond to the limits of the left window and the two last values correspond to the limits of the right window.

Return type:

2D array of float

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s.add_lines()
>>> bw = s.estimate_background_windows(line_width=[5.0, 2.0])
>>> s.plot(background_windows=bw)
>>> s.get_lines_intensity(background_windows=bw, plot_result=True)
Fe_Ka at 6.4039 keV : Intensity = 2754.00
Pt_La at 9.4421 keV : Intensity = 15090.00
estimate_integration_windows(windows_width=2.0, xray_lines=None)

Estimate a window of integration for each X-ray line.

Parameters:
  • windows_width (float) – The width of the integration windows is the ‘windows_width’ times the calculated FWHM of the line.
  • xray_lines (None or list of string) – If None, use ‘metadata.Sample.elements.xray_lines’. Else, provide an iterable containing a list of valid X-ray lines symbols.
Returns:

integration_windows – The positions of the windows in energy. Each row corresponds to a X-ray line. Each row contains the left and right value of the window.

Return type:

2D array of float

Examples

>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s.add_lines()
>>> iw = s.estimate_integration_windows()
>>> s.plot(integration_windows=iw)
>>> s.get_lines_intensity(integration_windows=iw, plot_result=True)
Fe_Ka at 6.4039 keV : Intensity = 3710.00
Pt_La at 9.4421 keV : Intensity = 15872.00
get_lines_intensity(xray_lines=None, integration_windows=2.0, background_windows=None, plot_result=False, only_one=True, only_lines=('a', ), **kwargs)

Return the intensity map of selected Xray lines.

The intensities, the number of X-ray counts, are computed by suming the spectrum over the different X-ray lines. The sum window width is calculated from the energy resolution of the detector as defined in ‘energy_resolution_MnKa’ of the metadata. Backgrounds average in provided windows can be subtracted from the intensities.

Parameters:
  • xray_lines ({None, "best", 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.
  • integration_windows (Float or array) – If float, the width of the integration windows is the ‘integration_windows_width’ times the calculated FWHM of the line. Else provide an array for which each row corresponds to a X-ray line. Each row contains the left and right value of the window.
  • background_windows (None or 2D array of float) – If None, no background subtraction. Else, the backgrounds average in the windows are subtracted from the return intensities. ‘background_windows’ provides the position of the windows in energy. Each line corresponds to a X-ray line. In a line, the two first values correspond to the limits of the left window and the two last values correspond to the limits of the right window.
  • 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 BaseSignal subclasses.

Return type:

list

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.get_lines_intensity(['Mn_Ka'], plot_result=True)
Mn_La at 0.63316 keV : Intensity = 96700.00
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.plot(['Mn_Ka'], integration_windows=2.1)
>>> s.get_lines_intensity(['Mn_Ka'],
>>>                       integration_windows=2.1, plot_result=True)
Mn_Ka at 5.8987 keV : Intensity = 53597.00
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.set_elements(['Mn'])
>>> s.set_lines(['Mn_Ka'])
>>> bw = s.estimate_background_windows()
>>> s.plot(background_windows=bw)
>>> s.get_lines_intensity(background_windows=bw, plot_result=True)
Mn_Ka at 5.8987 keV : Intensity = 46716.00
get_take_off_angle()

Calculate the take-off-angle (TOA).

TOA is the angle with which the X-rays leave the surface towards the detector. Parameters are read in ‘SEM.tilt_stage’, ‘Acquisition_instrument.SEM.Detector.EDS.azimuth_angle’ and ‘SEM.Detector.EDS.elevation_angle’ in ‘metadata’.

Returns:take_off_angle – in Degree
Return type:float

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.get_take_off_angle()
37.0
>>> s.set_microscope_parameters(tilt_stage=20.)
>>> s.get_take_off_angle()
57.0

See also

hs.eds.take_off_angle()

Notes

Defined by M. Schaffer et al., Ultramicroscopy 107(8), pp 587-597 (2007)

plot(xray_lines=False, only_lines=('a', 'b'), only_one=False, background_windows=None, integration_windows=None, **kwargs)

Plot the EDS spectrum. The following markers can be added

  • The position of the X-ray lines and their names.
  • The background windows associated with each X-ray lines. A black line

links the left and right window with the average value in each window.

Parameters:
  • xray_lines ({False, True, 'from_elements', list of string}) – If not False, indicate the position and the name of the X-ray lines. If True, if metadata.Sample.elements.xray_lines contains a list of lines use those. If metadata.Sample.elements.xray_lines is undefined or empty or if xray_lines equals ‘from_elements’ and 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.
  • only_lines (None or list of strings) – If not None, use only the given lines (eg. (‘a’,’Kb’)). If None, use all lines.
  • 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).
  • background_windows (None or 2D array of float) – If not None, add markers at the position of the windows in energy. Each line corresponds to a X-ray lines. In a line, the two first value corresponds to the limit of the left window and the two last values corresponds to the limit of the right window.
  • integration_windows (None or 'auto' or float or 2D array of float) – If not None, add markers at the position of the integration windows. If ‘auto’ (or float), the width of the integration windows is 2.0 (or float) times the calculated FWHM of the line. see ‘estimate_integration_windows’. Else provide an array for which each row corresponds to a X-ray line. Each row contains the left and right value of the window.
  • kwargs – The extra keyword arguments for plot()

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.plot()
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.plot(True)
>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s.add_lines()
>>> bw = s.estimate_background_windows()
>>> s.plot(background_windows=bw)
>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.plot(['Mn_Ka'], integration_windows='auto')
>>> s = hs.datasets.example_signals.EDS_TEM_Spectrum()
>>> s.add_lines()
>>> bw = s.estimate_background_windows()
>>> s.plot(background_windows=bw, integration_windows=2.1)
rebin(new_shape)

Rebins the data to the new shape

Parameters:new_shape (tuple of ints) – The new shape must be a divisor of the original shape

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> print(s)
>>> print(s.rebin([512]))
<EDSSEMSpectrum, title: EDS SEM Signal1D, dimensions: (|1024)>
<EDSSEMSpectrum, title: EDS SEM Signal1D, dimensions: (|512)>
remove_xray_lines_markers(xray_lines)

Remove marker previosuly added on a spec.plot() with the name of the selected X-ray lines

Parameters:xray_lines (list of string) – A valid list of X-ray lines to remove
set_elements(elements)

Erase all elements and set them.

Parameters:elements (list of strings) – A list of chemical element symbols.

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> print(s.metadata.Sample.elements)
>>> s.set_elements(['Al'])
>>> print(s.metadata.Sample.elements)
['Al' 'C' 'Cu' 'Mn' 'Zr']
['Al']
set_lines(lines, only_one=True, only_lines=('a', ))

Erase all Xrays lines and set them.

See add_lines for details.

Parameters:
  • lines (list of strings) – A list of valid element X-ray lines to add e.g. Fe_Kb. Additionally, if metadata.Sample.elements is defined, add the lines of those elements that where not given in this list.
  • only_one (bool) – If False, add all the lines of each element in metadata.Sample.elements that has not line defined in lines. If True (default), only add the line at the highest energy above an overvoltage of 2 (< beam energy / 2).
  • only_lines ({None, list of strings}) – If not None, only the given lines will be added.

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.add_lines()
>>> print(s.metadata.Sample.xray_lines)
>>> s.set_lines(['Cu_Ka'])
>>> print(s.metadata.Sample.xray_lines)
['Al_Ka', 'C_Ka', 'Cu_La', 'Mn_La', 'Zr_La']
['Al_Ka', 'C_Ka', 'Cu_Ka', 'Mn_La', 'Zr_La']
sum(axis=None, out=None)

Sum the data over the given axis.

Parameters:axis ({int, string}) – The axis can be specified using the index of the axis in axes_manager or the axis name.
Returns:s
Return type:Signal1D

See also

sum_in_mask(), mean()

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s.sum(0).data
array(1000279)

hyperspy._signals.eds_sem module

class hyperspy._signals.eds_sem.EDSSEMSpectrum(*args, **kwards)

Bases: hyperspy._signals.eds.EDSSpectrum

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

Create a model for the current SEM EDS data.

Parameters:
  • auto_background (boolean, default True) – If True, adds automatically a polynomial order 6 to the model, using the edsmodel.add_polynomial_background method.
  • auto_add_lines (boolean, 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:

EDSSEMModel instance.

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.

Examples

>>> ref = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> s = hs.signals.EDSSEMSpectrum(
>>>     hs.datasets.example_signals.EDS_SEM_Spectrum().data)
>>> print(s.axes_manager[0].scale)
>>> s.get_calibration_from(ref)
>>> print(s.axes_manager[0].scale)
1.0
0.01
set_microscope_parameters(beam_energy=None, live_time=None, tilt_stage=None, azimuth_angle=None, elevation_angle=None, energy_resolution_MnKa=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 second
  • tilt_stage (float) – In degree
  • azimuth_angle (float) – In degree
  • elevation_angle (float) – In degree
  • energy_resolution_MnKa (float) – In eV

Examples

>>> s = hs.datasets.example_signals.EDS_SEM_Spectrum()
>>> print('Default value %s eV' %
>>>       s.metadata.Acquisition_instrument.
>>>       SEM.Detector.EDS.energy_resolution_MnKa)
>>> s.set_microscope_parameters(energy_resolution_MnKa=135.)
>>> print('Now set to %s eV' %
>>>       s.metadata.Acquisition_instrument.
>>>       SEM.Detector.EDS.energy_resolution_MnKa)
Default value 130.0 eV
Now set to 135.0 eV

hyperspy._signals.eds_tem module

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

Bases: hyperspy._signals.eds.EDSSpectrum

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

Create a model for the current TEM EDS data.

Parameters:
  • auto_background (boolean, default True) – If True, adds automatically a polynomial order 6 to the model, using the edsmodel.add_polynomial_background method.
  • auto_add_lines (boolean, 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)

Decomposition with a choice of algorithms

The results are stored in self.learning_results

Parameters:
  • normalize_poissonian_noise (bool) – If True, scale the SI to normalize Poissonian noise
  • navigation_mask (None or float or boolean numpy array) – 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) – If true, applied a morphologic closing to the maks obtained by vacuum_mask.
  • algorithm ('svd' | 'fast_svd' | 'mlpca' | 'fast_mlpca' | 'nmf' |) – ‘sparse_pca’ | ‘mini_batch_sparse_pca’
  • output_dimension (None or int) – number of components to keep/calculate
  • centre (None | 'variables' | 'trials') – If None no centring is applied. If ‘variable’ the centring will be performed in the variable axis. If ‘trials’, the centring will be performed in the ‘trials’ axis. It only has effect when using the svd or fast_svd algorithms
  • auto_transpose (bool) – If True, automatically transposes the data to boost performance. Only has effect when using the svd of fast_svd algorithms.
  • 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
  • var_func (function or numpy array) – If function, it will apply it to the dataset to obtain the var_array. Alternatively, it can a an array with the coefficients of a polynomial.
  • polyfit
  • reproject (None | signal | navigation | both) – If not None, the results of the decomposition will be projected in the selected masked area.

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.

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
quantification(intensities, method, factors='auto', composition_units='atomic', navigation_mask=1.0, closing=True, plot_result=False, **kwargs)

Quantification using Cliff-Lorimer, the zeta-factor method, or ionization cross sections.

Parameters:
  • intensities (list of signal) – the intensitiy for each X-ray lines.
  • method ('CL' or 'zeta' or '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 ('weight' or 'atomic') – The quantification returns the composition in atomic percent by default, but can also return weight percent if specified.
  • navigation_mask (None or float or signal) – The navigation locations marked as True are not used in the quantification. If int is given the vacuum_mask method is used to generate a mask with the int value as threhsold. Else provides a signal with the navigation shape.
  • 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.
  • 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.
  • 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)

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^2
  • real_time (float) – In seconds

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

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)
Returns:mask – The mask of the region
Return type:signal

hyperspy._signals.eels module

class hyperspy._signals.eels.EELSSpectrum(*args, **kwargs)

Bases: hyperspy._signals.signal1d.Signal1D

add_elements(elements, include_pre_edges=False)

Declare the elemental composition of the sample.

The ionisation edges of the elements present in the current energy range will be added automatically.

Parameters:
  • elements (tuple of strings) – The symbol of the elements. Note this input must always be in the form of a tuple. Meaning: add_elements((‘C’,)) will work, while add_elements((‘C’)) will NOT work.
  • include_pre_edges (bool) – If True, the ionization edges with an onset below the lower energy limit of the SI will be incluided

Examples

>>> s = hs.signals.EELSSpectrum(np.arange(1024))
>>> s.add_elements(('C', 'O'))
Adding C_K subshell
Adding O_K subshell
Raises:ValueError
align_zero_loss_peak(calibrate=True, also_align=[], print_stats=True, subpixel=True, mask=None, signal_range=None, show_progressbar=None, **kwargs)

Align the zero-loss peak.

This function first aligns the spectra using the result of estimate_zero_loss_peak_centre and afterward, if subpixel is True, proceeds to align with subpixel accuracy using align1D. The offset is automatically correct if calibrate is True.

Parameters:
  • calibrate (bool) – If True, set the offset of the spectral axis so that the zero-loss peak is at position zero.
  • also_align (list of signals) – A list containing other spectra of identical dimensions to align using the shifts applied to the current spectrum. If calibrate is True, the calibration is also applied to the spectra in the list.
  • print_stats (bool) – If True, print summary statistics of the ZLP maximum before the aligment.
  • subpixel (bool) – If True, perform the alignment with subpixel accuracy using cross-correlation.
  • mask (Signal1D of bool data type.) – It must have signal_dimension = 0 and navigation_shape equal to the current signal. Where mask is True the shift is not computed and set to nan.
  • signal_range (tuple of integers, tuple of floats. Optional) – Will only search for the ZLP within the signal_range. If given in integers, the range will be in index values. If given floats, the range will be in spectrum values. Useful if there are features in the spectrum which are more intense than the ZLP. Default is searching in the whole signal.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.

Examples

>>>> s_ll.align_zero_loss_peak()

Aligning both the lowloss signal and another signal >>>> s_ll.align_zero_loss_peak(also_align=[s])

Aligning within a narrow range of the lowloss signal >>>> s_ll.align_zero_loss_peak(signal_range=(-10.,10.))

See also

estimate_zero_loss_peak_centre(), align1D(), estimate_shift1D.()

Notes

Any extra keyword arguments are passed to align1D. For more information read its docstring.

create_model(ll=None, auto_background=True, auto_add_edges=True, GOS=None, dictionary=None)

Create a model for the current EELS data.

Parameters:
  • ll (EELSSpectrum, optional) – 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 (boolean, default True) – 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 (boolean, default True) – If True, and if spectrum is an EELS instance, it will automatically add the ionization edges as defined in the Signal1D instance. Adding a new element to the spectrum using the components.EELSSpectrum.add_elements method automatically add the corresponding ionisation edges to the model.
  • GOS ({'hydrogenic' | 'Hartree-Slater'}, optional) – The generalized oscillation strenght calculations to use for the core-loss EELS edges. If None the Hartree-Slater GOS are used if available, otherwise it uses the hydrogenic GOS.
  • dictionary ({None | dict}, optional) – A dictionary to be used to recreate a model. Usually generated using hyperspy.model.as_dictionary()
Returns:

model

Return type:

EELSModel instance.

estimate_elastic_scattering_intensity(threshold, show_progressbar=None)

Rough estimation of the elastic scattering intensity by truncation of a EELS low-loss spectrum.

Parameters:
  • threshold ({Signal1D, float, int}) – Truncation energy to estimate the intensity of the elastic scattering. The threshold can be provided as a signal of the same dimension as the input spectrum navigation space containing the threshold value in the energy units. Alternatively a constant threshold can be specified in energy/index units by passing float/int.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

I0 – The elastic scattering intensity.

Return type:

Signal1D

estimate_elastic_scattering_threshold(window=10.0, tol=None, window_length=5, polynomial_order=3, start=1.0)

Calculate the first inflexion point of the spectrum derivative within a window.

This method assumes that the zero-loss peak is located at position zero in all the spectra. Currently it looks for an inflexion point, that can be a local maximum or minimum. Therefore, to estimate the elastic scattering threshold start + window must be less than the first maximum for all spectra (often the bulk plasmon maximum). If there is more than one inflexion point in energy the window it selects the smoother one what, often, but not always, is a good choice in this case.

Parameters:
  • window ({None, float}) – If None, the search for the local inflexion point is performed using the full energy range. A positive float will restrict the search to the (0,window] energy window, where window is given in the axis units. If no inflexion point is found in this spectral range the window value is returned instead.
  • tol ({None, float}) – The threshold tolerance for the derivative. If “auto” it is automatically calculated as the minimum value that guarantees finding an inflexion point in all the spectra in given energy range.
  • window_length (int) – If non zero performs order three Savitzky-Golay smoothing to the data to avoid falling in local minima caused by the noise. It must be an odd interger.
  • polynomial_order (int) – Savitzky-Golay filter polynomial order.
  • start (float) – Position from the zero-loss peak centre from where to start looking for the inflexion point.
Returns:

threshold – A Signal1D of the same dimension as the input spectrum navigation space containing the estimated threshold. Where the threshold couldn’t be estimated the value is set to nan.

Return type:

Signal1D

See also

estimate_elastic_scattering_intensity(), align_zero_loss_peak(), find_peaks1D_ohaver(), fourier_ratio_deconvolution.()

Notes

The main purpose of this method is to be used as input for estimate_elastic_scattering_intensity. Indeed, for currently achievable energy resolutions, there is not such a thing as a elastic scattering threshold. Therefore, please be aware of the limitations of this method when using it.

estimate_thickness(threshold, zlp=None)

Estimates the thickness (relative to the mean free path) of a sample using the log-ratio method.

The current EELS spectrum must be a low-loss spectrum containing the zero-loss peak. The hyperspectrum must be well calibrated and aligned.

Parameters:
  • threshold ({Signal1D, float, int}) – Truncation energy to estimate the intensity of the elastic scattering. The threshold can be provided as a signal of the same dimension as the input spectrum navigation space containing the threshold value in the energy units. Alternatively a constant threshold can be specified in energy/index units by passing float/int.
  • zlp ({None, EELSSpectrum}) – If not None the zero-loss peak intensity is calculated from the ZLP spectrum supplied by integration using Simpson’s rule. If None estimates the zero-loss peak intensity using estimate_elastic_scattering_intensity by truncation.
Returns:

s – The thickness relative to the MFP. It returns a Signal1D, Signal2D or a BaseSignal, depending on the current navigation dimensions.

Return type:

Signal1D

Notes

For details see: Egerton, R. Electron Energy-Loss Spectroscopy in the Electron Microscope. Springer-Verlag, 2011.

estimate_zero_loss_peak_centre(mask=None)

Estimate the posision of the zero-loss peak.

This function provides just a coarse estimation of the position of the zero-loss peak centre by computing the position of the maximum of the spectra. For subpixel accuracy use estimate_shift1D.

Parameters:mask (Signal1D of bool data type.) – It must have signal_dimension = 0 and navigation_shape equal to the current signal. Where mask is True the shift is not computed and set to nan.
Returns:zlpc – The estimated position of the maximum of the ZLP peak.
Return type:Signal1D subclass

Notes

This function only works when the zero-loss peak is the most intense feature in the spectrum. If it is not in most cases the spectrum can be cropped to meet this criterium. Alternatively use estimate_shift1D.

See also

estimate_shift1D(), align_zero_loss_peak()

fourier_log_deconvolution(zlp, add_zlp=False, crop=False)

Performs fourier-log deconvolution.

Parameters:
  • zlp (EELSSpectrum) – The corresponding zero-loss peak.
  • add_zlp (bool) – If True, adds the ZLP to the deconvolved spectrum
  • crop (bool) – If True crop the spectrum to leave out the channels that have been modified to decay smoothly to zero at the sides of the spectrum.
Returns:

Return type:

An EELSSpectrum containing the current data deconvolved.

Notes

For details see: Egerton, R. Electron Energy-Loss Spectroscopy in the Electron Microscope. Springer-Verlag, 2011.

fourier_ratio_deconvolution(ll, fwhm=None, threshold=None, extrapolate_lowloss=True, extrapolate_coreloss=True)

Performs Fourier-ratio deconvolution.

The core-loss should have the background removed. To reduce
the noise amplication the result is convolved with a

Gaussian function.

Parameters:
  • ll (EELSSpectrum) – The corresponding low-loss (ll) EELSSpectrum.
  • fwhm (float or None) – Full-width half-maximum of the Gaussian function by which the result of the deconvolution is convolved. It can be used to select the final SNR and spectral resolution. If None, the FWHM of the zero-loss peak of the low-loss is estimated and used.
  • threshold ({None, float}) –

    Truncation energy to estimate the intensity of the elastic scattering. If None the threshold is taken as the

    first minimum after the ZLP centre.
  • extrapolate_coreloss (extrapolate_lowloss,) – If True the signals are extrapolated using a power law,

Notes

For details see: Egerton, R. Electron Energy-Loss Spectroscopy in the Electron Microscope. Springer-Verlag, 2011.

generate_subshells(include_pre_edges=False)

Calculate the subshells for the current energy range for the elements present in self.elements

Parameters:include_pre_edges (bool) – If True, the ionization edges with an onset below the lower energy limit of the SI will be incluided
kramers_kronig_analysis(zlp=None, iterations=1, n=None, t=None, delta=0.5, full_output=False)

Calculate the complex dielectric function from a single scattering distribution (SSD) using the Kramers-Kronig relations.

It uses the FFT method as in [Egerton2011]. The SSD is an EELSSpectrum instance containing SSD low-loss EELS with no zero-loss peak. The internal loop is devised to approximately subtract the surface plasmon contribution supposing an unoxidized planar surface and neglecting coupling between the surfaces. This method does not account for retardation effects, instrumental broading and surface plasmon excitation in particles.

Note that either refractive index or thickness are required. If both are None or if both are provided an exception is raised.

Parameters:
  • zlp ({None, number, Signal1D}) – ZLP intensity. It is optional (can be None) if t is None and n is not None and the thickness estimation is not required. If t is not None, the ZLP is required to perform the normalization and if t is not None, the ZLP is required to calculate the thickness. If the ZLP is the same for all spectra, the integral of the ZLP can be provided as a number. Otherwise, if the ZLP intensity is not the same for all spectra, it can be provided as i) a Signal1D of the same dimensions as the current signal containing the ZLP spectra for each location ii) a BaseSignal of signal dimension 0 and navigation_dimension equal to the current signal containing the integrated ZLP intensity.
  • iterations (int) – Number of the iterations for the internal loop to remove the surface plasmon contribution. If 1 the surface plasmon contribution is not estimated and subtracted (the default is 1).
  • n ({None, float}) – The medium refractive index. Used for normalization of the SSD to obtain the energy loss function. If given the thickness is estimated and returned. It is only required when t is None.
  • t ({None, number, Signal1D}) – The sample thickness in nm. Used for normalization of the SSD to obtain the energy loss function. It is only required when n is None. If the thickness is the same for all spectra it can be given by a number. Otherwise, it can be provided as a BaseSignal with signal dimension 0 and navigation_dimension equal to the current signal.
  • delta (float) – A small number (0.1-0.5 eV) added to the energy axis in specific steps of the calculation the surface loss correction to improve stability.
  • full_output (bool) – If True, return a dictionary that contains the estimated thickness if t is None and the estimated surface plasmon excitation and the spectrum corrected from surface plasmon excitations if iterations > 1.
Returns:

  • eps (DielectricFunction instance) –

    The complex dielectric function results,

    $epsilon = epsilon_1 + i*epsilon_2$,

    contained in an DielectricFunction instance.

  • output (Dictionary (optional)) – A dictionary of optional outputs with the following keys:

    thickness

    The estimated thickness in nm calculated by normalization of the SSD (only when t is None)

    surface plasmon estimation

    The estimated surface plasmon excitation (only if iterations > 1.)

Raises:
  • ValuerError – If both n and t are undefined (None).
  • AttribureError – If the beam_energy or the collection semi-angle are not defined in metadata.

Notes

This method is based in Egerton’s Matlab code [Egerton2011] with some minor differences:

  • The integrals are performed using the simpsom rule instead of using a summation.
  • The wrap-around problem when computing the ffts is workarounded by padding the signal instead of substracting the reflected tail.
[Egerton2011]Ray Egerton, “Electron Energy-Loss Spectroscopy in the Electron Microscope”, Springer-Verlag, 2011.
power_law_extrapolation(window_size=20, extrapolation_size=1024, add_noise=False, fix_neg_r=False)

Extrapolate the spectrum to the right using a powerlaw

Parameters:
  • window_size (int) – The number of channels from the right side of the spectrum that are used to estimate the power law parameters.
  • extrapolation_size (int) – Size of the extrapolation in number of channels
  • add_noise (bool) – If True, add poissonian noise to the extrapolated spectrum.
  • fix_neg_r (bool) – If True, the negative values for the “components.PowerLaw” parameter r will be flagged and the extrapolation will be done with a constant zero-value.
Returns:

Return type:

A new spectrum, with the extrapolation.

richardson_lucy_deconvolution(psf, iterations=15, mask=None, show_progressbar=None)

1D Richardson-Lucy Poissonian deconvolution of the spectrum by the given kernel.

Parameters:
  • iterations (int) – Number of iterations of the deconvolution. Note that increasing the value will increase the noise amplification.
  • psf (EELSSpectrum) – It must have the same signal dimension as the current spectrum and a spatial dimension of 0 or the same as the current spectrum.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
  • Notes
  • -----
  • details on the algorithm see Gloter, A., A. Douiri, (For) –
  • Tence, and C. Colliex. “Improving Energy Resolution of (M.) –
  • Spectra (EELS) –
  • 96, no. 3–4 (September 2003) (Ultramicroscopy) –
set_microscope_parameters(beam_energy=None, convergence_angle=None, collection_angle=None)

Set the microscope parameters that are necessary to calculate the GOS.

If not all of them are defined, raises in interactive mode raises an UI item to fill the values

beam_energy: float
The energy of the electron beam in keV
convengence_angle : float
The microscope convergence semi-angle in mrad.
collection_angle : float
The collection semi-angle in mrad.

hyperspy._signals.signal1d module

class hyperspy._signals.signal1d.Signal1D(*args, **kwargs)

Bases: hyperspy.signal.BaseSignal, hyperspy._signals.common_signal1d.CommonSignal1D

align1D(start=None, end=None, reference_indices=None, max_shift=None, interpolate=True, number_of_interpolation_points=5, interpolation_method='linear', crop=True, expand=False, fill_value=nan, also_align=[], mask=None, show_progressbar=None)

Estimate the shifts in the signal axis using cross-correlation and use the estimation to align the data in place. This method can only estimate the shift by comparing unidimensional features that should not change the position. To decrease memory usage, time of computation and improve accuracy it is convenient to select the feature of interest setting the start and end keywords. By default interpolation is used to obtain subpixel precision. :param start, end: The limits of the interval. If int they are taken as the

axis index. If float they are taken as the axis value.
Parameters:
  • reference_indices (tuple of ints or None) – Defines the coordinates of the spectrum that will be used as eference. If None the spectrum at the current coordinates is used for this purpose.
  • max_shift (int) – “Saturation limit” for the shift.
  • interpolate (bool) – If True, interpolation is used to provide sub-pixel accuracy.
  • number_of_interpolation_points (int) – Number of interpolation points. Warning: making this number too big can saturate the memory
  • interpolation_method (str or int) – Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic, ‘cubic’) or as an integer specifying the order of the spline interpolator to use.
  • crop (bool) – If True automatically crop the signal axis at both ends if needed.
  • expand (bool) – If True, the data will be expanded to fit all data after alignment. Overrides crop.
  • fill_value (float) – If crop is False fill the data outside of the original interval with the given value where needed.
  • also_align (list of signals) – A list of BaseSignal instances that has exactly the same dimensions as this one and that will be aligned using the shift map estimated using the this signal.
  • mask (BaseSignal of bool data type.) – It must have signal_dimension = 0 and navigation_shape equal to the current signal. Where mask is True the shift is not computed and set to nan.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

Return type:

An array with the result of the estimation. The shift will be

Raises:

SignalDimensionError if the signal dimension is not 1.

calibrate(*args, **kwargs)

Calibrate the spectral dimension using a gui. It displays a window where the new calibration can be set by: * Setting the offset, units and scale directly * Selection a range by dragging the mouse on the spectrum figure

and

setting the new values for the given range limits .. rubric:: Notes

For this method to work the output_dimension must be 1. Set the view accordingly

Raises:SignalDimensionError if the signal dimension is not 1.
create_model(dictionary=None)

Create a model for the current data.

Returns:model
Return type:Model1D instance.
crop_signal1D(*args, **kwargs)

Crop in place the spectral dimension.

Parameters:righ_value (left_value,) – If int the values are taken as indices. If float they are converted to indices using the spectral axis calibration. If left_value is None crops from the beginning of the axis. If right_value is None crops up to the end of the axis. If both are None the interactive cropping interface is activated enabling cropping the spectrum using a span selector in the signal plot.
Raises:SignalDimensionError if the signal dimension is not 1.
estimate_peak_width(factor=0.5, window=None, return_interval=False, show_progressbar=None)

Estimate the width of the highest intensity of peak of the spectra at a given fraction of its maximum.

It can be used with asymmetric peaks. For accurate results any background must be previously substracted. The estimation is performed by interpolation using cubic splines.

Parameters:
  • factor (0 < float < 1) – The default, 0.5, estimates the FWHM.
  • window (None, float) – The size of the window centred at the peak maximum used to perform the estimation. The window size must be chosen with care: if it is narrower than the width of the peak at some positions or if it is so wide that it includes other more intense peaks this method cannot compute the width and a NaN is stored instead.
  • return_interval (bool) – If True, returns 2 extra signals with the positions of the desired height fraction at the left and right of the peak.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

  • width or [width, left, right], depending on the value of
  • return_interval.

estimate_shift1D(start=None, end=None, reference_indices=None, max_shift=None, interpolate=True, number_of_interpolation_points=5, mask=None, show_progressbar=None)
Estimate the shifts in the current signal axis using
cross-correlation.

This method can only estimate the shift by comparing unidimensional features that should not change the position in the signal axis. To decrease the memory usage, the time of computation and the accuracy of the results it is convenient to select the feature of interest providing sensible values for start and end. By default interpolation is used to obtain subpixel precision. :param start, end: The limits of the interval. If int they are taken as the

axis index. If float they are taken as the axis value.
Parameters:
  • reference_indices (tuple of ints or None) – Defines the coordinates of the spectrum that will be used as eference. If None the spectrum at the current coordinates is used for this purpose.
  • max_shift (int) – “Saturation limit” for the shift.
  • interpolate (bool) – If True, interpolation is used to provide sub-pixel accuracy.
  • number_of_interpolation_points (int) – Number of interpolation points. Warning: making this number too big can saturate the memory
  • mask (BaseSignal of bool data type.) – It must have signal_dimension = 0 and navigation_shape equal to the current signal. Where mask is True the shift is not computed and set to nan.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

Return type:

An array with the result of the estimation in the axis units.

Raises:

SignalDimensionError if the signal dimension is not 1.

filter_butterworth(cutoff_frequency_ratio=None, type='low', order=2)

Butterworth filter in place. :raises: SignalDimensionError if the signal dimension is not 1.

find_peaks1D_ohaver(xdim=None, slope_thresh=0, amp_thresh=None, subchannel=True, medfilt_radius=5, maxpeakn=30000, peakgroup=10)

Find peaks along a 1D line (peaks in spectrum/spectra).

Function to locate the positive peaks in a noisy x-y data set.

Detects peaks by looking for downward zero-crossings in the first derivative that exceed ‘slope_thresh’.

Returns an array containing position, height, and width of each peak.

‘slope_thresh’ and ‘amp_thresh’, control sensitivity: higher values will neglect smaller features.

peakgroup is the number of points around the top peak to search around

Parameters:
  • slope_thresh (float (optional)) – 1st derivative threshold to count the peak default is set to 0.5 higher values will neglect smaller features.
  • amp_thresh (float (optional)) – intensity threshold above which default is set to 10% of max(y) higher values will neglect smaller features.
  • medfilt_radius (int (optional)) – median filter window to apply to smooth the data (see scipy.signal.medfilt) if 0, no filter will be applied. default is set to 5
  • peakgroup (int (optional)) – number of points around the “top part” of the peak default is set to 10
  • maxpeakn (int (optional)) – number of maximum detectable peaks default is set to 5000
  • subpix (bool (optional)) – default is set to True
Returns:

  • peaks (structured array of shape _navigation_shape_in_array in which)
  • each cell contains an array that contains as many structured arrays as
  • peaks where found at that location and which fields (position, height,)
  • width, contains position, height, and width of each peak.

Raises:

SignalDimensionError if the signal dimension is not 1.

gaussian_filter(FWHM)

Applies a Gaussian filter in the spectral dimension in place.

Parameters:

FWHM (float) – The Full Width at Half Maximum of the gaussian in the spectral axis units

Raises:
  • ValueError if FWHM is equal or less than zero.
  • SignalDimensionError if the signal dimension is not 1.
hanning_taper(side='both', channels=None, offset=0)

Apply a hanning taper to the data in place.

Parameters:
  • side ({'left', 'right', 'both'}) –
  • channels ({None, int}) – The number of channels to taper. If None 5% of the total number of channels are tapered.
  • offset (int) –
Returns:

Return type:

channels

Raises:

SignalDimensionError if the signal dimension is not 1.

integrate_in_range(signal_range='interactive')

Sums the spectrum over an energy range, giving the integrated area. The energy range can either be selected through a GUI or the command line. :param signal_range: l and r are the left and right limits of the range. They can be

numbers or None, where None indicates the extremes of the interval. If l and r are floats the signal_range will be in axis units (for example eV). If l and r are integers the signal_range will be in index units. When signal_range is “interactive” (default) the range is selected using a GUI.
Returns:integrated_spectrum
Return type:BaseSignal subclass

See also

integrate_simpson()

Examples

Using the GUI >>> s.integrate_in_range() Using the CLI >>> s_int = s.integrate_in_range(signal_range=(560,None)) Selecting a range in the axis units, by specifying the signal range with floats. >>> s_int = s.integrate_in_range(signal_range=(560.,590.)) Selecting a range using the index, by specifying the signal range with integers. >>> s_int = s.integrate_in_range(signal_range=(100,120))

interpolate_in_between(start, end, delta=3, show_progressbar=None, **kwargs)

Replace the data in a given range by interpolation. The operation is performed in place. :param start, end: The limits of the interval. If int they are taken as the

axis index. If float they are taken as the axis value.
Parameters:
  • delta ({int | float}) – The windows around the (start, end) to use for interpolation
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
  • extra keyword arguments are passed to (All) –
  • See the function documentation (scipy.interpolate.interp1d.) –
  • details. (for) –
Raises:

SignalDimensionError if the signal dimension is not 1.

remove_background(signal_range='interactive', background_type='PowerLaw', polynomial_order=2, fast=True, show_progressbar=None)

Remove the background, either in place using a gui or returned as a new spectrum using the command line. :param signal_range: If this argument is not specified, the signal range has to be

selected using a GUI. And the original spectrum will be replaced. If tuple is given, the a spectrum will be returned.
Parameters:
  • background_type (string) – The type of component which should be used to fit the background. Possible components: PowerLaw, Gaussian, Offset, Polynomial If Polynomial is used, the polynomial order can be specified
  • polynomial_order (int, default 2) – Specify the polynomial order if a Polynomial background is used.
  • fast (bool) – If True, perform an approximative estimation of the parameters. If False, the signal is fitted using non-linear least squares afterwards.This is slower compared to the estimation but possibly more accurate.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.

Examples

Using gui, replaces spectrum s >>>> s.remove_background() Using command line, returns a spectrum >>>> s = s.remove_background(signal_range=(400,450), background_type=’PowerLaw’) Using a full model to fit the background >>>> s = s.remove_background(signal_range=(400,450), fast=False)

Raises:SignalDimensionError if the signal dimension is not 1.
shift1D(shift_array, interpolation_method='linear', crop=True, expand=False, fill_value=nan, show_progressbar=None)

Shift the data in place over the signal axis by the amount specified by an array. :param shift_array: An array containing the shifting amount. It must have

axes_manager._navigation_shape_in_array shape.
Parameters:
  • interpolation_method (str or int) – Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic, ‘cubic’) or as an integer specifying the order of the spline interpolator to use.
  • crop (bool) – If True automatically crop the signal axis at both ends if needed.
  • expand (bool) – If True, the data will be expanded to fit all data after alignment. Overrides crop.
  • fill_value (float) – If crop is False fill the data outside of the original interval with the given value where needed.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Raises:

SignalDimensionError if the signal dimension is not 1.

smooth_lowess(smoothing_parameter=None, number_of_iterations=None, show_progressbar=None)

Lowess data smoothing in place. If smoothing_parameter or number_of_iterations are None the method is run in interactive mode. :param smoothing_parameter: Between 0 and 1. The fraction of the data used

when estimating each y-value.
Parameters:
  • number_of_iterations (int or None) – The number of residual-based reweightings to perform.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Raises:
  • SignalDimensionError if the signal dimension is not 1.
  • ImportError if statsmodels is not installed.

Notes

This method uses the lowess algorithm from statsmodels. statsmodels is required for this method.

smooth_savitzky_golay(polynomial_order=None, window_length=None, differential_order=0)

Apply a Savitzky-Golay filter to the data in place. If polynomial_order or window_length or differential_order are None the method is run in interactive mode. :param window_length: The length of the filter window (i.e. the number of coefficients).

window_length must be a positive odd integer.
Parameters:
  • polynomial_order (int) – The order of the polynomial used to fit the samples. polyorder must be less than window_length.
  • differential_order (int, optional) – The order of the derivative to compute. This must be a nonnegative integer. The default is 0, which means to filter the data without differentiating.

Notes

More information about the filter in scipy.signal.savgol_filter.

smooth_tv(smoothing_parameter=None, show_progressbar=None)

Total variation data smoothing in place. :param smoothing_parameter: Denoising weight relative to L2 minimization. If None the method

is run in interactive mode.
Parameters:show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Raises:SignalDimensionError if the signal dimension is not 1.
spikes_removal_tool(signal_mask=None, navigation_mask=None)

Graphical interface to remove spikes from EELS spectra.

Parameters:
  • signal_mask (boolean array) – Restricts the operation to the signal locations not marked as True (masked)
  • navigation_mask (boolean array) – Restricts the operation to the navigation locations not marked as True (masked)

See also

_spikes_diagnosis()

hyperspy._signals.signal1d.find_peaks_ohaver(y, x=None, slope_thresh=0.0, amp_thresh=None, medfilt_radius=5, maxpeakn=30000, peakgroup=10, subchannel=True)

Find peaks along a 1D line. Function to locate the positive peaks in a noisy x-y data set. Detects peaks by looking for downward zero-crossings in the first derivative that exceed ‘slope_thresh’. Returns an array containing position, height, and width of each peak. Sorted by position. ‘slope_thresh’ and ‘amp_thresh’, control sensitivity: higher values will neglect smaller features. :param y: 1D input array, e.g. a spectrum :type y: array :param x: 1D array describing the calibration of y (must have same shape as y) :type x: array (optional) :param slope_thresh: 1st derivative threshold to count the peak

default is set to 0.5 higher values will neglect smaller features.
Parameters:
  • amp_thresh (float (optional)) – intensity threshold above which default is set to 10% of max(y) higher values will neglect smaller features.
  • medfilt_radius (int (optional)) – median filter window to apply to smooth the data (see scipy.signal.medfilt) if 0, no filter will be applied. default is set to 5
  • peakgroup (int (optional)) – number of points around the “top part” of the peak default is set to 10
  • maxpeakn (int (optional)) – number of maximum detectable peaks default is set to 30000
  • subchannel (bool (optional)) – default is set to True
Returns:

P – contains position, height, and width of each peak

Return type:

structured array of shape (npeaks) and fields: position, width, height

Examples

>>> x = arange(0,50,0.01)
>>> y = cos(x)
>>> one_dim_findpeaks(y, x,0,0)
array([[  1.68144859e-05,   9.99999943e-01,   3.57487961e+00],
       [  6.28318614e+00,   1.00000003e+00,   3.57589018e+00],
       [  1.25663708e+01,   1.00000002e+00,   3.57600673e+00],
       [  1.88495565e+01,   1.00000002e+00,   3.57597295e+00],
       [  2.51327421e+01,   1.00000003e+00,   3.57590284e+00],
       [  3.14159267e+01,   1.00000002e+00,   3.57600856e+00],
       [  3.76991124e+01,   1.00000002e+00,   3.57597984e+00],
       [  4.39822980e+01,   1.00000002e+00,   3.57591479e+00]])

Notes

Original code from T. C. O’Haver, 1995. Version 2 Last revised Oct 27, 2006 Converted to Python by Michael Sarahan, Feb 2011. Revised to handle edges better. MCS, Mar 2011

hyperspy._signals.signal1d.interpolate1D(number_of_interpolation_points, data)

hyperspy._signals.signal2d module

class hyperspy._signals.signal2d.Signal2D(*args, **kw)

Bases: hyperspy.signal.BaseSignal, hyperspy._signals.common_signal2d.CommonSignal2D

add_ramp(ramp_x, ramp_y, offset=0)

Add a linear ramp to the signal.

Parameters:
  • ramp_x (float) – Slope of the ramp in x-direction.
  • ramp_y (float) – Slope of the ramp in y-direction.
  • offset (float, optional) – Offset of the ramp at the signal fulcrum.

Notes

The fulcrum of the linear ramp is at the origin and the slopes are given in units of the axis with the according scale taken into account. Both are available via the axes_manager of the signal.

align2D(crop=True, fill_value=nan, shifts=None, expand=False, roi=None, sobel=True, medfilter=True, hanning=True, plot=False, normalize_corr=False, reference='current', dtype='float', correlation_threshold=None, chunk_size=30, interpolation_order=1)

Align the images in place using user provided shifts or by estimating the shifts. Please, see estimate_shift2D docstring for details on the rest of the parameters not documented in the following section :param crop: If True, the data will be cropped not to include regions

with missing data
Parameters:
  • fill_value (int, float, nan) – The areas with missing data are filled with the given value. Default is nan.
  • shifts (None or list of tuples) – If None the shifts are estimated using estimate_shift2D.
  • expand (bool) – If True, the data will be expanded to fit all data after alignment. Overrides crop.
  • interpolation_order (int, default 1.) – The order of the spline interpolation. Default is 1, linear interpolation.
Returns:

shifts – The shifts are returned only if shifts is None

Return type:

np.array

Notes

The statistical analysis approach to the translation estimation when using `reference`=’stat’ roughly follows [1]_ . If you use it please cite their article.

References

[1]Schaffer, Bernhard, Werner Grogger, and Gerald

Kothleitner. “Automated Spatial Drift Correction for EFTEM Signal2D Series.” Ultramicroscopy 102, no. 1 (December 2004): 27–36.

create_model(dictionary=None)

Create a model for the current signal :param dictionary: A dictionary to be used to recreate a model. Usually generated using

hyperspy.model.as_dictionary()
Returns:
Return type:A Model class
crop_image(top=None, bottom=None, left=None, right=None)

Crops an image in place.

top, bottom, left, right : int or float

If int the values are taken as indices. If float the values are converted to indices.

crop

estimate_shift2D(reference='current', correlation_threshold=None, chunk_size=30, roi=None, normalize_corr=False, sobel=True, medfilter=True, hanning=True, plot=False, dtype='float', show_progressbar=None)

Estimate the shifts in a image using phase correlation This method can only estimate the shift by comparing bidimensional features that should not change position between frames. To decrease the memory usage, the time of computation and the accuracy of the results it is convenient to select a region of interest by setting the roi keyword. :param reference: If ‘current’ (default) the image at the current

coordinates is taken as reference. If ‘cascade’ each image is aligned with the previous one. If ‘stat’ the translation of every image with all the rest is estimated and by performing statistical analysis on the result the translation is estimated.
Parameters:
  • correlation_threshold ({None, 'auto', float}) – This parameter is only relevant when reference is ‘stat’. If float, the shift estimations with a maximum correlation value lower than the given value are not used to compute the estimated shifts. If ‘auto’ the threshold is calculated automatically as the minimum maximum correlation value of the automatically selected reference image.
  • chunk_size ({None, int}) – If int and `reference`==’stat’ the number of images used as reference are limited to the given value.
  • roi (tuple of ints or floats (left, right, top bottom)) – Define the region of interest. If int(float) the position is given axis index(value).
  • sobel (bool) – apply a sobel filter for edge enhancement
  • medfilter (bool) – apply a median filter for noise reduction
  • hanning (bool) – Apply a 2d hanning filter
  • plot (bool) – If True plots the images after applying the filters and the phase correlation
  • dtype (str or dtype) – Typecode or data-type in which the calculations must be performed.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

Return type:

list of applied shifts

Notes

The statistical analysis approach to the translation estimation when using `reference`=’stat’ roughly follows [1]_ . If you use it please cite their article.

References

[1]Schaffer, Bernhard, Werner Grogger, and Gerald

Kothleitner. “Automated Spatial Drift Correction for EFTEM Signal2D Series.” Ultramicroscopy 102, no. 1 (December 2004): 27–36.

plot(colorbar=True, scalebar=True, scalebar_color='white', axes_ticks=None, saturated_pixels=0, vmin=None, vmax=None, no_nans=False, centre_colormap='auto', **kwargs)

Plot the signal at the current coordinates.

For multidimensional datasets an optional figure, the “navigator”, with a cursor to navigate that data is raised. In any case it is possible to navigate the data using the sliders. Currently only signals with signal_dimension equal to 0, 1 and 2 can be plotted.

Parameters:
  • navigator ({"auto", None, "slider", "spectrum", Signal}) – If “auto”, if navigation_dimension > 0, a navigator is provided to explore the data. If navigation_dimension is 1 and the signal is an image the navigator is a spectrum obtained by integrating over the signal axes (the image). If navigation_dimension is 1 and the signal is a spectrum the navigator is an image obtained by stacking horizontally all the spectra in the dataset. If navigation_dimension is > 1, the navigator is an image obtained by integrating the data over the signal axes. Additionaly, if navigation_dimension > 2 a window with one slider per axis is raised to navigate the data. For example, if the dataset consists of 3 navigation axes X, Y, Z and one signal axis, E, the default navigator will be an image obtained by integrating the data over E at the current Z index and a window with sliders for the X, Y and Z axes will be raised. Notice that changing the Z-axis index changes the navigator in this case. If “slider” and the navigation dimension > 0 a window with one slider per axis is raised to navigate the data. If “spectrum” and navigation_dimension > 0 the navigator is always a spectrum obtained by integrating the data over all other axes. If None, no navigator will be provided. Alternatively a Signal instance can be provided. The signal dimension must be 1 (for a spectrum navigator) or 2 (for a image navigator) and navigation_shape must be 0 (for a static navigator) or navigation_shape + signal_shape must be equal to the navigator_shape of the current object (for a dynamic navigator). If the signal dtype is RGB or RGBA this parameters has no effect and is always “slider”.
  • axes_manager ({None, axes_manager}) – If None axes_manager is used.
  • colorbar (bool, optional) – If true, a colorbar is plotted for non-RGB images.
  • scalebar (bool, optional) – If True and the units and scale of the x and y axes are the same a scale bar is plotted.
  • scalebar_color (str, optional) – A valid MPL color string; will be used as the scalebar color.
  • axes_ticks ({None, bool}, optional) – If True, plot the axes ticks. If None axes_ticks are only plotted when the scale bar is not plotted. If False the axes ticks are never plotted.
  • saturated_pixels (scalar) – The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range.
  • vmax (vmin,) – vmin and vmax are used to normalize luminance data.
  • no_nans (bool, optional) – If True, set nans to zero for plotting.
  • centre_colormap ({"auto", True, False}) – If True the centre of the color scheme is set to zero. This is specially useful when using diverging color schemes. If “auto” (default), diverging color schemes are automatically centred.
  • optional (**kwargs,) – Additional key word arguments passed to matplotlib.imshow()
hyperspy._signals.signal2d.estimate_image_shift(ref, image, roi=None, sobel=True, medfilter=True, hanning=True, plot=False, dtype='float', normalize_corr=False)

Estimate the shift in a image using phase correlation

This method can only estimate the shift by comparing bidimensional features that should not change the position in the given axis. To decrease the memory usage, the time of computation and the accuracy of the results it is convenient to select a region of interest by setting the roi keyword.

Parameters:
  • roi (tuple of ints (top, bottom, left, right)) – Define the region of interest
  • sobel (bool) – apply a sobel filter for edge enhancement
  • medfilter (bool) – apply a median filter for noise reduction
  • hanning (bool) – Apply a 2d hanning filter
  • plot (bool) – If True plots the images after applying the filters and the phase correlation
  • reference ('current' | 'cascade') – If ‘current’ (default) the image at the current coordinates is taken as reference. If ‘cascade’ each image is aligned with the previous one.
  • dtype (str or dtype) – Typecode or data-type in which the calculations must be performed.
  • normalize_corr (bool) – If True use phase correlation instead of standard correlation
Returns:

  • shifts (np.array) – containing the estimate shifts
  • max_value (float) – The maximum value of the correlation

hyperspy._signals.signal2d.fft_correlation(in1, in2, normalize=False)

Correlation of two N-dimensional arrays using FFT.

Adapted from scipy’s fftconvolve.

Parameters:
  • in2 (in1,) –
  • normalize (bool) – If True performs phase correlation
hyperspy._signals.signal2d.hanning2d(M, N)

A 2D hanning window created by outer product.

hyperspy._signals.signal2d.shift_image(im, shift, interpolation_order=1, fill_value=nan)
hyperspy._signals.signal2d.sobel_filter(im)
hyperspy._signals.signal2d.triu_indices_minus_diag(n)

Returns the indices for the upper-triangle of an (n, n) array excluding its diagonal

Parameters:n (int) – The length of the square array

Module contents