hyperspy.signal module

hyperspy.signal.ARITHMETIC_OPERATORS = ('__add__', '__sub__', '__mul__', '__floordiv__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__', '__and__', '__xor__', '__or__', '__mod__', '__truediv__')
class hyperspy.signal.BaseSetMetadataItems(signal)

Bases: traits.has_traits.HasTraits

store(*args, **kwargs)
class hyperspy.signal.BaseSignal(data, **kwds)

Bases: hyperspy.misc.slicing.FancySlicing, hyperspy.learn.mva.MVA, hyperspy.signal.MVATools

property T

The transpose of the signal, with signal and navigation spaces swapped.

add_gaussian_noise(std)

Add Gaussian noise to the data.

The operation is performed in-place i.e. the data of the signal is modified.

This method requires a float data type, otherwise numpy raises a TypeError.

Parameters
  • std (float) – The standard deviation of the gaussian noise.

  • Note

  • -----

  • method uses numpy.random.normal (dask.array.random.normal (This) –

  • lazy signals) to generate the Gaussian noise. In order to seed it (for) –

  • must use numpy.random.seed (dask.random.seed) (you) –

add_marker(marker, plot_on_signal=True, plot_marker=True, permanent=False, plot_signal=True, render_figure=True)

Add one or several markers to the signal or navigator plot.

Plot the signal, if not yet plotted

Parameters
  • marker (marker object or iterable of marker objects) – The marker or iterable (list, tuple, …) of markers to add. See plot.markers. If you want to add a large number of markers, add them as an iterable, since this will be much faster. For signals with navigation dimensions, the markers can be made to change for different navigation indices. See the examples for info.

  • plot_on_signal (bool, default True) – If True, add the marker to the signal If False, add the marker to the navigator

  • plot_marker (bool, default True) – If True, plot the marker.

  • permanent (bool, default False) – If False, the marker will only appear in the current plot. If True, the marker will be added to the metadata.Markers list, and be plotted with plot(plot_markers=True). If the signal is saved as a HyperSpy HDF5 file, the markers will be stored in the HDF5 signal and be restored when the file is loaded.

Examples

>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> m = hs.markers.rectangle(x1=150, y1=100, x2=400,
>>>                                  y2=400, color='red')
>>> im.add_marker(m)

Adding to a 1D signal, where the point will change when the navigation index is changed.

>>> s = hs.signals.Signal1D(np.random.random((3, 100)))
>>> marker = hs.markers.point((19, 10, 60), (0.2, 0.5, 0.9))
>>> s.add_marker(marker, permanent=True, plot_marker=True)

Add permanent marker

>>> s = hs.signals.Signal2D(np.random.random((100, 100)))
>>> marker = hs.markers.point(50, 60, color='red')
>>> s.add_marker(marker, permanent=True, plot_marker=True)

Add permanent marker to signal with 2 navigation dimensions. The signal has navigation dimensions (3, 2), as the dimensions gets flipped compared to the output from np.random.random. To add a vertical line marker which changes for different navigation indices, the list used to make the marker must be a nested list: 2 lists with 3 elements each (2 x 3).

>>> s = hs.signals.Signal1D(np.random.random((2, 3, 10)))
>>> marker = hs.markers.vertical_line([[1, 3, 5], [2, 4, 6]])
>>> s.add_marker(marker, permanent=True)

Add permanent marker which changes with navigation position, and do not add it to a current plot

>>> s = hs.signals.Signal2D(np.random.randint(10, size=(3, 100, 100)))
>>> marker = hs.markers.point((10, 30, 50), (30, 50, 60), color='red')
>>> s.add_marker(marker, permanent=True, plot_marker=False)
>>> s.plot(plot_markers=True) #doctest: +SKIP

Removing a permanent marker

>>> s = hs.signals.Signal2D(np.random.randint(10, size=(100, 100)))
>>> marker = hs.markers.point(10, 60, color='red')
>>> marker.name = "point_marker"
>>> s.add_marker(marker, permanent=True)
>>> del s.metadata.Markers.point_marker

Adding many markers as a list

>>> from numpy.random import random
>>> s = hs.signals.Signal2D(np.random.randint(10, size=(100, 100)))
>>> marker_list = []
>>> for i in range(100):
>>>     marker = hs.markers.point(random()*100, random()*100, color='red')
>>>     marker_list.append(marker)
>>> s.add_marker(marker_list, permanent=True)
add_poissonian_noise(keep_dtype=True)

Add Poissonian noise to the data

This method works in-place. The resulting data type is int64. If this is different from the original data type a warning is added to the log.

Parameters
  • keep_dtype (bool) – If True, keep the original data type of the signal data. For example, if the data type was initially “float64”, the result of the operation (usually “int64”) will be converted to “float64”. The default is True for convienece.

  • Note

  • -----

  • method uses numpy.random.poisson (dask.array.random.poisson (This) –

  • lazy signals) to generate the Gaussian noise. In order to seed it (for) –

  • must use numpy.random.seed (dask.random.seed) (you) –

as_lazy(copy_variance=True)
as_signal1D(spectral_axis, out=None, optimize=True)

Return the Signal as a spectrum.

The chosen spectral axis is moved to the last index in the array and the data is made contiguous for efficient iteration over spectra. By default ensures the data is stored optimally, hence often making a copy of the data. See transpose for a more general method with more options.

Parameters
  • spectral_axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • optimize (bool) – If True, the location of the data in memory is optimised for the fastest iteration over the navigation axes. This operation can cause a peak of memory usage and requires considerable processing times for large datasets and/or low specification hardware. See the transposing section of the HyperSpy user guide for more information. When operating on lazy signals, if True the chunks are optimised for the new axes configuration.

See also

as_signal2D(), transpose(), hs.transpose()

Examples

