hyperspy package

Subpackages

Submodules

hyperspy.Release module

hyperspy.api module

All public packages, functions and classes are available in this module.

When starting HyperSpy using the hyperspy script (e.g. by executing hyperspy in a console, using the context menu entries or using the links in the Start Menu, the api package is imported in the user namespace as hs, i.e. by executing the following:

>>> import hyperspy.api as hs

(Note that code snippets are indicated by three greater-than signs)

We recommend to import the HyperSpy API as above also when doing it manually. The docstring examples assume that hyperspy has been imported as hs, numpy as np and matplotlib.pyplot as plt.

Functions:

create_model
Create a model for curve fitting.
get_configuration_directory_path
Return the configuration directory path.
load
Load data into Signal instances from supported files.
preferences
Preferences class instance to configure the default value of different parameters. It has a CLI and a GUI that can be started by execting its gui method i.e. preferences.gui().
stack
Stack several signals.

The api package contains the following submodules/packages:

signals
Signal classes which are the core of HyperSpy. Use this modules to create Signal instances manually from numpy arrays. Note that to load data from supported file formats is more convenient to use the load function.
model
Contains the components module with components that can be used to create a model for curve fitting.
eds
Functions for energy dispersive X-rays data analysis.
material
Useful functions for materials properties and elements database that includes physical properties and X-rays and EELS energies.
plot
Plotting functions that operate on multiple signals.
datasets
Example datasets.

For more details see their doctrings.

hyperspy.axes module

class hyperspy.axes.AxesManager(axes_list)

Bases: traits.has_traits.HasTraits

Contains and manages the data axes.

It supports indexing, slicing, subscriptins and iteration. As an iterator, iterate over the navigation coordinates returning the current indices. It can only be indexed and sliced to access the DataAxis objects that it contains. Standard indexing and slicing follows the “natural order” as in Signal, i.e. [nX, nY, ...,sX, sY,...] where n indicates a navigation axis and s a signal axis. In addition AxesManager support indexing using complex numbers a + bj, where b can be one of 0, 1, 2 and 3 and a a valid index. If b is 3 AxesManager is indexed using the order of the axes in the array. If b is 1(2), indexes only the navigation(signal) axes in the natural order. In addition AxesManager supports subscription using axis name.

coordinates

tuple – Get and set the current coordinates if the navigation dimension is not 0. If the navigation dimension is 0 it raises AttributeError when attempting to set its value.

indices : tuple
Get and set the current indices if the navigation dimension is not 0. If the navigation dimension is 0 it raises AttributeError when attempting to set its value.
signal_axes, navigation_axes : list
Contain the corresponding DataAxis objects

Examples

>>> %hyperspy
HyperSpy imported!
The following commands were just executed:
---------------
import numpy as np
import hyperspy.api as hs
%matplotlib qt
import matplotlib.pyplot as plt
>>> # Create a spectrum with random data
>>> s = hs.signals.Signal1D(np.random.random((2,3,4,5)))
>>> s.axes_manager
<Axes manager, axes: (<axis2 axis, size: 4, index: 0>, <axis1 axis, size: 3, index: 0>, <axis0 axis, size: 2, index: 0>, <axis3 axis, size: 5>)>
>>> s.axes_manager[0]
<axis2 axis, size: 4, index: 0>
>>> s.axes_manager[3j]
<axis0 axis, size: 2, index: 0>
>>> s.axes_manager[1j]
<axis2 axis, size: 4, index: 0>
>>> s.axes_manager[2j]
<axis3 axis, size: 5>
>>> s.axes_manager[1].name="y"
>>> s.axes_manager['y']
<y axis, size: 3 index: 0>
>>> for i in s.axes_manager:
>>>     print i, s.axes_manager.indices
(0, 0, 0) (0, 0, 0)
(1, 0, 0) (1, 0, 0)
(2, 0, 0) (2, 0, 0)
(3, 0, 0) (3, 0, 0)
(0, 1, 0) (0, 1, 0)
(1, 1, 0) (1, 1, 0)
(2, 1, 0) (2, 1, 0)
(3, 1, 0) (3, 1, 0)
(0, 2, 0) (0, 2, 0)
(1, 2, 0) (1, 2, 0)
(2, 2, 0) (2, 2, 0)
(3, 2, 0) (3, 2, 0)
(0, 0, 1) (0, 0, 1)
(1, 0, 1) (1, 0, 1)
(2, 0, 1) (2, 0, 1)
(3, 0, 1) (3, 0, 1)
(0, 1, 1) (0, 1, 1)
(1, 1, 1) (1, 1, 1)
(2, 1, 1) (2, 1, 1)
(3, 1, 1) (3, 1, 1)
(0, 2, 1) (0, 2, 1)
(1, 2, 1) (1, 2, 1)
(2, 2, 1) (2, 2, 1)
(3, 2, 1) (3, 2, 1)
as_dictionary()
axes_are_aligned_with_data

Verify if the data axes are aligned with the signal axes.

When the data are aligned with the axes the axes order in self._axes is [nav_n, nav_n-1, ..., nav_0, sig_m, sig_m-1 ..., sig_0].

Returns:aligned
Return type:bool
connect(f)
coordinates

Get the coordinates of the navigation axes.

Returns:
Return type:list
copy()
create_axes(axes_list)

Given a list of dictionaries defining the axes properties create the DataAxis instances and add them to the AxesManager.

The index of the axis in the array and in the _axes lists can be defined by the index_in_array keyword if given for all axes. Otherwise it is defined by their index in the list.

See also

_append_axis()

deepcopy()
disconnect(f)
gui()
indices

Get the index of the navigation axes.

Returns:
Return type:list
key_navigator(event)
navigation_indices_in_array
remove(axis)

Remove the given Axis.

Raises:ValueError if the Axis is not present.
set_signal_dimension(value)

Set the dimension of the signal.

value

int

Raises:
  • ValueError if value if greater than the number of axes or
  • is negative
shape
show()
signal_indices_in_array
class hyperspy.axes.DataAxis(size, index_in_array=None, name=<undefined>, scale=1.0, offset=0.0, units=<undefined>, navigate=<undefined>)

Bases: traits.has_traits.HasTraits

calibrate(value_tuple, index_tuple, modify_calibration=True)
connect(f, trait='value')
copy()
disconnect(f, trait='value')
get_axis_dictionary()
index2value(index)
index_in_array
index_in_axes_manager
set_index_from_value(value)
update_axis()
update_index_bounds()
update_value()
value2index(value, rounding=<built-in function round>)

Return the closest index to the given value if between the limit.

Parameters:value (number or numpy array) –
Returns:index
Return type:integer or numpy array
Raises:ValueError if any value is out of the axis limits.
value_range_to_indices(v1, v2)

Convert the given range to index range.

When an out of the axis limits, the endpoint is used instead.

Parameters:v2 (v1,) – The end points of the interval in the axis units. v2 must be greater than v1.
hyperspy.axes.generate_axis(offset, scale, size, offset_index=0)

Creates an axis given the offset, scale and number of channels

Alternatively, the offset_index of the offset channel can be specified.

Parameters:
  • offset (float) –
  • scale (float) –
  • size (number of channels) –
  • offset_index (int) – offset_index number of the offset
Returns:

Return type:

Numpy array

class hyperspy.axes.ndindex_nat(*shape)

Bases: numpy.lib.index_tricks.ndindex

hyperspy.component module

class hyperspy.component.Component(parameter_name_list)

Bases: traits.has_traits.HasTraits

active_is_multidimensional
connect(f)
disconnect(f)
export(folder=None, format=None, save_std=False, only_free=True)

Plot the value of the parameters of the model

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

    The format to which the data will be exported. It must be the extension of any format supported by HyperSpy. If None, the default format for exporting as defined in the Preferences will be

    used.
  • save_std (bool) – If True, also the standard deviation will be saved.
  • only_free (bool) –
    If True, only the value of the parameters that are free will
    be

    exported.

Notes

The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.

fetch_stored_values(only_fixed=False)
fetch_values_from_array(p, p_std=None, onlyfree=False)
init_parameters(parameter_name_list)
notebook_interaction(display=True)

Creates interactive notebook widgets for all component parameters, if available.

Requires ipywidgets to be installed.

Parameters:display (bool) – if True (default), attempts to display the widgets. Otherwise returns the formatted widget object.
plot(only_free=True)

Plot the value of the parameters of the model

Parameters:only_free (bool) –
If True, only the value of the parameters that are free will
be plotted
set_parameters_free(parameter_name_list=None)

Sets parameters in a component to free.

Parameters:parameter_name_list (None or list of strings, optional) – If None, will set all the parameters to free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to free.

Examples

>>> v1 = hs.model.components.Voigt()
>>> v1.set_parameters_free()
>>> v1.set_parameters_free(parameter_name_list=['area','centre'])
set_parameters_not_free(parameter_name_list=None)

Sets parameters in a component to not free.

Parameters:parameter_name_list (None or list of strings, optional) – If None, will set all the parameters to not free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to not free.

Examples

>>> v1 = hs.model.components.Voigt()
>>> v1.set_parameters_not_free()
>>> v1.set_parameters_not_free(parameter_name_list=['area','centre'])
store_current_parameters_in_map()
summary()
update_number_parameters()
class hyperspy.component.NoneFloat(default_value=<traits.trait_handlers.NoDefaultSpecified object>, **metadata)

Bases: traits.trait_types.CFloat

default_value = None
validate(object, name, value)
class hyperspy.component.Parameter

Bases: traits.has_traits.HasTraits

Model parameter

value

float or array – The value of the parameter for the current location. The value for other locations is stored in map.

bmin, bmax

float – Lower and upper bounds of the parameter value.

twin

{None, Parameter} – If it is not None, the value of the current parameter is a function of the given Parameter. The function is by default the identity function, but it can be defined by twin_function

twin_function

function – Function that, if selt.twin is not None, takes self.twin.value as its only argument and returns a float or array that is returned when getting Parameter.value

twin_inverse_function

function – The inverse of twin_function. If it is None then it is not possible to set the value of the parameter twin by setting the value of the current parameter.

ext_force_positive

bool – If True, the parameter value is set to be the absolute value of the input value i.e. if we set Parameter.value = -3, the value stored is 3 instead. This is useful to bound a value to be positive in an optimization without actually using an optimizer that supports bounding.

ext_bounded

bool – Similar to ext_force_positive, but in this case the bounds are defined by bmin and bmax. It is a better idea to use an optimizer that supports bounding though.

as_signal(field = 'values')

Get a parameter map as a signal object

plot()

Plots the value of the Parameter at all locations.

export(folder=None, name=None, format=None, save_std=False)

Saves the value of the parameter map to the specified format

connect, disconnect(function)

Call the functions connected when the value attribute changes.

as_signal(field='values')

Get a parameter map as a signal object.

Please note that this method only works when the navigation dimension is greater than 0.

Parameters:field ({'values', 'std', 'is_set'}) –
Raises:NavigationDimensionError : if the navigation dimension is 0
assign_current_value_to_all(mask=None)

Assign the current value attribute to all the indices

Parameters:mask ({None, boolean numpy array}) – Set only the indices that are not masked i.e. where mask is False.
connect(f)
default_traits_view()
disconnect(f)
export(folder=None, name=None, format=None, save_std=False)

Save the data to a file.

All the arguments are optional.

Parameters:
  • folder (str or None) –
    The path to the folder where the file will be saved.
    If None the current folder is used by default.
  • name (str or None) –
    The name of the file. If None the Components name followed
    by the Parameter name attributes will be used by default.
    If a file with the same name exists the name will be modified by appending a number to the file path.
  • save_std (bool) – If True, also the standard deviation will be saved
ext_bounded
ext_force_positive
fetch()

Fetch the stored value and std attributes.

notebook_interaction(display=True)

Creates interactive notebook widgets for the parameter, if available.

Requires ipywidgets to be installed.

Parameters:display (bool) – if True (default), attempts to display the parameter widget. Otherwise returns the formatted widget object.
plot()
store_current_value_in_array()

Store the value and std attributes.

twin

hyperspy.components module

Components that can be used to define a model for e.g. curve fitting.

There are some components that are only useful for one particular kind of signal and therefore their name are preceded by the signal name: eg. eels_cl_edge.

For more details see each component docstring.

Arctan Arctan function component.. Bleasdale Bleasdale function component... DoubleOffset Deprecated in favour of HeavisideStep compo.. DoublePowerLaw .. EELSCLEdge EELS core loss ionisation edge from hydroge.. Erf Error function component.. Exponential Exponentian function components.. Expression Create a component from a string expression.. Gaussian Normalized gaussian function component.. HeavisideStep The Heaviside step function.. Logistic Logistic function component.. Lorentzian Cauchy-Lorentz distribution (a.k.a. Lorentz.. Offset Component to add a constant value in the y-.. PESCoreLineShape .. Polynomial n-order polynomial component... PowerLaw Power law component.. RC .. SEE Secondary electron emission component for P.. ScalableFixedPattern Fixed pattern component with interpolation .. Spline .. Vignetting .. Voigt Voigt profile component with support for sh.. VolumePlasmonDrude Drude volume plasmon energy loss function c..

hyperspy.decorators module

hyperspy.decorators.auto_replot(f)
hyperspy.decorators.do_not_replot(f)
hyperspy.decorators.interactive_range_selector(f)
hyperspy.decorators.only_interactive(f)
hyperspy.decorators.simple_decorator(decorator)

This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn’t modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied.

This decorator was taken from: http://wiki.python.org/moin/PythonDecoratorLibrary

hyperspy.defaults_parser module

class hyperspy.defaults_parser.EDSConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.EELSConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.GeneralConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.MachineLearningConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.ModelConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.PlotConfig

Bases: traits.has_traits.HasTraits

class hyperspy.defaults_parser.Preferences

Bases: traits.has_traits.HasTraits

gui()
save()
hyperspy.defaults_parser.config2template(template, config)
hyperspy.defaults_parser.dictionary_from_template(template)
hyperspy.defaults_parser.file_version(fname)
hyperspy.defaults_parser.guess_gos_path()
hyperspy.defaults_parser.template2config(template, config)

hyperspy.exceptions module

exception hyperspy.exceptions.ByteOrderError(order='')

Bases: Exception

exception hyperspy.exceptions.DM3DataTypeError(value='')

Bases: Exception

exception hyperspy.exceptions.DM3FileVersionError(value='')

Bases: Exception

exception hyperspy.exceptions.DM3TagError(value='')

Bases: Exception

exception hyperspy.exceptions.DM3TagIDError(value='')

Bases: Exception

exception hyperspy.exceptions.DM3TagTypeError(value='')

Bases: Exception

exception hyperspy.exceptions.DataDimensionError(msg)

Bases: Exception

exception hyperspy.exceptions.ImageIDError(value='')

Bases: Exception

exception hyperspy.exceptions.ImageModeError(value='')

Bases: Exception

exception hyperspy.exceptions.MissingParametersError(parameters)

Bases: Exception

exception hyperspy.exceptions.NavigationDimensionError(navigation_dimension, expected_navigation_dimension)

Bases: Exception

exception hyperspy.exceptions.NavigationSizeError(navigation_size, expected_navigation_size)

Bases: Exception

exception hyperspy.exceptions.NoInteractiveError

Bases: Exception

exception hyperspy.exceptions.ShapeError(value)

Bases: Exception

exception hyperspy.exceptions.SignalDimensionError(output_dimension, expected_output_dimension)

Bases: Exception

exception hyperspy.exceptions.SignalSizeError(signal_size, expected_signal_size)

Bases: Exception

exception hyperspy.exceptions.WrongObjectError(is_str, must_be_str)

Bases: Exception

hyperspy.hspy module

This module is deprecated and will be removed in HyperSpy 0.10, plese use api instead.

hyperspy.hspy.create_model(signal, *args, **kwargs)

Create a model object

Any extra argument is passes to the Model constructor.

Parameters:
  • signal (A signal class) –
  • the signal is an EELS signal the following extra parameters (If) –
  • available (are) –
  • auto_background (boolean) – If True, and if spectrum is an EELS instance adds automatically a powerlaw to the model and estimate the parameters by the two-area method.
  • auto_add_edges (boolean) – If True, and if spectrum is an EELS instance, it will automatically add the ionization edges as defined in the Spectrum instance. Adding a new element to the spectrum using the components.EELSSpectrum.add_elements method automatically add the corresponding ionisation edges to the model.
  • ll ({None, EELSSpectrum}) – If an EELSSPectrum is provided, it will be assumed that it is a low-loss EELS spectrum, and it will be used to simulate the effect of multiple scattering by convolving it with the EELS spectrum.
  • GOS ({'hydrogenic', 'Hartree-Slater', None}) – The GOS to use when auto adding core-loss EELS edges. If None it will use the Hartree-Slater GOS if they are available, otherwise it will use the hydrogenic GOS.
Returns:

Return type:

A Model class

hyperspy.hspy.get_configuration_directory_path()

hyperspy.io module

hyperspy.io.assign_signal_subclass(record_by='', signal_type='', signal_origin='')

Given record_by and signal_type return the matching Signal subclass.

Parameters:
  • record_by ({"spectrum", "image", ""}) –
  • signal_type ({"EELS", "EDS", "EDS_TEM", "", str}) –
  • signal_origin ({"experiment", "simulation", ""}) –
Returns:

Return type:

Signal or subclass

hyperspy.io.dict2signal(signal_dict)

Create a signal (or subclass) instance defined by a dictionary

Parameters:signal_dict (dictionary) –
Returns:s
Return type:Signal or subclass
hyperspy.io.load(filenames=None, record_by=None, signal_type=None, signal_origin=None, stack=False, stack_axis=None, new_axis_name='stack_element', mmap=False, mmap_dir=None, **kwds)

Load potentially multiple supported file into an hyperspy structure Supported formats: HDF5, msa, Gatan dm3, Ripple (rpl+raw) FEI ser and emi and hdf5, tif and a number of image formats.

Any extra keyword is passed to the corresponsing reader. For available options see their individual documentation.

Parameters:
  • filenames (None, str or list of strings) – The filename to be loaded. If None, a window will open to select a file to load. If a valid filename is passed in that single file is loaded. If multiple file names are passed in a list, a list of objects or a single object containing the data of the individual files stacked are returned. This behaviour is controlled by the stack parameter (see bellow). Multiple files can be loaded by using simple shell-style wildcards, e.g. ‘my_file*.msa’ loads all the files that starts by ‘my_file’ and has the ‘.msa’ extension.
  • record_by ({None, 'spectrum', 'image', ""}) – The value provided may determine the Signal subclass assigned to the data. If None, the value is read or guessed from the file. Any other value overrides the value stored in the file if any. If “spectrum” load the data in a Spectrum (sub)class. If “image” load the data in an Image (sub)class. If “” (empty string) load the data in a Signal class.
  • signal_type ({None, "EELS", "EDS_TEM", "EDS_SEM", "", str}) – The acronym that identifies the signal type. The value provided may determine the Signal subclass assigned to the data. If None the value is read/guessed from the file. Any other value overrides the value stored in the file if any. For electron energy-loss spectroscopy use “EELS”. For energy dispersive x-rays use “EDS_TEM” if acquired from an electron-transparent sample — as it is usually the case in a transmission electron microscope (TEM) —, “EDS_SEM” if acquired from a non electron-transparent sample — as it is usually the case in a scanning electron microscope (SEM) —. If “” (empty string) the value is not read from the file and is considered undefined.
  • signal_origin ({None, "experiment", "simulation", ""}) – Defines the origin of the signal. The value provided may determine the Signal subclass assigned to the data. If None the value is read/guessed from the file. Any other value overrides the value stored in the file if any. Use “experiment” if loading experimental data. Use “simulation” if loading simulated data. If “” (empty string) the value is not read from the file and is considered undefined.
  • stack (bool) – If True and multiple filenames are passed in, stacking all the data into a single object is attempted. All files must match in shape. It is possible to store the data in a memory mapped temporary file instead of in memory setting mmap_mode. The title is set to the name of the folder containing the files.
  • stack_axis ({None, int, str}) – If None, the signals are stacked over a new axis. The data must have the same dimensions. Otherwise the signals are stacked over the axis given by its integer index or its name. The data must have the same shape, except in the dimension corresponding to axis.
  • new_axis_name (string) – The name of the new axis when axis is None. If an axis with this name already exists it automatically append ‘-i’, where i are integers, until it finds a name that is not yet in use.
  • mmap (bool) – If True and stack is True, then the data is stored in a memory-mapped temporary file.The memory-mapped data is stored on disk, and not directly loaded into memory. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.
  • mmap_dir (string) – If mmap_dir is not None, and stack and mmap are True, the memory mapped file will be created in the given directory, otherwise the default directory is used.
Returns:

Return type:

Signal instance or list of signal instances

Examples

Loading a single file providing the signal type:

>>> d = hs.load('file.dm3', signal_type='EDS_TEM')

Loading a single file and overriding its default record_by:

>>> d = hs.load('file.dm3', record_by='Image')

Loading multiple files:

>>> d = hs.load('file1.dm3','file2.dm3')

Loading multiple files matching the pattern:

>>> d = hs.load('file*.dm3')
hyperspy.io.load_single_file(filename, record_by=None, signal_type=None, signal_origin=None, **kwds)

Load any supported file into an HyperSpy structure Supported formats: netCDF, msa, Gatan dm3, Ripple (rpl+raw) FEI ser and emi and hdf5.

Parameters:
  • filename (string) – File name (including the extension)
  • record_by ({None, 'spectrum', 'image'}) – If None (default) it will try to guess the data type from the file, if ‘spectrum’ the file will be loaded as an Spectrum object If ‘image’ the file will be loaded as an Image object
hyperspy.io.load_with_reader(filename, reader, record_by=None, signal_type=None, signal_origin=None, **kwds)
hyperspy.io.save(filename, signal, overwrite=None, **kwds)

hyperspy.messages module

hyperspy.messages.alert(text)
hyperspy.messages.information(text)
hyperspy.messages.warning(text)
hyperspy.messages.warning_exit(text)

hyperspy.model module

class hyperspy.model.Model(signal1D)

Bases: list

One-dimensional model and data fitting.

A model is constructed as a linear combination of components that are added to the model using append() or extend(). There are many predifined components available in the in the components module. If needed, new components can easyly created using the code of existing components as a template.

Once defined, the model can be fitted to the data using fit() or multifit(). Once the optimizer reaches the convergence criteria or the maximum number of iterations the new value of the component parameters are stored in the components.

It is possible to access the components in the model by their name or by the index in the model. An example is given at the end of this docstring.

signal1D

Signal1D instance – It contains the data to fit.

chisq

A Signal of floats – Chi-squared of the signal (or np.nan if not yet fit)

dof

A Signal of integers – Degrees of freedom of the signal (0 if not yet fit)

red_chisq

Signal instance – Reduced chi-squared.

components

ModelComponents instance – The components of the model are attributes of this class. This provides a convinient way to access the model components when working in IPython as it enables tab completion.

append()

Append one component to the model.

extend()

Append multiple components to the model.

remove()

Remove component from model.

as_signal()

Generate a Signal1D instance (possible multidimensional) from the model.

store_current_values()

Store the value of the parameters at the current position.

fetch_stored_values()

Fetch stored values of the parameters.

update_plot()

Force a plot update. (In most cases the plot should update automatically.)

set_signal_range, remove_signal range, reset_signal_range,
add signal_range.

Customize the signal range to fit.

fit, multifit

Fit the model to the data at the current position or the full dataset.

save_parameters2file, load_parameters_from_file

Save/load the parameter values to/from a file.

plot()

Plot the model and the data.

enable_plot_components, disable_plot_components

Plot each component separately. (Use after plot.)

set_current_values_to()

Set the current value of all the parameters of the given component as the value for all the dataset.

export_results()

Save the value of the parameters in separate files.

plot_results()

Plot the value of all parameters at all positions.

print_current_values()

Print the value of the parameters at the current position.

enable_adjust_position, disable_adjust_position

Enable/disable interactive adjustment of the position of the components that have a well defined position. (Use after plot).

fit_component()

Fit just the given component in the given signal range, that can be set interactively.

set_parameters_not_free, set_parameters_free

Fit the free status of several components and parameters at once.

set_parameters_value()

Set the value of a parameter in components in a model to a specified value.

Examples

In the following example we create a histogram from a normal distribution and fit it with a gaussian component. It demonstrates how to create a model from a Signal1D instance, add components to it, adjust the value of the parameters of the components, fit the model to the data and access the components in the model.

>>> s = hs.signals.Signal1D(
        np.random.normal(scale=2, size=10000)).get_histogram()
>>> g = hs.model.components.Gaussian()
>>> m = s.create_model()
>>> m.append(g)
>>> m.print_current_values()
Components  Parameter       Value
Gaussian
            sigma   1.000000
            A       1.000000
            centre  0.000000
>>> g.centre.value = 3
>>> m.print_current_values()
Components  Parameter       Value
Gaussian
            sigma   1.000000
            A       1.000000
            centre  3.000000
>>> g.sigma.value
1.0
>>> m.fit()
>>> g.sigma.value
1.9779042300856682
>>> m[0].sigma.value
1.9779042300856682
>>> m["Gaussian"].centre.value
-0.072121936813224569
add_signal_range(*args, **kwargs)

Adds the data in the given range from the data range that will be used by the fitting rountine

Parameters:
  • x1 (None or float) –
  • x2 (None or float) –
append(thing)
as_signal(component_list=None, out_of_range_to_nan=True, show_progressbar=None)

Returns a recreation of the dataset using the model. the spectral range that is not fitted is filled with nans.

Parameters:
  • component_list (list of hyperspy components, optional) – If a list of components is given, only the components given in the list is used in making the returned spectrum. The components can be specified by name, index or themselves.
  • out_of_range_to_nan (bool) – If True the spectral range that is not fitted is filled with nans.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns:

signal

Return type:

An instance of the same class as signal.

Examples

>>> s = hs.signals.Signal1D(np.random.random((10,100)))
>>> m = s.create_model()
>>> l1 = hs.model.components.Lorentzian()
>>> l2 = hs.model.components.Lorentzian()
>>> m.append(l1)
>>> m.append(l2)
>>> s1 = m.as_signal()
>>> s2 = m.as_signal(component_list=[l1])
assign_current_values_to_all(components_list=None, mask=None)

Set parameter values for all positions to the current ones.

Parameters:
  • component_list (list of components, optional) – If a list of components is given, the operation will be performed only in the value of the parameters of the given components. The components can be specified by name, index or themselves.
  • mask (boolean numpy array or None, optional) – The operation won’t be performed where mask is True.
disable_adjust_position()

Disables the interactive adjust position feature

disable_plot_components()
enable_adjust_position(components=None, fix_them=True, show_label=True)

Allow changing the x position of component by dragging a vertical line that is plotted in the signal model figure

Parameters:
  • components ({None, list of components}) – If None, the position of all the active components of the model that has a well defined x position with a value in the axis range will get a position adjustment line. Otherwise the feature is added only to the given components. The components can be specified by name, index or themselves.
  • fix_them (bool) – If True the position parameter of the components will be temporarily fixed until adjust position is disable. This can be useful to iteratively adjust the component positions and fit the model.
  • show_label (bool, optional) – If True, a label showing the component name is added to the plot next to the vertical line.
enable_plot_components()
ensure_parameters_in_bounds()

For all active components, snaps their free parameter values to be within their boundaries (if bounded). Does not touch the array of values.

export_results(folder=None, format=None, save_std=False, only_free=True, only_active=True)

Export the results of the parameters of the model to the desired folder.

Parameters:
  • folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.
  • format (str) – The format to which the data will be exported. It must be the extension of any format supported by HyperSpy. If None, the default format for exporting as defined in the Preferences will be used.
  • save_std (bool) – If True, also the standard deviation will be saved.
  • only_free (bool) – If True, only the value of the parameters that are free will be exported.
  • only_active (bool) – If True, only the value of the active parameters will be exported.

Notes

The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.

extend(iterable)
fetch_stored_values(only_fixed=False)

Fetch the value of the parameters that has been previously stored.

Parameters:only_fixed (bool) – If True, only the fixed parameters are fetched.
fit(fitter=None, method='ls', grad=False, bounded=False, ext_bounding=False, update_plot=False, **kwargs)

Fits the model to the experimental data.

The chi-squared, reduced chi-squared and the degrees of freedom are computed automatically when fitting. They are stored as signals, in the chisq, red_chisq and dof. Note that, unless metadata.Signal.Noise_properties.variance contains an accurate estimation of the variance of the data, the chi-squared and reduced chi-squared cannot be computed correctly. This is also true for homocedastic noise.

Parameters:
  • fitter ({None, "leastsq", "odr", "mpfit", "fmin"}) – The optimizer to perform the fitting. If None the fitter defined in preferences.Model.default_fitter is used. “leastsq” performs least squares using the Levenberg–Marquardt algorithm. “mpfit” performs least squares using the Levenberg–Marquardt algorithm and, unlike “leastsq”, support bounded optimization. “fmin” performs curve fitting using a downhill simplex algorithm. It is less robust than the Levenberg-Marquardt based optimizers, but, at present, it is the only one that support maximum likelihood optimization for poissonian noise. “odr” performs the optimization using the orthogonal distance regression algorithm. It does not support bounds. “leastsq”, “odr” and “mpfit” can estimate the standard deviation of the estimated value of the parameters if the “metada.Signal.Noise_properties.variance” attribute is defined. Note that if it is not defined the standard deviation is estimated using variance equal 1, what, if the noise is heterocedatic, will result in a biased estimation of the parameter values and errors. If variance is a Signal instance of the same navigation_dimension as the signal, and method is “ls” weighted least squares is performed.
  • method ({'ls', 'ml'}) – Choose ‘ls’ (default) for least squares and ‘ml’ for poissonian maximum-likelihood estimation. The latter is only available when fitter is “fmin”.
  • grad (bool) – If True, the analytical gradient is used if defined to speed up the optimization.
  • bounded (bool) – If True performs bounded optimization if the fitter supports it. Currently only “mpfit” support it.
  • update_plot (bool) – If True, the plot is updated during the optimization process. It slows down the optimization but it permits to visualize the optimization progress.
  • ext_bounding (bool) – If True, enforce bounding by keeping the value of the parameters constant out of the defined bounding area.
  • **kwargs (key word arguments) – Any extra key word argument will be passed to the chosen fitter. For more information read the docstring of the optimizer of your choice in scipy.optimize.

See also

multifit()

fit_component(component, signal_range='interactive', estimate_parameters=True, fit_independent=False, only_current=True, **kwargs)

Fit just the given component in the given signal range.

This method is useful to obtain starting parameters for the components. Any keyword arguments are passed to the fit method.

Parameters:
  • component (component instance) – The component must be in the model, otherwise an exception is raised. The component can be specified by name, index or itself.
  • signal_range ({'interactive', (left_value, right_value), None}) –
    If ‘interactive’ the signal range is selected using the span
    selector on the spectrum plot. The signal range can also be manually specified by passing a tuple of floats. If None the current signal range is used.
  • estimate_parameters (bool, default True) – If True will check if the component has an estimate_parameters function, and use it to estimate the parameters in the component.
  • fit_independent (bool, default False) – If True, all other components are disabled. If False, all other component parameters are fixed.
  • only_current (bool, default True) – If True, will only fit the currently selected index in the model. If False, will fit the full dataset. component paramemeters are fixed.

Examples

Signal range set interactivly

>>> g1 = hs.model.components.Gaussian()
>>> m.append(g1)
>>> m.fit_component(g1)

Signal range set through direct input

>>> m.fit_component(g1, signal_range=(50,100))
insert(**kwargs)
load_parameters_from_file(filename)

Loads the parameters array from a binary file written with the ‘save_parameters2file’ function.

Parameters:filename (str) –

Notes

In combination with save_parameters2file, this method can be used to recreate a model stored in a file. Actually, before HyperSpy 0.8 this is the only way to do so. However, this is known to be brittle. For example see https://github.com/hyperspy/hyperspy/issues/341.

low_loss
multifit(mask=None, fetch_only_fixed=False, autosave=False, autosave_every=10, show_progressbar=None, **kwargs)

Fit the data to the model at all the positions of the navigation dimensions.

Parameters:
  • mask ({None, numpy.array}) – To mask (do not fit) at certain position pass a numpy.array of type bool where True indicates that the data will not be fitted at the given position.
  • fetch_only_fixed (bool) – If True, only the fixed parameters values will be updated when changing the positon.
  • autosave (bool) – If True, the result of the fit will be saved automatically with a frequency defined by autosave_every.
  • autosave_every (int) – Save the result of fitting every given number of spectra.
  • show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
  • **kwargs (key word arguments) – Any extra key word argument will be passed to the fit method. See the fit method documentation for a list of valid arguments.

See also

fit()

notebook_interaction()

Creates interactive notebook widgets for all components and parameters, if available.

Requires ipywidgets to be installed.

plot(plot_components=False)

Plots the current signal to the screen and a map with a cursor to explore the SI.

Parameters:plot_components (bool) – If True, add a line per component to the signal figure.
plot_results(only_free=True, only_active=True)

Plot the value of the parameters of the model

Parameters:
  • only_free (bool) – If True, only the value of the parameters that are free will be plotted.
  • only_active (bool) – If True, only the value of the active parameters will be plotted.

Notes

The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.

print_current_values(only_free=True)

Print the value of each parameter of the model.

Parameters:only_free (bool) –
If True, only the value of the parameters that are free will
be printed.
red_chisq

Reduced chi-squared. Calculated from self.chisq and self.dof

remove(thing, touch=True)

Remove component from model.

Examples

>>> s = hs.signals.Signal1D(np.empty(1))
>>> m = s.create_model()
>>> g = hs.model.components.Gaussian()
>>> m.append(g)

You could remove g like this

>>> m.remove(g)

Like this:

>>> m.remove("Gaussian")

Or like this:

>>> m.remove(0)
remove_signal_range(*args, **kwargs)

Removes the data in the given range from the data range that will be used by the fitting rountine

Parameters:
  • x1 (None or float) –
  • x2 (None or float) –
reset_signal_range()

Resets the data range

reset_the_signal_range()
resume_update(update=True)

Resumes plot update after suspension by suspend_update()

Parameters:update (bool, optional) – If True, also updates plot after resuming (default).
save_parameters2file(filename)

Save the parameters array in binary format.

The data is saved to a single file in numpy’s uncompressed .npz format.

Parameters:filename (str) –

Notes

This method can be used to save the current state of the model in a way that can be loaded back to recreate the it using load_parameters_from file. Actually, as of HyperSpy 0.8 this is the only way to do so. However, this is known to be brittle. For example see https://github.com/hyperspy/hyperspy/issues/341.

set_boundaries()

Generate the boundary list.

Necessary before fitting with a boundary aware optimizer.

set_component_active_value(value, component_list=None, only_current=False)

Sets the component ‘active’ parameter to a specified value

Parameters:
  • value (bool) – The new value of the ‘active’ parameter
  • component_list (list of hyperspy components, optional) – A list of components whos parameters will changed. The components can be specified by name, index or themselves.
  • only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.

Examples

>>> v1 = hs.model.components.Voigt()
>>> v2 = hs.model.components.Voigt()
>>> m.extend([v1,v2])
>>> m.set_component_active_value(False)
>>> m.set_component_active_value(True, component_list=[v1])
>>> m.set_component_active_value(False, component_list=[v1],
                                 only_current=True)
set_convolution_axis()

Creates an axis to use to generate the data of the model in the precise scale to obtain the correct axis and origin after convolution with the lowloss spectrum.

set_mpfit_parameters_info()
set_parameters_free(component_list=None, parameter_name_list=None)

Sets the parameters in a component in a model to free.

Parameters:
  • component_list (None, or list of hyperspy components, optional) – If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves.
  • parameter_name_list (None or list of strings, optional) – If None, will set all the parameters to not free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to not free.

Examples

>>> v1 = hs.model.components.Voigt()
>>> m.append(v1)
>>> m.set_parameters_free()
>>> m.set_parameters_free(component_list=[v1],
                          parameter_name_list=['area','centre'])
set_parameters_not_free(component_list=None, parameter_name_list=None)

Sets the parameters in a component in a model to not free.

Parameters:
  • component_list (None, or list of hyperspy components, optional) – If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves.
  • parameter_name_list (None or list of strings, optional) – If None, will set all the parameters to not free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to not free.

Examples

>>> v1 = hs.model.components.Voigt()
>>> m.append(v1)
>>> m.set_parameters_not_free()
>>> m.set_parameters_not_free(component_list=[v1],
                              parameter_name_list=['area','centre'])
set_parameters_value(parameter_name, value, component_list=None, only_current=False)

Sets the value of a parameter in components in a model to a specified value

Parameters:
  • parameter_name (string) – Name of the parameter whos value will be changed
  • value (number) – The new value of the parameter
  • component_list (list of hyperspy components, optional) – A list of components whos parameters will changed. The components can be specified by name, index or themselves.
  • only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.

Examples

>>> v1 = hs.model.components.Voigt()
>>> v2 = hs.model.components.Voigt()
>>> m.extend([v1,v2])
>>> m.set_parameters_value('area', 5)
>>> m.set_parameters_value('area', 5, component_list=[v1])
>>> m.set_parameters_value('area', 5, component_list=[v1],
                           only_current=True)
set_signal_range(*args, **kwargs)

Use only the selected spectral range defined in its own units in the fitting routine.

Parameters:
  • E1 (None or float) –
  • E2 (None or float) –

Notes

To use the full energy range call the function without arguments.

signal
store_current_values()

Store the parameters of the current coordinates into the parameters array.

If the parameters array has not being defined yet it creates it filling it with the current parameters.

suspend_update()

Prevents plot from updating until resume_update() is called

update_plot(*args, **kwargs)

Update model plot.

The updating can be suspended using suspend_update.

class hyperspy.model.ModelComponents(model)

Bases: object

Container for model components.

Useful to provide tab completion when running in IPython.

hyperspy.signal module

class hyperspy.signal.BaseSignal(data, **kwds)

Bases: hyperspy.learn.mva.MVA, hyperspy.signal.MVATools

add_marker(marker, plot_on_signal=True, plot_marker=True)

Add a marker to the signal or navigator plot.

Plot the signal, if not yet plotted

Parameters:
  • marker (hyperspy.drawing._markers) – the marker to add. see plot.markers
  • plot_on_signal (bool) – If True, add the marker to the signal If False, add the marker to the navigator
  • plot_marker (bool) – if True, plot the marker

Examples

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

Convert signal to image.

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

Parameters:image_axes (tuple of {int, complex, str}) – 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.

Examples

>>> s = hs.signals.Signal1D(np.ones((2,3,4,5)))
>>> s
<Spectrum, title: , dimensions: (4, 3, 2, 5)>
>>> s.as_image((0,1))
<Image, title: , dimensions: (5, 2, 4, 3)>
>>> s.to_image((1,2))
<Image, title: , dimensions: (4, 5, 3, 2)>
Raises:DataDimensionError : when data.ndim < 2
as_signal1D(spectral_axis)

Return the Signal as a one-dimensional Signal1D.

The chosen spectral axis is moved to the last index in the array and the data is made contiguous for effecient iteration over spectra.

Parameters:spectral_axis ({int, complex, str}) – Select the spectral axis to-be using its index or name.

Examples

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

Convert signal to image.

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

Parameters:image_axes (tuple of {int, complex, str}) – 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.

Examples

>>> s = hs.signals.Signal1D(np.ones((2,3,4,5)))
>>> s
<Spectrum, title: , dimensions: (4, 3, 2, 5)>
>>> s.as_image((0,1))
<Image, title: , dimensions: (5, 2, 4, 3)>
>>> s.to_image((1,2))
<Image, title: , dimensions: (4, 5, 3, 2)>
Raises:DataDimensionError : when data.ndim < 2
as_spectrum(spectral_axis)

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 effecient iteration over spectra.

Parameters:spectral_axis ({int, complex, str}) – Select the spectral axis to-be using its index or name.

Examples

>>> img = hs.signals.Signal2D(np.ones((3,4,5,6)))
>>> img
<Image, title: , dimensions: (4, 3, 6, 5)>
>>> img.to_spectrum(-1+1j)
<Spectrum, title: , dimensions: (6, 5, 4, 3)>
>>> img.to_spectrum(0)
<Spectrum, title: , dimensions: (6, 5, 3, 4)>
change_dtype(dtype)

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 record_by must be “spectrum”, signal_dimension must be 3(4) for rgb(rgba) dtypes and the dtype must be uint8(uint16) for rgbx8(rgbx16). After conversion record_by becomes image and the spectra dimension is removed. The dtype of images of dtype rgbx8(rgbx16) can only be changed to uint8(uint16) and the record_by becomes “spectrum”.

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()
create_model()

Create a model for the current signal

Returns:
Return type:A Model class
crop(axis, start=None, end=None)

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.
deepcopy()
derivative(axis, order=1)

Numerical derivative along the given axis.

Currently only the first order finite difference method is implemented.

Parameters:
  • axis ({int | string}) – The axis can be 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.)
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)

