Signal1D
#
- class hyperspy.api.signals.Signal1D(*args, **kwargs)#
Bases:
BaseSignal
,CommonSignal1D
General 1D signal class.
Create a signal instance.
- Parameters:
- data
numpy.ndarray
The signal data. It can be an array of any dimensions.
- axes[dict/axes], optional
List of either dictionaries or axes objects to define the axes (see the documentation of the
AxesManager
class for more details).- attributes
dict
, optional A dictionary whose items are stored as attributes.
- metadata
dict
, optional A dictionary containing a set of parameters that will to stores in the
metadata
attribute. Some parameters might be mandatory in some cases.- original_metadata
dict
, optional A dictionary containing a set of parameters that will to stores in the
original_metadata
attribute. It typically contains all the parameters that has been imported from the original data file.- raggedbool or
None
, optional Define whether the signal is ragged or not. Overwrite the
ragged
value in theattributes
dictionary. If None, it does nothing. Default is None.
- data
- 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
andend
keywords. By default interpolation is used to obtain subpixel precision.- Parameters:
- start, end
int
,float
orNone
The limits of the interval. If int they are taken as the axis index. If float they are taken as the axis value.
- reference_indices
tuple
ofint
orNone
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_shift
int
“Saturation limit” for the shift.
- interpolatebool
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
orint
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_value
float
If crop is False fill the data outside of the original interval with the given value where needed.
- also_align
list
ofBaseSignal
,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.
- mask
BaseSignal
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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.
- start, end
- Returns:
numpy.ndarray
The result of the estimation.
- Raises:
SignalDimensionError
If the signal dimension is not 1.
See also
- 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.
- toolkit
str
, iterable ofstr
orNone
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_value
int
,float
orNone
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.
- left_value, right_value
- 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:
- factor
float
, default 0.5 Normalized height (in interval [0, 1]) at which to estimate the width. The default (0.5) estimates the FWHM.
- window
None
orfloat
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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
Number of worker used by dask. If None, default to dask default value.
- factor
- Returns:
- 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
andend
. By default interpolation is used to obtain subpixel precision.- Parameters:
- start, end
int
,float
orNone
, defaultNone
The limits of the interval. If int they are taken as the axis index. If float they are taken as the axis value.
- reference_indices
tuple
ofint
orNone
, defaultNone
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_shift
int
“Saturation limit” for the shift.
- interpolatebool, default
True
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. 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. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
Number of worker used by dask. If None, default to dask default value.
- start, end
- 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.
- toolkit
str
, iterable ofstr
orNone
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
andamp_thresh
, control sensitivity: higher values will neglect broad peaks (slope) and smaller features (amp), respectively.- Parameters:
- slope_thresh
float
, default 0 1st derivative threshold to count the peak; higher values will neglect broader features.
- amp_thresh
float
, optional Intensity threshold below which peaks are ignored; higher values will neglect smaller features; default is set to 10% of max(y).
- medfilt_radius
int
, default 5 Median filter window to apply to smooth the data (see
scipy.signal.medfilt()
); if 0, no filter will be applied.- peakgroup
int
, 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.- maxpeakn
int
, default 5000 Number of maximum detectable peaks.
- subchannelbool, default
True
Whether to use subchannel precision or not.
- num_workers
None
orint
Number of worker used by dask. If None, default to dask default value.
- slope_thresh
- 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:
- FWHM
float
The Full Width at Half Maximum of the gaussian in the spectral axis units
- FWHM
- 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.
- 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, end
int
orfloat
The limits of the interval. If int, they are taken as the axis index. If float, they are taken as the axis value.
- delta
int
orfloat
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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
Number of worker used by dask. If None, default to dask default value.
- **kwargs
dict
All extra keyword arguments are passed to
scipy.interpolate.interp1d
. See the function documentation for details.
- start, end
- 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:
- navigator
str
,None
, orBaseSignal
(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 thenavigation_shape
+signal_shape
must be equal to thenavigator_shape
of the current object (for a dynamic navigator). If the signaldtype
is RGB or RGBA this parameter has no effect and the value is always set to'slider'
.- axes_manager
None
orAxesManager
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_kwds
dict
Only for image navigator, additional keyword arguments for
matplotlib.pyplot.imshow()
.- norm
str
, 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 whenpower_spectrum=True
(only for complex signals).- autoscale
str
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'
.
- navigator
- 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
ofint
orfloat
, 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_type
str
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_order
int
, 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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, 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.
- toolkit
str
, iterable ofstr
orNone
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.
- signal_range“interactive”,
- Returns:
None
or (hyperspy.api.signals.BaseSignal
,hyperspy.models.model1d.Model1D
)If
signal_range
is not'interactive'
, the signal with background subtracted is returned. Ifreturn_model=True
, returns the background model, otherwise, the GUI widget dictionary is returned ifdisplay=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_array
BaseSignal
ornumpy.ndarray
An array containing the shifting amount. It must have the same
axes_manager.navigation_shape
axes_manager._navigation_shape_in_array
shape.- interpolation_method
str
orint
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_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. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
Number of worker used by dask. If None, default to dask default value.
- shift_array
- 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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
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.
- toolkit
str
, iterable ofstr
orNone
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_order
int
, optional The order of the polynomial used to fit the samples. polyorder must be less than window_length.
- window_length
int
, 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_workers
None
orint
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.
- toolkit
str
, iterable ofstr
orNone
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.
- polynomial_order
- 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_progressbar
None
or bool If
True
, display a progress bar. IfNone
, the default from the preferences settings is used.- num_workers
None
orint
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.
- toolkit
str
, iterable ofstr
orNone
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_mask
numpy.ndarray
of bool Restricts the operation to the signal locations not marked as True (masked).
- navigation_mask
numpy.ndarray
of bool Restricts the operation to the navigation locations not marked as True (masked).
- **kwargs
dict
Keyword arguments pass to
get_histogram()
- signal_mask
See also
- 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_mask
numpy.ndarray
of bool Restricts the operation to the signal locations not marked as True (masked).
- navigation_mask
numpy.ndarray
of bool Restricts the operation to the navigation locations not marked as True (masked).
- threshold
'auto'
orint
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 thespikes_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.
- toolkit
str
, iterable ofstr
orNone
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.
- **kwargs
dict
Keyword arguments pass to
SpikesRemoval
.
- signal_mask
See also