>>> img = hs.signals.Signal2D(np.ones((3,4,5,6)))
>>> img
<Signal2D, title: , dimensions: (4, 3, 6, 5)>
>>> img.to_spectrum(-1+1j)
<Signal1D, title: , dimensions: (6, 5, 4, 3)>
>>> img.to_spectrum(0)
<Signal1D, title: , dimensions: (6, 5, 3, 4)>
as_signal2D(image_axes, out=None, optimize=True)

Convert signal to image.

The chosen image axes are moved to the last indices in the array and the data is made contiguous for efficient iteration over images.

Parameters
  • image_axes (tuple of {int | str | axis}) – Select the image axes. Note that the order of the axes matters and it is given in the “natural” i.e. X, Y, Z… order.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • optimize (bool) – If True, the location of the data in memory is optimised for the fastest iteration over the navigation axes. This operation can cause a peak of memory usage and requires considerable processing times for large datasets and/or low specification hardware. See the transposing section of the HyperSpy user guide for more information. When operating on lazy signals, if True the chunks are optimised for the new axes configuration.

:raises DataDimensionError : when data.ndim < 2:

See also

as_signal1D(), transpose(), hs.transpose()

Examples

>>> s = hs.signals.Signal1D(np.ones((2,3,4,5)))
>>> s
<Signal1D, title: , dimensions: (4, 3, 2, 5)>
>>> s.as_signal2D((0,1))
<Signal2D, title: , dimensions: (5, 2, 4, 3)>
>>> s.to_signal2D((1,2))
<Signal2D, title: , dimensions: (4, 5, 3, 2)>
change_dtype(dtype, rechunk=True)

Change the data type.

Parameters
  • dtype (str or dtype) – Typecode or data-type to which the array is cast. In addition to all standard numpy dtypes HyperSpy supports four extra dtypes for RGB images: “rgb8”, “rgba8”, “rgb16” and “rgba16”. Changing from and to any rgbx dtype is more constrained than most other dtype conversions. To change to a rgbx dtype the signal dimension must be 1, its size 3(4) for rgb(rgba) dtypes, the dtype uint8(uint16) for rgbx8(rgbx16) and the navigation dimension at least 2. After conversion the signal dimension becomes 2. The dtype of images of dtype rgbx8(rgbx16) can only be changed to uint8(uint16) and the signal dimension becomes 1.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Examples

>>> s = hs.signals.Signal1D([1,2,3,4,5])
>>> s.data
array([1, 2, 3, 4, 5])
>>> s.change_dtype('float')
>>> s.data
array([ 1.,  2.,  3.,  4.,  5.])
copy()
crop(axis, start=None, end=None, convert_units=False)

Crops the data in a given axis. The range is given in pixels.

Parameters
  • axis ({int | string}) – Specify the data axis in which to perform the cropping operation. The axis can be specified using the index of the axis in axes_manager or the axis name.

  • end (start,) – The beginning and end of the cropping interval. If int the value is taken as the axis index. If float the index is calculated using the axis calibration. If start/end is None crop from/to the low/high end of the axis.

  • convert_units (bool) – Default is False If True, convert the units using the convert_to_units method of the axes_manager. If False, does nothing.

property data
deepcopy()
derivative(axis, order=1, out=None, rechunk=True)

Numerical derivative along the given axis.

Currently only the first order finite difference method is implemented.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • order (int) – The order of the derivative. (Note that this is the order of the derivative i.e. order=2 does not use second order finite differences method.)

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

der – Note that the size of the data on the given axis decreases by the given order i.e. if axis is “x” and order is 2 the x dimension is N, der’s x dimension is N - 2.

Return type

Signal

See also

diff()

diff(axis, order=1, out=None, rechunk=True)

Returns a signal with the n-th order discrete difference along given axis.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • order (int) – the order of the derivative

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.diff(-1).data.shape
(64,64,1023)
estimate_poissonian_noise_variance(expected_value=None, gain_factor=None, gain_offset=None, correlation_factor=None)

Estimate the poissonian noise variance of the signal.

The variance is stored in the metadata.Signal.Noise_properties.variance attribute.

A poissonian noise variance is equal to the expected value. With the default arguments, this method simply sets the variance attribute to the given expected_value. However, more generally (although then noise is not strictly poissonian), the variance may be proportional to the expected value. Moreover, when the noise is a mixture of white (gaussian) and poissonian noise, the variance is described by the following linear model:

\mathrm{Var}[X] = (a * \mathrm{E}[X] + b) * c

Where a is the gain_factor, b is the gain_offset (the gaussian noise variance) and c the correlation_factor. The correlation factor accounts for correlation of adjacent signal elements that can be modeled as a convolution with a gaussian point spread function.

Parameters
  • expected_value (None or Signal instance.) – If None, the signal data is taken as the expected value. Note that this may be inaccurate where data is small.

  • gain_offset, correlation_factor (gain_factor,) – All three must be positive. If None, take the values from metadata.Signal.Noise_properties.Variance_linear_model if defined. Otherwise suppose poissonian noise i.e. gain_factor=1, gain_offset=0, correlation_factor=1. If not None, the values are stored in metadata.Signal.Noise_properties.Variance_linear_model.

fft(shift=False, **kwargs)

Compute the discrete Fourier Transform.

This function computes the discrete Fourier Transform over the signal axes by means of the Fast Fourier Transform (FFT) as implemented in numpy.

Parameters
  • shift (bool, optional) – If True, the origin of FFT will be shifted to the centre (Default: False).

  • **kwargs – other keyword arguments are described in np.fft.fftn().

Returns

s

Return type

ComplexSignal

Examples

>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> im.fft()
<ComplexSignal2D, title: FFT of , dimensions: (|512, 512)>
# Use following to plot power spectrum of `im`:
>>> im.fft().plot()