Returns a signal with the n-th order discrete difference along given axis. :param axis: The axis can be specified using the index of the axis in

axes_manager or the axis name.
Parameters:order (the order of the derivative) –

See also

mean(), sum()

Examples

>>> import numpy as np
>>> s = Signal(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.
fold(*args, **kwargs)

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
<Image, title: , dimensions: (3, 2, 32, 32)>
>>> im.axes_manager.indices = 2,1
>>> im.get_current_signal()
<Image, title:  (2, 1), dimensions: (32, 32)>
get_dimensions_from_data(*args, **kwargs)

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, **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())
  • **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 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()
indexmax(axis)

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

Parameters:axis ({int | string}) – The axis can be specified using the index of the axis in axes_manager or the axis name.
Returns:s – The data dtype is always int.
Return type:Signal

See also

sum, mean, min

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.indexmax(-1).data.shape
(64,64)
integrate1D(axis)

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 | string}) – The axis can be specified using the index of the axis in axes_manager or the axis name.
Returns:s
Return type:Signal

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.var(-1).data.shape
(64,64)
integrate_simpson(axis)

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

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

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.var(-1).data.shape
(64,64)
is_rgb
is_rgba
is_rgbx
map(function, show_progressbar=None, **kwargs)

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

The function must operate on numpy arrays and the output must have the same dimensions as the input. The function is applied to the data at each coordinate and the result is stored in the current signal i.e. this method operates in-place. 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.

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 is set in preferences.
  • arguments (keyword) – All extra keyword arguments are passed to the

