HyperSpy API is changing in version 2.0, see the release notes!

Signal1D#

class hyperspy.api.signals.Signal1D(*args, **kwargs)#

Bases: BaseSignal, CommonSignal1D

General 1D signal class.

Create a signal instance.

Parameters:
datanumpy.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).

attributesdict, optional

A dictionary whose items are stored as attributes.

metadatadict, 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_metadatadict, 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.

raggedbool 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.

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=None, mask=None, show_progressbar=None, iterpath='serpentine')#

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.

Parameters:
start, endint, float or None

The limits of the interval. If int they are taken as the axis index. If float they are taken as the axis value.

reference_indicestuple of int or None

Defines the coordinates of the spectrum that will be used as reference. If None the spectrum at the current coordinates is used for this purpose.

max_shiftint

“Saturation limit” for the shift.

interpolatebool

If True, interpolation is used to provide sub-pixel accuracy.

number_of_interpolation_pointsint

Number of interpolation points. Warning: making this number too big can saturate the memory

interpolation_methodstr 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.

cropbool

If True automatically crop the signal axis at both ends if needed.

expandbool

If True, the data will be expanded to fit all data after alignment. Overrides crop argument.

fill_valuefloat

If crop is False fill the data outside of the original interval with the given value where needed.

also_alignlist of BaseSignal, None

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.

maskBaseSignal or bool

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_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

Returns:
numpy.ndarray

The result of the estimation.

Raises:
SignalDimensionError

If the signal dimension is not 1.

See also

estimate_shift1D
calibrate(display=True, toolkit=None)#

Calibrate the spectral dimension using a gui. It displays a window where the new calibration can be set by:

  • setting the values of offset, units and scale directly

  • or selecting a range by dragging the mouse on the spectrum figure and setting the new values for the given range limits

Parameters:
displaybool

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

toolkitstr, iterable of str 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.

Raises:
SignalDimensionError

If the signal dimension is not 1.

NotImplementedError

If called with a non-uniform axes.

Notes

For this method to work the output_dimension must be 1.

create_model(dictionary=None)#

Create a model for the current data.

Returns:
modelModel1D instance.
crop_signal(*args, **kwargs)#

Crop in place in the signal space.

Parameters:
left_value, right_valueint, float or None

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, num_workers=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 subtracted. The estimation is performed by interpolation using cubic splines.

Parameters:
factorfloat, default 0.5

Normalized height (in interval [0, 1]) at which to estimate the width. The default (0.5) estimates the FWHM.

windowNone or 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_intervalbool

If True, returns 2 extra signals with the positions of the desired height fraction at the left and right of the peak.

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

Returns:
float or list of float

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, num_workers=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.

Parameters:
start, endint, float or None, default None

The limits of the interval. If int they are taken as the axis index. If float they are taken as the axis value.

reference_indicestuple of int or None, default None

Defines the coordinates of the spectrum that will be used as reference. If None the spectrum at the current coordinates is used for this purpose.

max_shiftint

“Saturation limit” for the shift.

interpolatebool, default True

If True, interpolation is used to provide sub-pixel accuracy.

number_of_interpolation_pointsint

Number of interpolation points. Warning: making this number too big can saturate the memory

maskBaseSignal of bool.

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_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

Returns:
numpy.ndarray

An array with the result of the estimation in the axis units. Although the computation is performed in batches if the signal is lazy, the result is computed in memory because it depends on the current state of the axes that could change later on in the workflow.

Raises:
SignalDimensionError

If the signal dimension is not 1.

NotImplementedError

If the signal axis is a non-uniform axis.

filter_butterworth(cutoff_frequency_ratio=None, type='low', order=2, display=True, toolkit=None)#

Butterworth filter in place.

Parameters:
displaybool

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

toolkitstr, iterable of str 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.

Raises:
SignalDimensionError

If the signal dimension is not 1.

NotImplementedError

If the signal axis is a non-uniform axis.

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

Find positive peaks along a 1D Signal. It detects peaks by looking for downward zero-crossings in the first derivative that exceed slope_thresh.

slope_thresh and amp_thresh, control sensitivity: higher values will neglect broad peaks (slope) and smaller features (amp), respectively.

Parameters:
slope_threshfloat, default 0

1st derivative threshold to count the peak; higher values will neglect broader features.

amp_threshfloat, optional

Intensity threshold below which peaks are ignored; higher values will neglect smaller features; default is set to 10% of max(y).

medfilt_radiusint, default 5

Median filter window to apply to smooth the data (see scipy.signal.medfilt()); if 0, no filter will be applied.

peakgroupint, default 10

Number of points around the “top part” of the peak that is taken to estimate the peak height. For spikes or very narrow peaks, set peakgroup to 1 or 2; for broad or noisy peaks, make peakgroup larger to reduce the effect of noise.