Notes

For further information see the documentation of numpy.fft.fftn

fold()

If the signal was previously unfolded, folds it back

get_current_signal(auto_title=True, auto_filename=True)

Returns the data at the current coordinates as a Signal subclass.

The signal subclass is the same as that of the current object. All the axes navigation attribute are set to False.

Parameters
  • auto_title (bool) – If True an space followed by the current indices in parenthesis are appended to the title.

  • auto_filename (bool) – If True and tmp_parameters.filename is defined (what is always the case when the Signal has been read from a file), the filename is modified by appending an underscore and a parenthesis containing the current indices.

Returns

cs

Return type

Signal subclass instance.

Examples

>>> im = hs.signals.Signal2D(np.zeros((2,3, 32,32)))
>>> im
<Signal2D, title: , dimensions: (3, 2, 32, 32)>
>>> im.axes_manager.indices = 2,1
>>> im.get_current_signal()
<Signal2D, title:  (2, 1), dimensions: (32, 32)>
get_dimensions_from_data()

Get the dimension parameters from the data_cube. Useful when the data_cube was externally modified, or when the SI was not loaded from a file

get_histogram(bins='freedman', range_bins=None, out=None, **kwargs)

Return a histogram of the signal data.

More sophisticated algorithms for determining bins can be used. Aside from the bins argument allowing a string specified how bins are computed, the parameters are the same as numpy.histogram().

Parameters
  • bins (int or list or str, optional) – If bins is a string, then it must be one of: ‘knuth’ : use Knuth’s rule to determine bins ‘scotts’ : use Scott’s rule to determine bins ‘freedman’ : use the Freedman-diaconis rule to determine bins ‘blocks’ : use bayesian blocks for dynamic bin widths

  • range_bins (tuple or None, optional) – the minimum and maximum range for the histogram. If not specified, it will be (x.min(), x.max())

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

  • **kwargs – other keyword arguments (weight and density) are described in np.histogram().

Returns

hist_spec

Return type

An 1D spectrum instance containing the histogram.

See also

print_summary_statistics(), astroML.density_estimation.histogram(), numpy.histogram()

Notes

The lazy version of the algorithm does not support ‘knuth’ and ‘blocks’ bins arguments. The number of bins estimators are taken from AstroML. Read their documentation for more info.

Examples

>>> s = hs.signals.Signal1D(np.random.normal(size=(10, 100)))
Plot the data histogram
>>> s.get_histogram().plot()
Plot the histogram of the signal at the current coordinates
>>> s.get_current_signal().get_histogram().plot()
ifft(shift=None, **kwargs)

Compute the inverse discrete Fourier Transform.

This function computes real part of the inverse of the discrete Fourier Transform over the signal axes by means of the Fast Fourier Transform (FFT) as implemented in numpy.

Parameters
  • shift (bool or None, optional) – If None the shift option will be set to the original status of the FFT using value in metadata. If no FFT entry is present in metadata, the parameter will be set to False. If True, the origin of FFT will be shifted to the centre, otherwise the origin would be kept at (0, 0)(Default: None).

  • **kwargs – other keyword arguments are described in np.fft.ifftn().

Returns

s

Return type

Signal

Examples

>>> import scipy
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> imfft = im.fft()
>>> imfft.ifft()
<Signal2D, title: real(iFFT of FFT of ), dimensions: (|512, 512)>

Notes

For further information see the documentation of numpy.fft.ifftn

indexmax(axis, out=None, rechunk=True)

Returns a signal with the index of the maximum along an axis.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s – The data dtype is always int.

Return type

Signal

See also

max, min, sum, mean, std, var, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.indexmax(-1).data.shape
(64,64)
indexmin(axis, out=None, rechunk=True)

Returns a signal with the index of the minimum along an axis.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s – The data dtype is always int.

Return type

Signal

See also

max, min, sum, mean, std, var, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.indexmin(-1).data.shape
(64,64)
integrate1D(axis, out=None)

Integrate the signal over the given axis.

The integration is performed using Simpson’s rule if metadata.Signal.binned is False and summation over the given axis if True.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

Returns

s

Return type

Signal

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.integrate1D(-1).data.shape
(64,64)
integrate_simpson(axis, out=None)

Returns a signal with the result of calculating the integral of the signal along an axis using Simpson’s rule.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

Returns

s

Return type

Signal

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.integrate_simpson(-1).data.shape
(64,64)
property is_rgb
property is_rgba
property is_rgbx
map(function, show_progressbar=None, parallel=None, inplace=True, ragged=None, **kwargs)

Apply a function to the signal data at all the coordinates.

The function must operate on numpy arrays. It is applied to the data at each navigation coordinate pixel-py-pixel. Any extra keyword argument is passed to the function. The keywords can take different values at different coordinates. If the function takes an axis or axes argument, the function is assumed to be vectorial and the signal axes are assigned to axis or axes. Otherwise, the signal is iterated over the navigation axes and a progress bar is displayed to monitor the progress.

In general, only navigation axes (order, calibration and number) is guaranteed to be preserved.

Parameters
  • function (function) – A function that can be applied to the signal.

  • show_progressbar (None or bool) – If True, display a progress bar. If None the default from the preferences settings is used.

  • parallel (None or bool) – If True, perform computation in parallel using multiple cores. If None the default from the preferences settings is used.

  • inplace (bool) – if True (default), the data is replaced by the result. Otherwise a new signal with the results is returned.

  • ragged ({None, bool}) – Indicates if results for each navigation pixel are of identical shape (and/or numpy arrays to begin with). If None, appropriate choice is made while processing. None is not allowed for Lazy signals!

  • arguments (keyword) – All extra keyword arguments are passed to the

Notes