Notes

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 sigmal parameter is variable.

>>> im = hs.signals.Signal2D(np.random.random((10, 64, 64)))
>>> sigmas = hs.signals.Signal(np.linspace(2,5,10))
>>> sigmas.axes_manager.set_signal_dimension(0)
>>> im.map(scipy.ndimage.gaussian_filter, sigma=sigmas)
max(axis, return_signal=False)

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

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

See also

sum(), mean(), min()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.max(-1).data.shape
(64,64)
mean(axis)

Returns a signal with the average of the signal along an axis.

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

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.mean(-1).data.shape
(64,64)
min(axis)

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

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

See also

sum(), mean(), max(), std(), var()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.min(-1).data.shape
(64,64)
plot(navigator='auto', axes_manager=None, **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.
  • **kwargs (optional) – Any extra keyword arguments are passed to the signal plot.
print_summary_statistics(formatter='%.3f')

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

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

Parameters:formatter (bool) – Number formatter.

See also

get_histogram()

rebin(new_shape)

Returns the object with the data rebinned.

Parameters:new_shape (tuple of ints) – The new shape elements must be divisors of the original shape elements.
Returns:s
Return type:Signal subclass
Raises:ValueError – When there is a mismatch between the number of elements in the signal shape and new_shape or new_shape elements are not divisors of the original signal shape.

Examples

>>> import hyperspy.api as hs
>>> s = hs.signals.Signal1D(np.zeros((10, 100)))
>>> s
<Spectrum, title: , dimensions: (10|100)>
>>> s.rebin((5, 100))
<Spectrum, title: , dimensions: (5|100)>
I
rollaxis(axis, to_axis)

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

Parameters:
  • axis ({int, str}) – The axis to roll backwards. The positions of the other axes do not change relative to one another.
  • to_axis ({int, str}) – The axis is rolled until it lies before this other axis.
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
<Spectrum, title: , dimensions: (3, 4, 5, 6)>
>>> s.rollaxis(3, 1)
<Spectrum, title: , dimensions: (3, 4, 5, 6)>
>>> s.rollaxis(2,0)
<Spectrum, 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.:
  • hdf5 for HDF5
  • rpl for Ripple (useful to export to Digital Micrograph)
  • msa for EMSA/MSA single spectrum 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.

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, 'hdf5', 'rpl', 'msa',common image extensions e.g.) – ‘tiff’, ‘png’} The extension of the file that defines the file format. If None, the extension is taken from the first not None in the following list: i) the filename ii) tmp_parameters.extension iii) preferences.General.default_file_format in this order.
set_signal_origin(origin)