maxpeaknint, default 5000

Number of maximum detectable peaks.

subchannelbool, default True

Whether to use subchannel precision or not.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

Returns:
numpy.ndarray

Structured array of shape (npeaks) containing fields: ‘position’, ‘width’, and ‘height’ for 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:
FWHMfloat

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.

NotImplementedError

If the signal axis is a non-uniform axis.

hanning_taper(side='both', channels=None, offset=0)#

Apply a hanning taper to the data in place.

Parameters:
side{ 'left' | 'right' | 'both' }

Specify which side to use.

channelsNone or int

The number of channels to taper. If None 5% of the total number of channels are tapered.

offsetint
Returns:
int
Raises:
SignalDimensionError

If the signal dimension is not 1.

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

Replace the data in a given range by interpolation. The operation is performed in place.

Parameters:
start, endint or float

The limits of the interval. If int, they are taken as the axis index. If float, they are taken as the axis value.

deltaint or float

The windows around the (start, end) to use for interpolation. If int, they are taken as index steps. If float, they are taken in units of the axis value.

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

**kwargsdict

All extra keyword arguments are passed to scipy.interpolate.interp1d. See the function documentation for details.

Raises:
SignalDimensionError

If the signal dimension is not 1.

plot(navigator='auto', plot_markers=True, autoscale='v', norm='auto', axes_manager=None, navigator_kwds={}, **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:
navigatorstr, None, or BaseSignal (or subclass).
Allowed string values are ``’auto’``, ``’slider’``, and ``’spectrum’``.
  • 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 sum 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 all the spectra in the dataset horizontally.

    • If navigation_dimension is > 1, the navigator is a sum image obtained by integrating the data over the signal axes.

    • Additionally, 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.

    • For lazy signals, the navigator will be calculated using the compute_navigator() method.

  • If 'slider':

    • If navigation dimension > 0 a window with one slider per axis is raised to navigate the data.

  • If 'spectrum':

    • If navigation_dimension > 0 the navigator is always a spectrum obtained by integrating the data over all other axes.

    • Not supported for lazy signals, the 'auto' option will be used instead.

  • If None, no navigator will be provided.

Alternatively a BaseSignal (or subclass) instance can be provided. The navigation or signal shape must match the navigation shape of the signal to plot or the 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 parameter has no effect and the value is always set to 'slider'.

axes_managerNone or AxesManager

If None, the signal’s axes_manager attribute is used.

plot_markersbool, default True

Plot markers added using s.add_marker(marker, permanent=True). Note, a large number of markers might lead to very slow plotting.

navigator_kwdsdict

Only for image navigator, additional keyword arguments for matplotlib.pyplot.imshow().

normstr, default 'auto'

The function used to normalize the data prior to plotting. Allowable strings are: 'auto', 'linear', 'log'. If 'auto', intensity is plotted on a linear scale except when power_spectrum=True (only for complex signals).

autoscalestr

The string must contain any combination of the 'x' and 'v' characters. If 'x' or 'v' (for values) are in the string, the corresponding horizontal or vertical axis limits are set to their maxima and the axis limits will reset when the data or the navigation indices are changed. Default is 'v'.

remove_background(signal_range='interactive', background_type='Power law', polynomial_order=2, fast=True, zero_fill=False, plot_remainder=True, show_progressbar=None, return_model=False, display=True, toolkit=None)#

Remove the background, either in place using a GUI or returned as a new spectrum using the command line. The fast option is not accurate for most background types - except Gaussian, Offset and Power law - but it is useful to estimate the initial fitting parameters before performing a full fit.

Parameters:
signal_range“interactive”, tuple of int or float, optional

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, a spectrum will be returned.

background_typestr

The type of component which should be used to fit the background. Possible components: Doniach, Gaussian, Lorentzian, Offset, Polynomial, PowerLaw, Exponential, SkewNormal, SplitVoigt, Voigt. If Polynomial is used, the polynomial order can be specified

polynomial_orderint, default 2

Specify the polynomial order if a Polynomial background is used.

fastbool

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 often more accurate.

zero_fillbool

If True, all spectral channels lower than the lower bound of the fitting range will be set to zero (this is the default behavior of Gatan’s DigitalMicrograph). Setting this value to False allows for inspection of the quality of background fit throughout the pre-fitting region.

plot_remainderbool

If True, add a (green) line previewing the remainder signal after background removal. This preview is obtained from a Fast calculation so the result may be different if a NLLS calculation is finally performed.

return_modelbool

If True, the background model is returned. The chi² can be obtained from this model using chisq().

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

displaybool

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

toolkitstr, iterable of str 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.

Returns:
None or (hyperspy.api.signals.BaseSignal, hyperspy.models.model1d.Model1D)

If signal_range is not 'interactive', the signal with background subtracted is returned. If return_model=True, returns the background model, otherwise, the GUI widget dictionary is returned if display=False - see the display parameter documentation.

Raises:
SignalDimensionError

If the signal dimension is not 1.

Examples

Using GUI, replaces spectrum s

>>> s = hs.signals.Signal1D(range(1000))
>>> s.remove_background() 

Using command line, returns a Signal1D:

>>> s.remove_background(
...    signal_range=(400,450), background_type='PowerLaw'
... )
<Signal1D, title: , dimensions: (|1000)>

Using a full model to fit the background:

>>> s.remove_background(signal_range=(400,450), fast=False)
<Signal1D, title: , dimensions: (|1000)>

Returns background subtracted and the model:

>>> s.remove_background(
...    signal_range=(400,450), fast=False, return_model=True
... )
(<Signal1D, title: , dimensions: (|1000)>, <Model1D>)
shift1D(shift_array, interpolation_method='linear', crop=True, expand=False, fill_value=nan, show_progressbar=None, num_workers=None)#

Shift the data in place over the signal axis by the amount specified by an array.

Parameters:
shift_arrayBaseSignal or numpy.ndarray

An array containing the shifting amount. It must have the same axes_manager.navigation_shape axes_manager._navigation_shape_in_array shape.

interpolation_methodstr 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.

cropbool

If True automatically crop the signal axis at both ends if needed.

expandbool

If True, the data will be expanded to fit all data after alignment. Overrides crop.

fill_valuefloat

If crop is False fill the data outside of the original interval with the given value where needed.

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

Raises:
SignalDimensionError

If the signal dimension is not 1.

NotImplementedError

If the signal axis is a non-uniform axis.

smooth_lowess(smoothing_parameter=None, number_of_iterations=None, show_progressbar=None, num_workers=None, display=True, toolkit=None)#

Lowess data smoothing in place. If smoothing_parameter or number_of_iterations are None the method is run in interactive mode.

Parameters:
smoothing_parameter: float or None

Between 0 and 1. The fraction of the data used when estimating each y-value.

number_of_iterations: int or None

The number of residual-based reweightings to perform.

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

displaybool

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

toolkitstr, iterable of str 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.

Raises:
SignalDimensionError

If the signal dimension is not 1.

smooth_savitzky_golay(polynomial_order=None, window_length=None, differential_order=0, num_workers=None, display=True, toolkit=None)#

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.

Parameters:
polynomial_orderint, optional

The order of the polynomial used to fit the samples. polyorder must be less than window_length.

window_lengthint, optional

The length of the filter window (i.e. the number of coefficients). window_length must be a positive odd integer.

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.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

displaybool

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

toolkitstr, iterable of str 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.

Raises:
NotImplementedError

If the signal axis is a non-uniform axis.

Notes

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

smooth_tv(smoothing_parameter=None, show_progressbar=None, num_workers=None, display=True, toolkit=None)#

Total variation data smoothing in place.

Parameters:
smoothing_parameter: float or None

Denoising weight relative to L2 minimization. If None the method is run in interactive mode.

show_progressbarNone or bool

If True, display a progress bar. If None, the default from the preferences settings is used.

num_workersNone or int

Number of worker used by dask. If None, default to dask default value.

displaybool

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

toolkitstr, iterable of str 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.

Raises:
SignalDimensionError

If the signal dimension is not 1.

NotImplementedError

If the signal axis is a non-uniform axis.

spikes_diagnosis(signal_mask=None, navigation_mask=None, **kwargs)#

Plots a histogram to help in choosing the threshold for spikes removal.

Parameters:
signal_masknumpy.ndarray of bool

Restricts the operation to the signal locations not marked as True (masked).

navigation_masknumpy.ndarray of bool

Restricts the operation to the navigation locations not marked as True (masked).

**kwargsdict

Keyword arguments pass to get_histogram()

spikes_removal_tool(signal_mask=None, navigation_mask=None, threshold='auto', interactive=True, display=True, toolkit=None, **kwargs)#

Graphical interface to remove spikes from EELS spectra or luminescence data. If non-interactive, it removes all spikes.

Parameters:
signal_masknumpy.ndarray of bool

Restricts the operation to the signal locations not marked as True (masked).

navigation_masknumpy.ndarray of bool

Restricts the operation to the navigation locations not marked as True (masked).

threshold'auto' or int

if int set the threshold value use for the detecting the spikes. If "auto", determine the threshold value as being the first zero value in the histogram obtained from the spikes_diagnosis() method.

interactivebool

If True, remove the spikes using the graphical user interface. If False, remove all the spikes automatically, which can introduce artefacts if used with signal containing peak-like features. However, this can be mitigated by using the signal_mask argument to mask the signal of interest.

displaybool

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

toolkitstr, iterable of str 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.

**kwargsdict

Keyword arguments pass to SpikesRemoval.