If the function results do not have identical shapes, the result is an array of navigation shape, where each element corresponds to the result of the function (of arbitrary object type), called “ragged array”. As such, most functions are not able to operate on the result and the data should be used directly.

This method is similar to Python’s map() that can also be utilize with a Signal instance for similar purposes. However, this method has the advantage of being faster because it iterates the numpy array instead of the Signal.

Examples

Apply a Gaussian filter to all the images in the dataset. The sigma parameter is constant.

>>> import scipy.ndimage
>>> im = hs.signals.Signal2D(np.random.random((10, 64, 64)))
>>> im.map(scipy.ndimage.gaussian_filter, sigma=2.5)

Apply a Gaussian filter to all the images in the dataset. The signal parameter is variable.

>>> im = hs.signals.Signal2D(np.random.random((10, 64, 64)))
>>> sigmas = hs.signals.BaseSignal(np.linspace(2,5,10)).T
>>> im.map(scipy.ndimage.gaussian_filter, sigma=sigmas)
max(axis=None, out=None, rechunk=True)

Returns a signal with the maximum of the signal along at least one axis.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

min(), sum(), mean(), std(), var(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.max(-1).data.shape
(64,64)
mean(axis=None, out=None, rechunk=True)

Returns a signal with the average of the signal along at least one axis.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), min(), sum(), std(), var(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.mean(-1).data.shape
(64,64)
min(axis=None, out=None, rechunk=True)

Returns a signal with the minimum of the signal along at least one axis.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), sum(), mean(), std(), var(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.min(-1).data.shape
(64,64)
nanmax(axis=None, out=None, rechunk=True)

Identical to max except ignores missing (NaN) values. The full documentation follows:

——————– max ——————–

Returns a signal with the maximum of the signal along at least one axis.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

min, sum, mean, std, var, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.max(-1).data.shape
(64,64)
nanmean(axis=None, out=None, rechunk=True)

Identical to mean except ignores missing (NaN) values. The full documentation follows:

——————– mean ——————–

Returns a signal with the average of the signal along at least one axis.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

max, min, sum, std, var, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.mean(-1).data.shape
(64,64)
nanmin(axis=None, out=None, rechunk=True)

Identical to min except ignores missing (NaN) values. The full documentation follows:

——————– min ——————–

Returns a signal with the minimum of the signal along at least one axis.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

max, sum, mean, std, var, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.min(-1).data.shape
(64,64)
nanstd(axis=None, out=None, rechunk=True)

Identical to std except ignores missing (NaN) values. The full documentation follows:

——————– std ——————–

Returns a signal with the standard deviation of the signal along at least one axis.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

max, min, sum, mean, var, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.std(-1).data.shape
(64,64)
nansum(axis=None, out=None, rechunk=True)

Identical to sum except ignores missing (NaN) values. The full documentation follows:

——————– sum ——————–

Sum the data over the given axes.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

max, min, mean, std, var, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.sum(-1).data.shape
(64,64)
nanvar(axis=None, out=None, rechunk=True)

Identical to var except ignores missing (NaN) values. The full documentation follows:

——————– var ——————–

Returns a signal with the variances of the signal along at least one axis.

axisint, str, axis, tuple of axis or None

Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

outSignal or None

If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

rechunk: bool

Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

s : Signal

max, min, sum, mean, std, indexmax, valuemax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.var(-1).data.shape
(64,64)
plot(navigator='auto', axes_manager=None, plot_markers=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.

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

  • norm ({‘auto’, ‘linear’, ‘log’, mpl Normalize instance or subclass},) – default is ‘auto’. Plot the intensity scale on a linear or logarithmic scale. If ‘auto’, plot the intensity on a linear scale except when power_spectrum is True, which can be used only for compatible signal. For Signal2D, a matplotlib Normalize subclass or instance can be provided.

  • optional (**kwargs,) – Only for 2D signals: additional key word arguments for matplotlib.pyplot.imshow.

print_summary_statistics(formatter='%.3g', rechunk=True)

Prints the five-number summary statistics of the data, the mean and the standard deviation.

Prints the mean, standard deviation (std), maximum (max), minimum (min), first quartile (Q1), median and third quartile. nans are removed from the calculations.

Parameters
  • formatter (bool) – Number formatter.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

See also

get_histogram()

rebin(new_shape=None, scale=None, crop=True, out=None)

Rebin array.

Rebin the signal into a smaller or larger shape, based on linear interpolation. Specify either new_shape or scale.

Parameters
  • new_shape (a list of floats or integer, default None) – For each dimension specify the new_shape. This will then be converted into a scale.

  • scale (a list of floats or integer, default None) – For each dimension specify the new:old pixel ratio, e.g. a ratio of 1 is no binning and a ratio of 2 means that each pixel in the new spectrum is twice the size of the pixels in the old spectrum. The length of the list should match the dimension of the numpy array. *Note : Only one of scale or new_shape should be specified otherwise the function will not run*

  • crop (bool, default True) –

    When binning by a non-integer number of pixels it is likely that the final row in each dimension contains less than the full quota to fill one pixel.

    e.g. 5*5 array binned by 2.1 will produce two rows containing 2.1 pixels and one row containing only 0.8 pixels worth. Selection of crop=’True’ or crop=’False’ determines whether or not this ‘black’ line is cropped from the final binned array or not.

    Please note that if crop=False is used, the final row in each dimension may appear black, if a fractional number of pixels are left over. It can be removed but has been left to preserve total counts before and after binning.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

Returns

s

Return type

Signal subclass

Examples

>>> spectrum = hs.signals.EDSTEMSpectrum(np.ones([4, 4, 10]))
>>> spectrum.data[1, 2, 9] = 5
>>> print(spectrum)
<EDXTEMSpectrum, title: dimensions: (4, 4|10)>
>>> print ('Sum = ', sum(sum(sum(spectrum.data))))
Sum = 164.0
>>> scale = [2, 2, 5]
>>> test = spectrum.rebin(scale)
>>> print(test)
<EDSTEMSpectrum, title: dimensions (2, 2|2)>
>>> print('Sum = ', sum(sum(sum(test.data))))
Sum =  164.0
rollaxis(axis, to_axis, optimize=False)

Roll the specified axis backwards, until it lies in a given position.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name. The axis to roll backwards. The positions of the other axes do not change relative to one another.

  • to_axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name. The axis is rolled until it lies before this other axis.

  • optimize (bool) – If True, the location of the data in memory is optimised for the fastest iteration over the navigation axes. This operation can cause a peak of memory usage and requires considerable processing times for large datasets and/or low specification hardware. See the transposing section of the HyperSpy user guide for more information. When operating on lazy signals, if True the chunks are optimised for the new axes configuration.

Returns

s – Output signal.

Return type

Signal or subclass

See also

roll()

swap_axes

Examples

>>> s = hs.signals.Signal1D(np.ones((5,4,3,6)))
>>> s
<Signal1D, title: , dimensions: (3, 4, 5, 6)>
>>> s.rollaxis(3, 1)
<Signal1D, title: , dimensions: (3, 4, 5, 6)>
>>> s.rollaxis(2,0)
<Signal1D, title: , dimensions: (5, 3, 4, 6)>
save(filename=None, overwrite=None, extension=None, **kwds)

Saves the signal in the specified format.

The function gets the format from the extension.:
  • hspy for HyperSpy’s HDF5 specification

  • rpl for Ripple (useful to export to Digital Micrograph)

  • msa for EMSA/MSA single spectrum saving.

  • unf for SEMPER unf binary format.

  • blo for Blockfile diffraction stack saving.

  • Many image formats such as png, tiff, jpeg…

If no extension is provided the default file format as defined in the preferences is used. Please note that not all the formats supports saving datasets of arbitrary dimensions, e.g. msa only supports 1D data, and blockfiles only support image stacks with a navigation dimension < 2.

Each format accepts a different set of parameters. For details see the specific format documentation.

Parameters
  • filename (str or None) – If None (default) and tmp_parameters.filename and tmp_paramters.folder are defined, the filename and path will be taken from there. A valid extension can be provided e.g. “my_file.rpl”, see extension.

  • overwrite (None, bool) – If None, if the file exists it will query the user. If True(False) it (does not) overwrites the file if it exists.

  • extension ({None, 'hspy', 'hdf5', 'rpl', 'msa', 'unf', 'blo',) – ‘emd’, common image extensions e.g. ‘tiff’, ‘png’} The extension of the file that defines the file format. ‘hspy’ and ‘hdf5’ are equivalent. Use ‘hdf5’ if compatibility with HyperSpy versions older than 1.2 is required. If None, the extension is determined from the following list in this order: i) the filename ii) Signal.tmp_parameters.extension iii) hspy (the default extension)