Set the origin of the signal and change the current class accordingly if pertinent.

The signal_origin attribute specifies if the data was obtained through experiment or simulation. There are some methods that are only available for experimental or simulated data, so setting this parameter can enable/disable features.

Parameters:origin ({'experiment', 'simulation', None, ""}) – None an the empty string mean that the signal origin is uknown.
Raises:ValueError if origin is not ‘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 containts 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 splitted. The splitting is homegenous. 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 supress from each sub_spectra.
  • step_sizes ({'auto' | list of ints | int}) – Size of the splitted parts. If ‘auto’, the step_sizes equals one. If int, the splitting is homogenous.

Examples

>>> s = hs.signals.Signal1D(random.random([4,3,2]))
>>> s
    <Spectrum, title: , dimensions: (3, 4|2)>
>>> s.split()
    [<Spectrum, title: , dimensions: (3 |2)>,
    <Spectrum, title: , dimensions: (3 |2)>,
    <Spectrum, title: , dimensions: (3 |2)>,
    <Spectrum, title: , dimensions: (3 |2)>]
>>> s.split(step_sizes=2)
    [<Spectrum, title: , dimensions: (3, 2|2)>,
    <Spectrum, title: , dimensions: (3, 2|2)>]
>>> s.split(step_sizes=[1,2])
    [<Spectrum, title: , dimensions: (3, 1|2)>,
    <Spectrum, title: , dimensions: (3, 2|2)>]