set_signal_origin(origin)

Set the signal_origin metadata value.

The signal_origin attribute specifies if the data was obtained through experiment or simulation.

Parameters

origin (string) – Typically ‘experiment’ or ‘simulation’.

set_signal_type(signal_type)

Set the signal type and change the current class accordingly if pertinent.

The signal_type attribute specifies the kind of data that the signal contains e.g. “EELS” for electron energy-loss spectroscopy, “PES” for photoemission spectroscopy. There are some methods that are only available for certain kind of signals, so setting this parameter can enable/disable features.

Parameters

signal_type ({"EELS", "EDS_TEM", "EDS_SEM", "DielectricFunction"}) – Currently there are special features for “EELS” (electron energy-loss spectroscopy), “EDS_TEM” (energy dispersive X-rays of thin samples, normally obtained in a transmission electron microscope), “EDS_SEM” (energy dispersive X-rays of thick samples, normally obtained in a scanning electron microscope) and “DielectricFuction”. Setting the signal_type to the correct acronym is highly advisable when analyzing any signal for which HyperSpy provides extra features. Even if HyperSpy does not provide extra features for the signal that you are analyzing, it is good practice to set signal_type to a value that best describes the data signal type.

split(axis='auto', number_of_parts='auto', step_sizes='auto')

Splits the data into several signals.

The split can be defined by giving the number_of_parts, a homogeneous step size or a list of customized step sizes. By default (‘auto’), the function is the reverse of utils.stack().