Returns:
Return type:list of the splitted signals
squeeze()

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

std(axis)

Returns a signal with the standard deviation of the signal along an axis.

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

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.std(-1).data.shape
(64,64)
sum(axis)

Sum the data over the given axis.

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

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.sum(-1).data.shape
(64,64)
# If we just want to plot the result of the operation
s.sum(-1, True).plot()
swap_axes(axis1, axis2)

Swaps the axes.

Parameters:axis2 (axis1,) – Specify the data axes in which to perform the operation. The axis can be specified using the index of the axis in axes_manager or the axis name.
Returns:s
Return type:a copy of the object with the axes swapped.
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
static unfold_if_multidim()

Unfold the datacube if it is >2D

Deprecated method, please use unfold.

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 = Signal(np.random.random((64,64,1024)))
>>> with s.unfolded():
        # Do whatever needs doing while unfolded here
        pass
valuemax(axis)

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

Parameters:axis ({int | string}) – The axis can be specified using the index of the axis in axes_manager or the axis name.
Returns:s – The data dtype is always int.
Return type:Signal

See also

sum, mean, min

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.valuemax(-1).data.shape
(64,64)
var(axis)

Returns a signal with the variances of the signal along an axis.

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

See also

sum_in_mask(), mean()

Examples

>>> import numpy as np
>>> s = Signal(np.random.random((64,64,1024)))
>>> s.data.shape
(64,64,1024)
>>> s.var(-1).data.shape
(64,64)
class hyperspy.signal.MVATools