Parameters
  • axis ({'auto' | int | string}) –

    Specify the data axis in which to perform the splitting operation. The axis can be specified using the index of the axis in axes_manager or the axis name. - If ‘auto’ and if the object has been created with utils.stack, split will return the former list of signals (options stored in ‘metadata._HyperSpy.Stacking_history’

    else the last navigation axis will be used.

  • number_of_parts ({'auto' | int}) – Number of parts in which the SI will be split. The splitting is homogeneous. When the axis size is not divisible by the number_of_parts the reminder data is lost without warning. If number_of_parts and step_sizes is ‘auto’, number_of_parts equals the length of the axis, step_sizes equals one and the axis is suppressed from each sub_spectra.

  • step_sizes ({'auto' | list of ints | int}) – Size of the split parts. If ‘auto’, the step_sizes equals one. If int, the splitting is homogeneous.

Examples

>>> s = hs.signals.Signal1D(random.random([4,3,2]))
>>> s
    <Signal1D, title: , dimensions: (3, 4|2)>
>>> s.split()
    [<Signal1D, title: , dimensions: (3 |2)>,
    <Signal1D, title: , dimensions: (3 |2)>,
    <Signal1D, title: , dimensions: (3 |2)>,
    <Signal1D, title: , dimensions: (3 |2)>]
>>> s.split(step_sizes=2)
    [<Signal1D, title: , dimensions: (3, 2|2)>,
    <Signal1D, title: , dimensions: (3, 2|2)>]
>>> s.split(step_sizes=[1,2])
    [<Signal1D, title: , dimensions: (3, 1|2)>,
    <Signal1D, title: , dimensions: (3, 2|2)>]
Returns

Return type

list of the split signals

squeeze()

Remove single-dimensional entries from the shape of an array and the axes.

std(axis=None, out=None, rechunk=True)

Returns a signal with the standard deviation of the signal along at least one axis.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), min(), sum(), mean(), var(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.std(-1).data.shape
(64,64)
sum(axis=None, out=None, rechunk=True)

Sum the data over the given axes.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), min(), mean(), std(), var(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.sum(-1).data.shape
(64,64)
swap_axes(axis1, axis2, optimize=False)

Swaps the axes.

Parameters
  • axis2 (axis1,) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • optimize (bool) – If True, the location of the data in memory is optimised for the fastest iteration over the navigation axes. This operation can cause a peak of memory usage and requires considerable processing times for large datasets and/or low specification hardware. See the transposing section of the HyperSpy user guide for more information. When operating on lazy signals, if True the chunks are optimised for the new axes configuration.

Returns

s

Return type

a copy of the object with the axes swapped.

transpose(signal_axes=None, navigation_axes=None, optimize=False)

Transposes the signal to have the required signal and navigation axes.

Parameters
  • navigation_axes (signal_axes,) – With the exception of both parameters getting iterables, generally one has to be None (i.e. “floating”). The other one specifies either the required number or explicitly the axes to move to the corresponding space. If both are iterables, full control is given as long as all axes are assigned to one space only.

  • optimize (bool) – If True, the location of the data in memory is optimised for the fastest iteration over the navigation axes. This operation can cause a peak of memory usage and requires considerable processing times for large datasets and/or low specification hardware. See the transposing section of the HyperSpy user guide for more information. When operating on lazy signals, if True the chunks are optimised for the new axes configuration.

See also

T(), as_signal2D(), as_signal1D(), hs.transpose()

Examples

>>> # just create a signal with many distinct dimensions
>>> s = hs.signals.BaseSignal(np.random.rand(1,2,3,4,5,6,7,8,9))
>>> s
<BaseSignal, title: , dimensions: (|9, 8, 7, 6, 5, 4, 3, 2, 1)>
>>> s.transpose() # swap signal and navigation spaces
<BaseSignal, title: , dimensions: (9, 8, 7, 6, 5, 4, 3, 2, 1|)>
>>> s.T # a shortcut for no arguments
<BaseSignal, title: , dimensions: (9, 8, 7, 6, 5, 4, 3, 2, 1|)>

# roll to leave 5 axes in navigation space >>> s.transpose(signal_axes=5) <BaseSignal, title: , dimensions: (4, 3, 2, 1|9, 8, 7, 6, 5)>

# roll leave 3 axes in navigation space >>> s.transpose(navigation_axes=3) <BaseSignal, title: , dimensions: (3, 2, 1|9, 8, 7, 6, 5, 4)>

>>> # 3 explicitly defined axes in signal space
>>> s.transpose(signal_axes=[0, 2, 6])
<BaseSignal, title: , dimensions: (8, 6, 5, 4, 2, 1|9, 7, 3)>
>>> # A mix of two lists, but specifying all axes explicitly
>>> # The order of axes is preserved in both lists
>>> s.transpose(navigation_axes=[1, 2, 3, 4, 5, 8], signal_axes=[0, 6, 7])
<BaseSignal, title: , dimensions: (8, 7, 6, 5, 4, 1|9, 3, 2)>
unfold(unfold_navigation=True, unfold_signal=True)

Modifies the shape of the data by unfolding the signal and navigation dimensions separately

Returns

needed_unfolding

Return type

bool

unfold_navigation_space()

Modify the shape of the data to obtain a navigation space of dimension 1

Returns

needed_unfolding

Return type

bool

unfold_signal_space()

Modify the shape of the data to obtain a signal space of dimension 1

Returns

needed_unfolding

Return type

bool

unfolded(unfold_navigation=True, unfold_signal=True)

Use this function together with a with statement to have the signal be unfolded for the scope of the with block, before automatically refolding when passing out of scope.

See also

unfold(), fold()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> with s.unfolded():
        # Do whatever needs doing while unfolded here
        pass
update_plot()
valuemax(axis, out=None, rechunk=True)

Returns a signal with the value of coordinates of the maximum along an axis.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max, min, sum, mean, std, var, indexmax, amax

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.valuemax(-1).data.shape
(64,64)
valuemin(axis, out=None, rechunk=True)

Returns a signal with the value of coordinates of the minimum along an axis.

Parameters
  • axis (int, str or axis) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), min(), sum(), mean(), std(), var(), indexmax(), amax()

var(axis=None, out=None, rechunk=True)

Returns a signal with the variances of the signal along at least one axis.

Parameters
  • axis (int, str, axis, tuple of axis or None) – Either one on its own, or many axes in a tuple can be passed. In both cases the axes can be passed directly, or specified using the index in axes_manager or the name of the axis. Any duplicates are removed. If None, the operation is performed over all navigation axes (default).

  • out (Signal or None) – If None, a new Signal is created with the result of the operation and returned (default). If a Signal is passed, it is used to receive the output of the operation, and nothing is returned.

  • rechunk (bool) – Only has effect when operating on lazy signal. If True (default), the data may be automatically rechunked before performing this operation.

Returns

s

Return type

Signal

See also

max(), min(), sum(), mean(), std(), indexmax(), valuemax(), amax()

Examples