Bases: object

export_bss_results(comp_ids=None, folder=None, calibrate=True, multiple_files=None, save_figures=False, factor_prefix='bss_factor', factor_format=None, loading_prefix='bss_loading', loading_format=None, 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. 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 factor is saved.
    • For multidimensional formats (rpl, hdf5), arrays are
    saved
    in single files. All factors are contained in the one file.
    • For spectral formats (msa), each factor is saved to a separate file.
  • 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.
  • 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_bss_factors(), get_bss_loadings.()

export_decomposition_results(comp_ids=None, folder=None, calibrate=True, factor_prefix='factor', factor_format=None, loading_prefix='loading', loading_format=None, comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, same_window=False, multiple_files=None, 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.
  • 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. 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, hdf5), 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=None, comp_label='BSS factor', per_row=3)

Plot factors from blind source separation results.

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.
  • comp_label (string, the label that is either the plot title) –
  • plotting in ((if) – 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.

See also

plot_bss_loadings(), plot_bss_results.()

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

Plot loadings from ICA

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.
  • 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). In this case, each loading line can be toggled on and off by clicking on the legended line.
  • 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.

See also

plot_bss_factors(), plot_bss_results.()

plot_bss_results(factors_navigator='auto', loadings_navigator='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 syncronize between the two.

Parameters:
  • loadings_navigator (factor_navigator,) –
  • Signal} – 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=None, comp_label='Decomposition factor', per_row=3)

Plot factors from a decomposition.

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.
  • comp_label (string, the label that is either the plot title) –
  • plotting in ((if) – 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.

See also

plot_decomposition_loadings(), plot_decomposition_results.()

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

Plot loadings from PCA.

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.
  • 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). In this case, each loading line can be toggled on and off by clicking on the legended line.
  • 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.

See also

plot_decomposition_factors(), plot_decomposition_results.()

plot_decomposition_results(factors_navigator='auto', loadings_navigator='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 syncronize between the two.

Parameters:
  • loadings_navigator (factor_navigator,) –
  • Signal} – 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.SpecialSlicers(signal, isNavigation)

Bases: object

hyperspy.signals module

The Signal class and its specilized subclasses:

Signal
For generic data with arbitrary signal_dimension. All other signal classes inherit from this one. It should only be used with none of the others is appropriated.
Signal1D
For generic data with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is unbinned by default.
Signal2D
For generic data with signal_dimension equal 2, i.e. image data of n-dimensions. The signal is unbinned by default.
Spectrum
Deprecated in favour of Signal1D from version 1.0.0
Image
Deprecated in favour of Signal2D from version 1.0.0
Simulation
For generic simulated data with arbitrary signal_dimension. All other simulation signal classes inherit from this one. It should only be used with none of the others is appropriated.
EELSSpectrum
For electron energy-loss data with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is binned by default.
EELSSpectrumSimulation, SpectrumSimulation, ImageSimulation
Simulation versions of EELSSpectrum, Spectrum and Image.
EDSTEMSpectrum
For electron energy-dispersive X-rays data acquired in a transmission electron microscopy with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is binned by default.
EDSSEMSpectrum
For electron energy-dispersive X-rays data acquired in a scanning electron microscopy with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is binned by default.
DielectricFunction
For dielectric function data with signal_dimension equal 1. The signal is unbinned by default.
class hyperspy.signals.Image(*args, **kwargs)