>>> import numpy as np
>>> s = BaseSignal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.var(-1).data.shape
(64,64)
hyperspy.signal.COMPARISON_OPERATORS = ('__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__')
hyperspy.signal.INPLACE_OPERATORS = ('__iadd__', '__isub__', '__imul__', '__itruediv__', '__ifloordiv__', '__imod__', '__ipow__', '__ilshift__', '__irshift__', '__iand__', '__ixor__', '__ior__')
class hyperspy.signal.MVATools

Bases: object

export_bss_results(comp_ids=None, folder=None, calibrate=True, multiple_files=True, save_figures=False, factor_prefix='bss_factor', factor_format='hspy', loading_prefix='bss_loading', loading_format='hspy', comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, same_window=False, no_nans=True, per_row=3, save_figures_format='png')

Export results from ICA to any of the supported formats.

Parameters
  • comp_ids (None, int, or list of ints) –

    if None, returns all components/loadings. if int, returns components/loadings with ids from 0 to given

    int.

    if list of ints, returns components/loadings with ids in iven list.

  • folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.

  • factor_prefix (string) – The prefix that any exported filenames for factors/components begin with

  • factor_format (string) – The extension of the format that you wish to save to. Default is “hspy”. See loading format for more details.

  • loading_prefix (string) – The prefix that any exported filenames for factors/components begin with

  • loading_format (string) –

    The extension of the format that you wish to save to. default is “hspy”. The format determines the kind of output. - For image formats (tif, png, jpg, etc.), plots are

    created using the plotting flags as below, and saved at 600 dpi. One plot per loading is saved.

    • For multidimensional formats (“rpl”, “hspy”), arrays are saved in single files. All loadings are contained in the one file.

    • For spectral formats (msa), each loading is saved to a separate file.

  • multiple_files (Bool) – If True, on exporting a file per factor and per loading will be created. Otherwise only two files will be created, one for the factors and another for the loadings. Default is True.

  • save_figures (Bool) – If True the same figures that are obtained when using the plot methods will be saved with 600 dpi resolution

  • options (for save_figures = True ONLY) (Plotting) –

  • ----------------------------------------------

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window.

  • comp_label (string) – the label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window)

  • cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.

  • per_row (int, the number of plots in each row, when the) –

  • same_window – parameter is True.

  • save_figures_format (str) – The image format extension.

See also

get_bss_factors(), get_bss_loadings.()

export_decomposition_results(comp_ids=None, folder=None, calibrate=True, factor_prefix='factor', factor_format='hspy', loading_prefix='loading', loading_format='hspy', comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, same_window=False, multiple_files=True, no_nans=True, per_row=3, save_figures=False, save_figures_format='png')

Export results from a decomposition to any of the supported formats.

Parameters
  • comp_ids (None, int, or list of ints) – if None, returns all components/loadings. if int, returns components/loadings with ids from 0 to given int. if list of ints, returns components/loadings with ids in given list.

  • folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.

  • factor_prefix (string) – The prefix that any exported filenames for factors/components begin with

  • factor_format (string) – The extension of the format that you wish to save to. Default is “hspy”. See loading format for more details.

  • loading_prefix (string) – The prefix that any exported filenames for factors/components begin with

  • loading_format (string) –

    The extension of the format that you wish to save to. default is “hspy”. The format determines the kind of output. - For image formats (tif, png, jpg, etc.), plots are

    created using the plotting flags as below, and saved at 600 dpi. One plot per loading is saved.

    • For multidimensional formats (“rpl”, “hspy”), arrays are saved in single files. All loadings are contained in the one file.

    • For spectral formats (msa), each loading is saved to a separate file.

  • multiple_files (bool) – If True, on exporting a file per factor and per loading will be created. Otherwise only two files will be created, one for the factors and another for the loadings. The default value can be chosen in the preferences.

  • save_figures (bool) – If True the same figures that are obtained when using the plot methods will be saved with 600 dpi resolution

  • options (for save_figures = True ONLY) (Plotting) –

  • ----------------------------------------------

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window.

  • comp_label (string, the label that is either the plot title) – (if plotting in separate windows) or the label in the legend (if plotting in the same window)

  • cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.

  • per_row (int, the number of plots in each row, when the) –

  • same_window – parameter is True.

  • save_figures_format (str) – The image format extension.

See also

get_decomposition_factors(), get_decomposition_loadings.()

get_bss_factors()

Return the blind source separtion factors as a Signal.

See also

get_bss_loadings(), export_bss_results.()

get_bss_loadings()

Return the blind source separtion loadings as a Signal.

See also

get_bss_factors(), export_bss_results.()

get_decomposition_factors()

Return the decomposition factors as a Signal.

See also

get_decomposition_loadings(), export_decomposition_results.()

get_decomposition_loadings()

Return the decomposition loadings as a Signal.

See also

get_decomposition_factors(), export_decomposition_results.()

plot_bss_factors(comp_ids=None, calibrate=True, same_window=True, comp_label=None, per_row=3, title=None)

Plot factors from blind source separation results. In case of 1D signal axis, each factors line can be toggled on and off by clicking on their corresponding line in the legend.

Parameters
  • comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window. They are not scaled. Default is True.

  • title (string) – Title of the plot.

  • cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.

  • per_row (int, the number of plots in each row, when the) –

  • same_window – parameter is True.

See also

plot_bss_loadings(), plot_bss_results.()

plot_bss_loadings(comp_ids=None, calibrate=True, same_window=True, comp_label=None, with_factors=False, cmap=<matplotlib.colors.LinearSegmentedColormap object>, no_nans=False, per_row=3, axes_decor='all', title=None)

Plot loadings from blind source separation results. In case of 1D navigation axis, each loading line can be toggled on and off by clicking on their corresponding line in the legend.