Bases: hyperspy._signals.signal2d.Signal2D, hyperspy._signals.signal1d.Signal1DTools

to_spectrum()

Returns the image as a spectrum.

See also

as_spectrum()
a method for the same purpose with more options.
signals.Spectrum.to_image()
performs the inverse operation on spectra.
Raises:DataDimensionError: when data.ndim < 2
class hyperspy.signals.Signal(*args, **kwargs)

Bases: hyperspy.signal.BaseSignal, hyperspy._signals.signal1d.Signal1DTools, hyperspy._signals.signal2d.Signal2DTools

class hyperspy.signals.Spectrum(*args, **kwargs)

Bases: hyperspy._signals.signal1d.Signal1D, hyperspy._signals.signal2d.Signal2DTools

to_image()

Returns the spectrum as an image.

See also

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

Module contents

HyperSpy: a multi-dimensional data analysis package for Python

Documentation is available in the docstrings and online at http://hyperspy.org/hyperspy-doc/current/index.html.

All public packages, functions and classes are in api. All other packages and modules are for internal consumption and should not be needed for data analysis.

When starting HyperSpy using the hyperspy script (e.g. by executing hyperspy in a console, using the context menu entries or using the links in the Start Menu, the api package is imported in the user namespace as hs, i.e. by executing the following:

>>> import hyperspy.api as hs

(Note that code snippets are indicated by three greater-than signs)

We recommend to import the HyperSpy API as above also when doing it manually. The docstring examples assume that hyperspy has been imported as hs, numpy as np and matplotlib.pyplot as plt.

More details in the api docstring.