Parameters
  • comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window. They are not scaled. Default is True.

  • title (string) – Title of the plot.

  • with_factors (bool) – If True, also returns figure(s) with the factors for the given comp_ids.

  • cmap (matplotlib colormap) – The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic.

  • no_nans (bool) – If True, removes NaN’s from the loading plots.

  • per_row (int) – the number of plots in each row, when the same_window parameter is True.

  • axes_decor ({'all', 'ticks', 'off', None}, optional) – Controls how the axes are displayed on each image; default is ‘all’ If ‘all’, both ticks and axis labels will be shown If ‘ticks’, no axis labels will be shown, but ticks / labels will If ‘off’, all decorations and frame will be disabled If None, no axis decorations will be shown, but ticks/frame will

See also

plot_bss_factors(), plot_bss_results.()

plot_bss_results(factors_navigator='smart_auto', loadings_navigator='smart_auto', factors_dim=2, loadings_dim=2)

Plot the blind source separation factors and loadings.

Unlike plot_bss_factors and plot_bss_loadings, this method displays one component at a time. Therefore it provides a more compact visualization than then other two methods. The loadings and factors are displayed in different windows and each has its own navigator/sliders to navigate them if they are multidimensional. The component index axis is synchronized between the two.

Parameters
  • loadings_navigator (factors_navigator,) –

  • Signal} – “smart_auto” (default) displays sliders if the navigation dimension is less than 3. For a description of the other options see plot documentation for details.

  • loadings_dim (factors_dim,) – Currently HyperSpy cannot plot signals of dimension higher than two. Therefore, to visualize the BSS results when the factors or the loadings have signal dimension greater than 2 we can view the data as spectra(images) by setting this parameter to 1(2). (Default 2)

See also

plot_bss_factors(), plot_bss_loadings(), plot_decomposition_results.()

plot_decomposition_factors(comp_ids=None, calibrate=True, same_window=True, comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, per_row=3, title=None)

Plot factors from a decomposition. In case of 1D signal axis, each factors line can be toggled on and off by clicking on their corresponding line in the legend.

Parameters
  • comp_ids (None, int, or list of ints) – if None (default), returns maps of all components if the output_dimension was defined when executing decomposition. Otherwise it raises a ValueError. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window. They are not scaled. Default is True.

  • title (string) – Title of the plot.

  • cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.

  • per_row (int, the number of plots in each row, when the) –

  • parameter is True. (same_window) –

See also

plot_decomposition_loadings(), plot_decomposition_results.()

plot_decomposition_loadings(comp_ids=None, calibrate=True, same_window=True, comp_label=None, with_factors=False, cmap=<matplotlib.colors.LinearSegmentedColormap object>, no_nans=False, per_row=3, axes_decor='all', title=None)

Plot loadings from a decomposition. In case of 1D navigation axis, each loading line can be toggled on and off by clicking on the legended line.

Parameters
  • comp_ids (None, int, or list of ints) – if None (default), returns maps of all components if the output_dimension was defined when executing decomposition. Otherwise it raises a ValueError. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.

  • calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.

  • same_window (bool) – if True, plots each factor to the same window. They are not scaled. Default is True.

  • title (string) – Title of the plot.

  • with_factors (bool) – If True, also returns figure(s) with the factors for the given comp_ids.

  • cmap (matplotlib colormap) – The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic.

  • no_nans (bool) – If True, removes NaN’s from the loading plots.

  • per_row (int) – the number of plots in each row, when the same_window parameter is True.

  • axes_decor ({'all', 'ticks', 'off', None}, optional) – Controls how the axes are displayed on each image; default is ‘all’ If ‘all’, both ticks and axis labels will be shown If ‘ticks’, no axis labels will be shown, but ticks/labels will If ‘off’, all decorations and frame will be disabled If None, no axis decorations will be shown, but ticks/frame will

See also

plot_decomposition_factors(), plot_decomposition_results.()

plot_decomposition_results(factors_navigator='smart_auto', loadings_navigator='smart_auto', factors_dim=2, loadings_dim=2)

Plot the decompostion factors and loadings.

Unlike plot_factors and plot_loadings, this method displays one component at a time. Therefore it provides a more compact visualization than then other two methods. The loadings and factors are displayed in different windows and each has its own navigator/sliders to navigate them if they are multidimensional. The component index axis is synchronized between the two.

Parameters
  • loadings_navigator (factors_navigator,) –

  • Signal} – “smart_auto” (default) displays sliders if the navigation dimension is less than 3. For a description of the other options see plot documentation for details.

  • loadings_dim (factors_dim,) – Currently HyperSpy cannot plot signals of dimension higher than two. Therefore, to visualize the BSS results when the factors or the loadings have signal dimension greater than 2 we can view the data as spectra(images) by setting this parameter to 1(2). (Default 2)

See also

plot_factors(), plot_loadings(), plot_bss_results.()

class hyperspy.signal.ModelManager(signal, dictionary=None)

Bases: object

Container for models

class ModelStub(mm, name)

Bases: object

pop(name)

Returns the restored model and removes it from storage

Parameters

name (string) – the name of the model to restore and remove

remove(name)

Removes the given model

Parameters

name (string) – the name of the model to remove

See also

restore(), store(), pop()

restore(name)

Returns the restored model

Parameters

name (string) – the name of the model to restore

See also

remove(), store(), pop()

store(model, name=None)

If the given model was created from this signal, stores it

Parameters
  • model (model) – the model to store in the signal

  • name ({string, None}) – the name for the model to be stored with

See also

remove(), restore(), pop()

class hyperspy.signal.SpecialSlicersSignal(obj, isNavigation)

Bases: hyperspy.misc.slicing.SpecialSlicers

hyperspy.signal.UNARY_OPERATORS = ('__neg__', '__pos__', '__abs__', '__invert__')