hyperspy package¶
Subpackages¶
- hyperspy._components package
- Submodules
- hyperspy._components.arctan module
- hyperspy._components.bleasdale module
- hyperspy._components.eels_cl_edge module
- hyperspy._components.eels_double_power_law module
- hyperspy._components.eels_vignetting module
- hyperspy._components.error_function module
- hyperspy._components.exponential module
- hyperspy._components.expression module
- hyperspy._components.gaussian module
- hyperspy._components.gaussian2d module
- hyperspy._components.gaussianhf module
- hyperspy._components.heaviside module
- hyperspy._components.logistic module
- hyperspy._components.lorentzian module
- hyperspy._components.offset module
- hyperspy._components.pes_core_line_shape module
- hyperspy._components.pes_see module
- hyperspy._components.polynomial module
- hyperspy._components.power_law module
- hyperspy._components.rc module
- hyperspy._components.scalable_fixed_pattern module
- hyperspy._components.voigt module
- hyperspy._components.volume_plasmon_drude module
- Module contents
- hyperspy._signals package
- Submodules
- hyperspy._signals.common_signal1d module
- hyperspy._signals.common_signal2d module
- hyperspy._signals.complex_signal module
- hyperspy._signals.complex_signal1d module
- hyperspy._signals.complex_signal2d module
- hyperspy._signals.dielectric_function module
- hyperspy._signals.eds module
- hyperspy._signals.eds_sem module
- hyperspy._signals.eds_tem module
- hyperspy._signals.eels module
- hyperspy._signals.hologram_image module
- hyperspy._signals.lazy module
- hyperspy._signals.signal1d module
- hyperspy._signals.signal2d module
- Module contents
- hyperspy.datasets package
- hyperspy.docstrings package
- hyperspy.drawing package
- Subpackages
- hyperspy.drawing._markers package
- Submodules
- hyperspy.drawing._markers.horizontal_line module
- hyperspy.drawing._markers.horizontal_line_segment module
- hyperspy.drawing._markers.line_segment module
- hyperspy.drawing._markers.point module
- hyperspy.drawing._markers.rectangle module
- hyperspy.drawing._markers.text module
- hyperspy.drawing._markers.vertical_line module
- hyperspy.drawing._markers.vertical_line_segment module
- Module contents
- hyperspy.drawing._widgets package
- Submodules
- hyperspy.drawing._widgets.circle module
- hyperspy.drawing._widgets.horizontal_line module
- hyperspy.drawing._widgets.label module
- hyperspy.drawing._widgets.line2d module
- hyperspy.drawing._widgets.range module
- hyperspy.drawing._widgets.rectangles module
- hyperspy.drawing._widgets.scalebar module
- hyperspy.drawing._widgets.vertical_line module
- Module contents
- hyperspy.drawing._markers package
- Submodules
- hyperspy.drawing.figure module
- hyperspy.drawing.image module
- hyperspy.drawing.marker module
- hyperspy.drawing.mpl_he module
- hyperspy.drawing.mpl_hie module
- hyperspy.drawing.mpl_hse module
- hyperspy.drawing.signal module
- hyperspy.drawing.signal1d module
- hyperspy.drawing.tiles module
- hyperspy.drawing.utils module
- hyperspy.drawing.widget module
- hyperspy.drawing.widgets module
- Module contents
- Subpackages
- hyperspy.external package
- hyperspy.io_plugins package
- Submodules
- hyperspy.io_plugins.bcf module
- hyperspy.io_plugins.blockfile module
- hyperspy.io_plugins.dens module
- hyperspy.io_plugins.digital_micrograph module
- hyperspy.io_plugins.edax module
- hyperspy.io_plugins.emd module
- hyperspy.io_plugins.fei module
- hyperspy.io_plugins.hspy module
- hyperspy.io_plugins.image module
- hyperspy.io_plugins.mrc module
- hyperspy.io_plugins.msa module
- hyperspy.io_plugins.netcdf module
- hyperspy.io_plugins.protochips module
- hyperspy.io_plugins.ripple module
- hyperspy.io_plugins.semper_unf module
- hyperspy.io_plugins.tiff module
- hyperspy.io_plugins.unbcf_fast module
- Module contents
- hyperspy.learn package
- hyperspy.misc package
- Subpackages
- Submodules
- hyperspy.misc.array_tools module
- hyperspy.misc.config_dir module
- hyperspy.misc.date_time_tools module
- hyperspy.misc.elements module
- hyperspy.misc.example_signals_loading module
- hyperspy.misc.export_dictionary module
- hyperspy.misc.ipython_tools module
- hyperspy.misc.material module
- hyperspy.misc.math_tools module
- hyperspy.misc.physical_constants module
- hyperspy.misc.physics_tools module
- hyperspy.misc.rgb_tools module
- hyperspy.misc.signal_tools module
- hyperspy.misc.slicing module
- hyperspy.misc.test_utils module
- hyperspy.misc.tv_denoise module
- hyperspy.misc.utils module
- Module contents
- hyperspy.models package
- hyperspy.samfire_utils package
- Subpackages
- Submodules
- hyperspy.samfire_utils.fit_tests module
- hyperspy.samfire_utils.global_strategies module
- hyperspy.samfire_utils.local_strategies module
- hyperspy.samfire_utils.samfire_kernel module
- hyperspy.samfire_utils.samfire_pool module
- hyperspy.samfire_utils.samfire_worker module
- hyperspy.samfire_utils.strategy module
- Module contents
- hyperspy.tests package
- Subpackages
- hyperspy.tests.axes package
- hyperspy.tests.component package
- hyperspy.tests.datasets package
- hyperspy.tests.drawing package
- Submodules
- hyperspy.tests.drawing.test_figure_title module
- hyperspy.tests.drawing.test_mpl_testing_setup module
- hyperspy.tests.drawing.test_plot_markers module
- hyperspy.tests.drawing.test_plot_model module
- hyperspy.tests.drawing.test_plot_mva module
- hyperspy.tests.drawing.test_plot_signal module
- hyperspy.tests.drawing.test_plot_signal1d module
- hyperspy.tests.drawing.test_plot_signal2d module
- hyperspy.tests.drawing.test_plot_widgets module
- hyperspy.tests.drawing.test_utils module
- Module contents
- hyperspy.tests.io package
- Submodules
- hyperspy.tests.io.generate_dm_testing_files module
- hyperspy.tests.io.test_bcf module
- hyperspy.tests.io.test_blockfile module
- hyperspy.tests.io.test_dens module
- hyperspy.tests.io.test_dm3 module
- hyperspy.tests.io.test_dm_stackbuilder_plugin module
- hyperspy.tests.io.test_edax module
- hyperspy.tests.io.test_emd module
- hyperspy.tests.io.test_fei module
- hyperspy.tests.io.test_hdf5 module
- hyperspy.tests.io.test_io module
- hyperspy.tests.io.test_msa module
- hyperspy.tests.io.test_protochips module
- hyperspy.tests.io.test_ripple module
- hyperspy.tests.io.test_semper_unf module
- hyperspy.tests.io.test_tiff module
- Module contents
- hyperspy.tests.misc package
- Submodules
- hyperspy.tests.misc.test_arraytools module
- hyperspy.tests.misc.test_date_time_tools module
- hyperspy.tests.misc.test_image_tools module
- hyperspy.tests.misc.test_math_tools module
- hyperspy.tests.misc.test_rgbtools module
- hyperspy.tests.misc.test_test_utils module
- hyperspy.tests.misc.test_utils module
- Module contents
- hyperspy.tests.model package
- Submodules
- hyperspy.tests.model.test_chi_squared module
- hyperspy.tests.model.test_component module
- hyperspy.tests.model.test_components module
- hyperspy.tests.model.test_components2D module
- hyperspy.tests.model.test_edsmodel module
- hyperspy.tests.model.test_eelsmodel module
- hyperspy.tests.model.test_fancy_indexing module
- hyperspy.tests.model.test_fit_component module
- hyperspy.tests.model.test_model module
- hyperspy.tests.model.test_model_as_dictionary module
- hyperspy.tests.model.test_model_selection_criteria module
- hyperspy.tests.model.test_model_storing module
- hyperspy.tests.model.test_parameter module
- hyperspy.tests.model.test_set_parameter_state module
- hyperspy.tests.model.test_set_parameter_value module
- Module contents
- hyperspy.tests.mva package
- hyperspy.tests.samfire package
- Submodules
- hyperspy.tests.samfire.test_goodness_of_fit_tests module
- hyperspy.tests.samfire.test_histogram_segmenter module
- hyperspy.tests.samfire.test_red_chisq_weight module
- hyperspy.tests.samfire.test_samfire module
- hyperspy.tests.samfire.test_strategy module
- hyperspy.tests.samfire.test_strategy_list module
- hyperspy.tests.samfire.test_utils module
- Module contents
- hyperspy.tests.signal package
- Submodules
- hyperspy.tests.signal.test_1D_tools module
- hyperspy.tests.signal.test_2D_tools module
- hyperspy.tests.signal.test_assign_subclass module
- hyperspy.tests.signal.test_binned module
- hyperspy.tests.signal.test_complex_signal module
- hyperspy.tests.signal.test_complex_signal2d module
- hyperspy.tests.signal.test_eds_sem module
- hyperspy.tests.signal.test_eds_tem module
- hyperspy.tests.signal.test_eels module
- hyperspy.tests.signal.test_fancy_indexing module
- hyperspy.tests.signal.test_find_peaks1D_ohaver module
- hyperspy.tests.signal.test_folding module
- hyperspy.tests.signal.test_hologram_image module
- hyperspy.tests.signal.test_image module
- hyperspy.tests.signal.test_inheritance module
- hyperspy.tests.signal.test_kramers_kronig_transform module
- hyperspy.tests.signal.test_lazy module
- hyperspy.tests.signal.test_map_method module
- hyperspy.tests.signal.test_remove_background module
- hyperspy.tests.signal.test_rgb module
- hyperspy.tests.signal.test_signal_operators module
- hyperspy.tests.signal.test_signal_subclass_conversion module
- hyperspy.tests.signal.test_spectrum module
- hyperspy.tests.signal.test_tools module
- Module contents
- hyperspy.tests.utils package
- Submodules
- hyperspy.tests.test_dictionary_tree_browser module
- hyperspy.tests.test_events module
- hyperspy.tests.test_interactive module
- Module contents
- Subpackages
- hyperspy.utils package
Submodules¶
hyperspy.Release module¶
hyperspy._lazy_signals 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 BaseSignal 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.
- interactive
- Define operations that are automatically recomputed on event changes.
- set_log_level
- Convenience function to set HyperSpy’s the log level.
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.
roi
- Region of interests (ROIs) that operate on BaseSignal instances and include widgets for interactive operation.
samfire
- SAMFire utilities (strategies, Pool, fit convergence tests)
For more details see their doctrings.
hyperspy.api_nogui 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 BaseSignal 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.
- interactive
- Define operations that are automatically recomputed on event changes.
- set_log_level
- Convenience function to set HyperSpy’s the log level.
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.
roi
- Region of interests (ROIs) that operate on BaseSignal instances and include widgets for interactive operation.
samfire
- SAMFire utilities (strategies, Pool, fit convergence tests)
For more details see their doctrings.
-
hyperspy.api_nogui.
get_configuration_directory_path
()¶
hyperspy.axes module¶
-
class
hyperspy.axes.
AxesManager
(axes_list)¶ Bases:
traits.has_traits.HasTraits
Contains and manages the data axes.
It supports indexing, slicing, subscripting 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
Create a spectrum with random data
>>> s = hs.signals.Signal1D(np.random.random((2,3,4,5))) >>> s.axes_manager <Axes manager, axes: (4, 3, 2|5)> Name | size | index | offset | scale | units ================ | ====== | ====== | ======= | ======= | ====== <undefined> | 4 | 0 | 0 | 1 | <undefined> <undefined> | 3 | 0 | 0 | 1 | <undefined> <undefined> | 2 | 0 | 0 | 1 | <undefined> ---------------- | ------ | ------ | ------- | ------- | ------ <undefined> | 5 | | 0 | 1 | <undefined> >>> s.axes_manager[0] <Unnamed 0th axis, size: 4, index: 0> >>> s.axes_manager[3j] <Unnamed 2nd axis, size: 2, index: 0> >>> s.axes_manager[1j] <Unnamed 0th axis, size: 4, index: 0> >>> s.axes_manager[2j] <Unnamed 3rd 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
-
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
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
Navigation sliders to control the index of the navigation axes.
Parameters: - title (str) –
- %s –
- %s –
-
indices
Get the index of the navigation axes.
Returns: Return type: list
-
remove
(axes)¶ Remove one or more axes
-
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_extent
¶
-
signal_indices_in_array
¶
-
update_axes_attributes_from
(axes, attributes=['scale', 'offset', 'units'])¶ Update the axes attributes to match those given.
The axes are matched by their index in the array. The purpose of this method is to update multiple axes triggering any_axis_changed only once.
Parameters: - axes (iterable of DataAxis instances.) – The axes to copy the attributes from.
- attributes (iterable of strings.) – The attributes to copy.
-
-
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)¶
-
copy
()¶
-
get_axis_dictionary
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
index2value
(index)¶
-
index_in_array
¶
-
index_in_axes_manager
¶
-
update_axis
()¶
-
update_from
(axis, attributes=['scale', 'offset', 'units'])¶ Copy values of specified axes fields from the passed AxesManager.
Parameters: - axis (DataAxis) – The DataAxis instance to use as a source for values.
- attributes (iterable container of strings.) – The name of the attribute to update. If the attribute does not exist in either of the AxesManagers, an AttributeError will be raised.
Returns: Return type: A boolean indicating whether any changes were made.
-
update_index_bounds
()¶
-
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
¶
-
as_dictionary
(fullcopy=True)¶ Returns component as a dictionary For more information on method and conventions, see
hyperspy.misc.export_dictionary.export_to_dictionary()
:param fullcopy: Copies of objects are stored, not references. If any found,functions will be pickled and signals converted to dictionariesReturns: dic – A dictionary, containing at least the following fields: parameters : list a list of dictionaries of the parameters, one per- _whitelist : dictionary
- a dictionary with keys used as references saved attributes, for
more information, see
hyperspy.misc.export_dictionary.export_to_dictionary()
- any field from _whitelist.keys() *
Return type: dictionary
-
export
(folder=None, format='hspy', 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 extension of the file format, default “hspy”.
- 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)¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
init_parameters
(parameter_name_list)¶
-
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.components1D.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.components1D.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)¶ Validates that a specified value is valid for this trait.
Note: The ‘fast validator’ version performs this check in C.
-
-
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_expr
¶ str – Expression of the
twin_function
that enables setting a functional relationship between the parameter and its twin. Iftwin
is notNone
, the parameter value is calculated as the output of calling the twin function with the value of the twin parameter. The string is parsed using sympy, so permitted values are any valid sympy expressions of one variable. If the function is invertible the twin inverse function is set automatically.
-
twin_inverse_function
¶ str – Expression of the
twin_inverse_function
that enables setting the value of the twin parameter. Iftwin
is notNone
, its value is set to the output of calling the twin inverse function with the value provided. The string is parsed using sympy, so permitted values are any valid sympy expressions of one variable.
-
twin_function
¶ function – Setting this attribute manually is deprecated in HyperSpy newer than 1.1.2. It will become private in HyperSpy 2.0. Please use ``twin_function_expr`` instead.
-
twin_inverse_function
function – Setting this attribute manually is deprecated in HyperSpy newer than 1.1.2. It will become private in HyperSpy 2.0. Please use ``twin_inverse_function_expr`` instead.
-
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_dictionary
(fullcopy=True)¶ Returns parameter as a dictionary, saving all attributes from self._whitelist.keys() For more information see
hyperspy.misc.export_dictionary.export_to_dictionary()
Parameters: fullcopy (Bool (optional, False)) – Copies of objects are stored, not references. If any found, functions will be pickled and signals converted to dictionaries Returns: dic – - _id_name : string
- _id_name of the original parameter, used to create the dictionary. Has to match with the self._id_name
- _twins : list
- a list of ids of the twins of the parameter
- _whitelist : dictionary
- a dictionary, which keys are used as keywords to match with the
parameter attributes. For more information see
hyperspy.misc.export_dictionary.export_to_dictionary()
- any field from _whitelist.keys() *
Return type: dictionary with the following keys:
-
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. See also
-
default_traits_view
()¶ Returns the name of the default traits view for the object’s class.
-
export
(folder=None, name=None, format='hspy', 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
- format (str) – The extension of any file format supported by HyperSpy, default hspy
- folder (str or None) –
-
ext_bounded
-
ext_force_positive
-
fetch
()¶ Fetch the stored value and std attributes.
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
plot
(**kwargs) Plot parameter signal.
Parameters: **kwargs – Any extra keyword arguments are passed to the signal plot. Example
>>> parameter.plot()
Set the minimum and maximum displayed values
>>> parameter.plot(vmin=0, vmax=1)
-
store_current_value_in_array
()¶ Store the value and std attributes.
See also
-
twin
-
twin_function
= None
-
twin_function_expr
-
twin_inverse_function
-
twin_inverse_function_expr
¶
-
hyperspy.components1d module¶
Components that can be used to define a 1D 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.
Writing a new template is really easy, just edit _template.py and maybe take a look to the other components.
For more details see each component docstring.¶
Arctan Arctan function component.. Bleasdale Bleasdale function component… 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.. GaussianHF Normalized gaussian function component, wit.. 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 .. Vignetting .. Voigt Voigt profile component with support for sh.. VolumePlasmonDrude Drude volume plasmon energy loss function c..
hyperspy.components2d module¶
Components that can be used to define a 2D model for e.g. 2D model fitting.
Writing a new template is really easy, just edit _template.py and maybe take a look to the other components.
For more details see each component docstring.¶
Expression Create a component from a string expression.. Gaussian2D Normalized 2D elliptical gaussian function ..
hyperspy.conftest module¶
hyperspy.decorators module¶
-
hyperspy.decorators.
interactive_range_selector
(f)¶
-
hyperspy.decorators.
lazify
(func, **kwargs)¶
-
hyperspy.decorators.
lazifyTestClass
(*args, **kwargs)¶
-
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.
GUIs
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
GeneralConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
Preferences
¶ Bases:
traits.has_traits.HasTraits
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
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.events module¶
-
class
hyperspy.events.
Event
(doc='', arguments=None)¶ Bases:
object
-
arguments
¶
-
connect
(function, kwargs='all')¶ Connects a function to the event. Arguments: ———- function : callable
The function to call when the event triggers.- kwargs : {tuple or list, dictionary, ‘all’, ‘auto’}, default “all”
- If “all”, all the trigger keyword arguments are passed to the function. If a list or tuple of strings, only those keyword arguments that are in the tuple or list are passed. If empty, no keyword argument is passed. If dictionary, the keyword arguments of trigger are mapped as indicated in the dictionary. For example, {“a” : “b”} maps the trigger argument “a” to the function argument “b”.
See also
-
connected
¶ Connected functions.
-
disconnect
(function)¶ Disconnects a function from the event. The passed function will be disconnected irregardless of which ‘nargs’ argument was passed to connect().
If you only need to temporarily prevent a function from being called, single callback suppression is supported by the suppress_callback context manager. :param function: :type function: function :param return_connection_kwargs: If True, returns the kwargs that would reconnect the function as
it was.See also
-
suppress
()¶ Use this function with a ‘with’ statement to temporarily suppress all events in the container. When the ‘with’ lock completes, the old suppression values will be restored.
>>> with obj.events.myevent.suppress(): ... # These would normally both trigger myevent: ... obj.val_a = a ... obj.val_b = b
Trigger manually once: >>> obj.events.myevent.trigger()
See also
-
suppress_callback
(function)¶ Use this function with a ‘with’ statement to temporarily suppress a single callback from being called. All other connected callbacks will trigger. When the ‘with’ lock completes, the old suppression value will be restored.
>>> with obj.events.myevent.suppress_callback(f): ... # Events will trigger as normal, but `f` will not be called ... obj.val_a = a ... obj.val_b = b >>> # Here, `f` will be called as before: >>> obj.events.myevent.trigger()
See also
-
trigger
(**kwargs)¶ Triggers the event. If the event is suppressed, this does nothing. Otherwise it calls all the connected functions with the arguments as specified when connected.
See also
-
-
class
hyperspy.events.
EventSuppressor
(*to_suppress)¶ Bases:
object
Object to enforce a variety of suppression types simultaneously
Targets to be suppressed can be added by the function add(), or given in the constructor. Valid targets are:
- Event: The entire Event will be suppressed
- Events: All events in th container will be suppressed
- (Event, callback): The callback will be suppressed in Event
- (Events, callback): The callback will be suppressed in each event in
- Events where it is connected.
- Any iterable collection of the above target types
>>> es = EventSuppressor((event1, callback1), (event1, callback2)) >>> es.add(event2, callback2) >>> es.add(event3) >>> es.add(events_container1) >>> es.add(events_container2, callback1) >>> es.add(event4, (events_container3, callback2)) >>> >>> with es.suppress(): ... do_something()
-
add
(*to_suppress)¶ Add one or more targets to be suppressed
- Valid targets are:
- Event: The entire Event will be suppressed
- Events: All events in the container will be suppressed
- (Event, callback): The callback will be suppressed in Event
- (Events, callback): The callback will be suppressed in each event in Events where it is connected.
- Any iterable collection of the above target types
-
suppress
()¶ Use this function with a ‘with’ statement to temporarily suppress all events added. When the ‘with’ lock completes, the old suppression values will be restored.
-
class
hyperspy.events.
Events
¶ Bases:
object
Events container.
All available events are attributes of this class.
-
suppress
()¶ Use this function with a ‘with’ statement to temporarily suppress all callbacks of all events in the container. When the ‘with’ lock completes, the old suppression values will be restored.
>>> with obj.events.suppress(): ... # Any events triggered by assignments are prevented: ... obj.val_a = a ... obj.val_b = b >>> # Trigger one event instead: >>> obj.events.values_changed.trigger()
See also
-
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
Bases:
Exception
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.
VisibleDeprecationWarning
¶ Bases:
UserWarning
Visible deprecation warning. By default, python will not show deprecation warnings, so this class provides a visible one.
-
exception
hyperspy.exceptions.
WrongObjectError
(is_str, must_be_str)¶ Bases:
Exception
hyperspy.interactive module¶
-
class
hyperspy.interactive.
Interactive
(f, event='auto', recompute_out_event='auto', *args, **kwargs)¶ Bases:
object
Chainable operations on Signals that update on events.
-
recompute_out
()¶
-
update
()¶
-
-
hyperspy.interactive.
interactive
(f, event='auto', recompute_out_event='auto', *args, **kwargs)¶ Update operation result when a given event is triggered.
Parameters: - f (function or method) – A function that returns an object and that optionally can place the result in an object given through the out keyword.
- event ({Event, "auto", None, iterable of events}) – Update the result of the operation when the event is triggered. If “auto” and f is a method of a Signal class instance its data_changed event is selected if the function takes an out argument. If None, update is not connected to any event. The default is “auto”. It is also possible to pass an iterable of events, in which case all the events are connected.
- recompute_out_event ({Event, "auto", None, iterable of events}) – Optional argument. If supplied, this event causes a full recomputation of a new object. Both the data and axes of the new object are then copied over to the existing out object. Only useful for Signal or other objects that have an attribute axes_manager. If “auto” and f is a method of a Signal class instance its AxesManager any_axis_chaged event is selected. Otherwise the Signal data_changed event is selected. If None, recompute_out is not connected to any event. The default is “auto”. It is also possible to pass an iterable of events, in which case all the events are connected.
hyperspy.io module¶
-
hyperspy.io.
assign_signal_subclass
(dtype, signal_dimension, signal_type='', lazy=False)¶ Given record_by and signal_type return the matching Signal subclass.
Parameters: - dtype (
dtype
) – - signal_dimension (int) –
- signal_type ({"EELS", "EDS", "EDS_SEM", "EDS_TEM", "DielectricFunction", "", str}) –
- lazy (bool) –
Returns: Return type: Signal or subclass
- dtype (
-
hyperspy.io.
dict2signal
(signal_dict, lazy=False)¶ 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, signal_type=None, stack=False, stack_axis=None, new_axis_name='stack_element', lazy=False, **kwds)¶ Load potentially multiple supported file into an hyperspy structure
Supported formats: hspy (HDF5), msa, Gatan dm3, Ripple (rpl+raw), Bruker bcf, FEI ser and emi, SEMPER unf, EMD, EDAX spd/spc, tif, and a number of image formats.
Any extra keyword is passed to the corresponding 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.
- signal_type ({None, "EELS", "EDS_SEM", "EDS_TEM", "", 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.
- 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. If each file contains multiple (N) signals, N stacks will be created, with the requirement that each file contains the same number of signals.
- 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.
- lazy ({None, bool}) – Open the data lazily - i.e. without actually reading the data from the disk until required. Allows opening arbitrary-sized datasets. default is False.
- print_info (bool) – For SEMPER unf- and EMD (Berkley)-files, if True (default is False) additional information read during loading is printed for a quick overview.
- downsample (int (1–4095)) – For Bruker bcf files, if set to integer (>=2) (default 1) bcf is parsed into down-sampled size array by given integer factor, multiple values from original bcf pixels are summed forming downsampled pixel. This allows to improve signal and conserve the memory with the cost of lower resolution.
- cutoff_at_kV ({None, int, float}) – For Bruker bcf files, if set to numerical (default is None) bcf is parsed into array with depth cutoff at coresponding given energy. This allows to conserve the memory, with cutting-off unused spectra’s tail, or force enlargement of the spectra size.
- select_type ({'spectrum', 'image', None}) – For Bruker bcf files, if one of ‘spectrum’ or ‘image’ (default is None) the loader returns either only hypermap or only SEM/TEM electron images.
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 multiple files:
>>> d = hs.load('file1.dm3','file2.dm3')
Loading multiple files matching the pattern:
>>> d = hs.load('file*.dm3')
Loading (potentially larger than the available memory) files lazily and stacking:
>>> s = hs.load('file*.blo', lazy=True, stack=True)
-
hyperspy.io.
load_single_file
(filename, signal_type=None, **kwds)¶ Load any supported file into an HyperSpy structure Supported formats: netCDF, msa, Gatan dm3, Ripple (rpl+raw), Bruker bcf, FEI ser and emi, EDAX spc and spd, hspy (HDF5), and SEMPER unf.
Parameters: filename (string) – File name (including the extension)
-
hyperspy.io.
load_with_reader
(filename, reader, signal_type=None, **kwds)¶
-
hyperspy.io.
save
(filename, signal, overwrite=None, **kwds)¶
hyperspy.logger module¶
-
hyperspy.logger.
set_log_level
(level)¶ Convenience function to set the log level of all hyperspy modules.
Note: The log level of all other modules are left untouched.
Parameters: level ({int | str}) – The log level to set. Any values that logging.Logger.setLevel() accepts are valid. The default options are:
- ’CRITICAL’
- ’ERROR’
- ’WARNING’
- ’INFO’
- ’DEBUG’
- ’NOTSET’
For normal logging of hyperspy functions, you can set the log level like this:
>>> import hyperspy.api as hs >>> hs.set_log_level('INFO') >>> hs.load(r'my_file.dm3') INFO:hyperspy.io_plugins.digital_micrograph:DM version: 3 INFO:hyperspy.io_plugins.digital_micrograph:size 4796607 B INFO:hyperspy.io_plugins.digital_micrograph:Is file Little endian? True INFO:hyperspy.io_plugins.digital_micrograph:Total tags in root group: 15 <Signal2D, title: My file, dimensions: (|1024, 1024)>
If you need the log output during the initial import of hyperspy, you should set the log level like this:
>>> from hyperspy.logger import set_log_level >>> set_log_level('DEBUG') >>> import hyperspy.api as hs DEBUG:hyperspy.gui:Loading hyperspy.gui DEBUG:hyperspy.gui:Current MPL backend: TkAgg DEBUG:hyperspy.gui:Current ETS toolkit: qt4 DEBUG:hyperspy.gui:Current ETS toolkit set to: null
hyperspy.model module¶
-
class
hyperspy.model.
BaseModel
¶ Bases:
list
Model and data fitting tools applicable to signals of both one and two dimensions.
Models of one-dimensional signals should use the
Model1D
and models of two-dimensional signals should use theModel2D
.A model is constructed as a linear combination of
components
that are added to the model usingappend()
orextend()
. There are many predefined components available in the in thecomponents
module. If needed, new components can be created easily using the code of existing components as a template.Once defined, the model can be fitted to the data using
fit()
ormultifit()
. 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.
-
signal
¶ BaseSignal instance – It contains the data to fit.
-
chisq
¶ A BaseSignal of floats – Chi-squared of the signal (or np.nan if not yet fit)
-
dof
¶ A BaseSignal of integers – Degrees of freedom of the signal (0 if not yet fit)
-
red_chisq
¶ BaseSignal instance – Reduced chi-squared.
-
components
¶ ModelComponents instance – The components of the model are attributes of this class. This provides a convenient 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 BaseSignal 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.
-
as_dictionary
()¶ Exports the model to a dictionary that can be saved in a file.
See also
Model1D
,Model2D
-
append
(thing) Add component to Model.
Parameters: thing (Component instance.) –
-
as_dictionary
(fullcopy=True) Returns a dictionary of the model, including all components, degrees of freedom (dof) and chi-squared (chisq) with values.
Parameters: fullcopy (Bool (optional, True)) – Copies of objects are stored, not references. If any found, functions will be pickled and signals converted to dictionaries Returns: - dictionary (a complete dictionary of the model, which includes at)
- least the following fields –
- components : list
- a list of dictionaries of components, one per
- _whitelist : dictionary
- a dictionary with keys used as references for saved attributes,
for more information, see
hyperspy.misc.export_dictionary.export_to_dictionary()
- any field from _whitelist.keys() *
Examples
>>> s = signals.Signal1D(np.random.random((10,100))) >>> m = s.create_model() >>> l1 = components1d.Lorentzian() >>> l2 = components1d.Lorentzian() >>> m.append(l1) >>> m.append(l2) >>> d = m.as_dictionary() >>> m2 = s.create_model(dictionary=d)
-
as_signal
(component_list=None, out_of_range_to_nan=True, show_progressbar=None, out=None, parallel=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. Default True.
- show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
- out ({None, BaseSignal}) – The signal where to put the result into. Convenient for parallel processing. If None (default), creates a new one. If passed, it is assumed to be of correct shape and dtype and not checked.
- parallel (bool, int) – If True or more than 1, perform the recreation parallel using as many threads as specified. If True, as many threads as CPU cores available are used.
Returns: spectrum
Return type: An instance of the same class as spectrum.
Examples
>>> s = hs.signals.Signal1D(np.random.random((10,100))) >>> m = s.create_model() >>> l1 = hs.model.components1D.Lorentzian() >>> l2 = hs.model.components1D.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.
-
create_samfire
(workers=None, setup=True, **kwargs)¶ Creates a SAMFire object.
Parameters: - workers ({None, int}) – the number of workers to initialise. If zero, all computations will be done serially. If None (default), will attempt to use (number-of-cores - 1), however if just one core is available, will use one worker.
- setup (bool) – if the setup should be run upon initialization.
- **kwargs – Any that will be passed to the _setup and in turn SamfirePool.
-
disable_plot_components
()¶
-
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='hspy', 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 extension of the file format. It must be one of the fileformats supported by HyperSpy. The default is “hspy”.
- 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) → None -- extend list by appending elements from the iterable
-
fetch_stored_values
(only_fixed=False) Fetch the value of the parameters that has been previously stored.
Parameters: only_fixed (bool, optional) – If True, only the fixed parameters are fetched. See also
-
fit
(fitter='leastsq', 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 ({"leastsq", "mpfit", "odr", "Nelder-Mead",) –
- “Powell”, “CG”, “BFGS”, “Newton-CG”, “L-BFGS-B”, “TNC”,
- ”Differential Evolution”}
The optimization algorithm used to perform the fitting. Default is “leastsq”.
”leastsq” performs least-squares optimization, and supports bounds on parameters.”mpfit” performs least-squares using the Levenberg–Marquardt algorithm and supports bounds on parameters.
”odr” performs the optimization using the orthogonal distance regression algorithm. It does not support bounds.
”Nelder-Mead”, “Powell”, “CG”, “BFGS”, “Newton-CG”, “L-BFGS-B” and “TNC” are wrappers for scipy.optimize.minimize(). Only “L-BFGS-B” and “TNC” support bounds.
”Differential Evolution” is a global optimization method.
”leastsq”, “mpfit” and “odr” 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 a variance of 1. If the noise is heteroscedastic, this can 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”, then weighted least squares is performed.
- method ({'ls', 'ml'}) – Choose ‘ls’ (default) for least-squares and ‘ml’ for Poisson maximum likelihood estimation. The latter is not available when ‘fitter’ is “leastsq”, “odr” or “mpfit”.
- 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.
- 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
- fitter ({"leastsq", "mpfit", "odr", "Nelder-Mead",) –
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
insert
(**kwargs)¶ L.insert(index, object) – insert object before index
-
load_parameters_from_file
(filename)¶ Loads the parameters array from a binary file written with the ‘save_parameters2file’ function.
Parameters: filename (str) – See also
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.
-
multifit
(mask=None, fetch_only_fixed=False, autosave=False, autosave_every=10, show_progressbar=None, interactive_plot=False, **kwargs)¶ Fit the data to the model at all the positions of the navigation dimensions.
Parameters: - mask (NumPy array, optional) – 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. Default False.
- autosave (bool) – If True, the result of the fit will be saved automatically with a frequency defined by autosave_every. Default False.
- autosave_every (int) – Save the result of fitting every given number of spectra. Default 10.
- show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
- interactive_plot (bool) – If True, update the plot for every position as they are processed. Note that this slows down the fitting by a lot, but it allows for interactive monitoring of the fitting (if in interactive mode).
- **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
-
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, skip_multi=False) 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.
- skip_multi (bool) – If True, parameters with attribute “__iter__” are not printed
-
red_chisq
Reduced chi-squared. Calculated from self.chisq and self.dof
-
remove
(thing) Remove component from model.
Examples
>>> s = hs.signals.Signal1D(np.empty(1)) >>> m = s.create_model() >>> g = hs.model.components1D.Gaussian() >>> m.append(g)
You could remove g like this
>>> m.remove(g)
Like this:
>>> m.remove("Gaussian")
Or like this:
>>> m.remove(0)
-
save
(file_name, name=None, **kwargs)¶ Saves signal and its model to a file
Parameters: - file_name (str) – Name of the file
- name ({None, str}) – Stored model name. Auto-generated if left empty
- **kwargs – Other keyword arguments are passed onto BaseSignal.save()
-
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) – See also
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 whose 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.components1D.Voigt() >>> v2 = hs.model.components1D.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_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.components1D.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.components1D.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 whose value will be changed
- value (number) – The new value of the parameter
- component_list (list of hyperspy components, optional) – A list of components whose 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.components1D.Voigt() >>> v2 = hs.model.components1D.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)
-
store
(name=None)¶ Stores current model in the original signal
Parameters: name ({None, str}) – Stored model name. Auto-generated if left empty
-
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
(update_on_resume=True)¶ Prevents plot from updating until ‘with’ clause completes.
See also
-
update_plot
(*args, **kwargs) Update model plot.
The updating can be suspended using suspend_update.
See also
-
-
class
hyperspy.model.
DummyComponentsContainer
¶ Bases:
object
-
class
hyperspy.model.
ModelComponents
(model)¶ Bases:
object
Container for model components.
Useful to provide tab completion when running in IPython.
-
class
hyperspy.model.
ModelSpecialSlicers
(model, isNavigation)¶ Bases:
object
hyperspy.roi module¶
Region of interests (ROIs).
ROIs operate on BaseSignal instances and include widgets for interactive operation.
The following 1D ROIs are available:
- Point1DROI
- Single element ROI of a 1D signal.
- SpanROI
- Interval ROI of a 1D signal.
The following 2D ROIs are available:
- Point2DROI
- Single element ROI of a 2D signal.
- RectangularROI
- Rectagular ROI of a 2D signal.
- CircleROI
- (Hollow) circular ROI of a 2D signal
- Line2DROI
- Line profile of a 2D signal with customisable width.
-
class
hyperspy.roi.
BaseInteractiveROI
¶ Bases:
hyperspy.roi.BaseROI
Base class for interactive ROIs, i.e. ROIs with widget interaction. The base class defines a lot of the common code for interacting with widgets, but inhertors need to implement the following functions:
_get_widget_type() _apply_roi2widget(widget) _set_from_widget(widget)
-
add_widget
(signal, axes=None, widget=None, color='green')¶ Add a widget to visually represent the ROI, and connect it so any changes in either are reflected in the other. Note that only one widget can be added per signal/axes combination.
- signal : Signal
- The signal to witch the widget is added. This is used to determine with plot to add the widget to, and it supplies the axes_manager for the widget.
- axes : specification of axes to use, default = None
The axes argument specifies which axes the ROI will be applied on. The DataAxis in the collection can be either of the following:
- “navigation” or “signal”, in which the first axes of that space’s axes will be used.
- a tuple of:
- DataAxis. These will not be checked with signal.axes_manager.
- anything that will index signal.axes_manager
- For any other value, it will check whether the navigation space can fit the right number of axis, and use that if it fits. If not, it will try the signal space.
- widget : Widget or None (default)
- If specified, this is the widget that will be added. If None, the default widget will be used, as given by _get_widget_type().
- color : Matplotlib color specifier (default: ‘green’)
- The color for the widget. Any format that matplotlib uses should be ok. This will not change the color fo any widget passed with the ‘widget’ argument.
-
interactive
(signal, navigation_signal='same', out=None, color='green', **kwargs)¶ Creates an interactively sliced Signal (sliced by this ROI) via hyperspy.interactive.
- signal : Signal
- The source signal to slice
- navigation_signal : Signal, None or “same” (default)
- If not None, it will automatically create a widget on navigation_signal. Passing “same” is identical to passing the same signal to ‘signal’ and ‘navigation_signal’, but is less ambigous, and allows “same” to be the default value.
- out : Signal
- If not None, it will use ‘out’ as the output instead of returning a new Signal.
- color : Matplotlib color specifier (default: ‘green’)
- The color for the widget. Any format that matplotlib uses should be ok. This will not change the color fo any widget passed with the ‘widget’ argument.
- **kwargs
- All kwargs are passed to the roi __call__ method which is called interactivel on any roi attribute change.
-
remove_widget
(signal)¶
-
update
()¶ Function responsible for updating anything that depends on the ROI. It should be called by implementors whenever the ROI changes. This implementation updates the widgets associated with it, and triggers the changed event.
-
-
class
hyperspy.roi.
BasePointROI
¶ Bases:
hyperspy.roi.BaseInteractiveROI
Base ROI class for point ROIs, i.e. ROIs with a unit size in each of its dimensions.
-
class
hyperspy.roi.
BaseROI
¶ Bases:
traits.has_traits.HasTraits
Base class for all ROIs.
Provides some basic functionality that is likely to be shared between all ROIs, and serve as a common type that can be checked for.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
ndim
¶
-
update
()¶ Function responsible for updating anything that depends on the ROI. It should be called by implementors whenever the ROI changes. The base implementation simply triggers the changed event.
-
-
class
hyperspy.roi.
CircleROI
(cx, cy, r, r_inner=None)¶ Bases:
hyperspy.roi.BaseInteractiveROI
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
-
class
hyperspy.roi.
Line2DROI
(x1, y1, x2, y2, linewidth=0)¶ Bases:
hyperspy.roi.BaseInteractiveROI
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
length
¶
-
static
profile_line
(img, src, dst, axes, linewidth=1, order=1, mode='constant', cval=0.0)¶ Return the intensity profile of an image measured along a scan line.
Parameters: - img (numeric array, shape (M, N[, C])) – The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information).
- src (2-tuple of numeric scalar (float or int)) – The start point of the scan line.
- dst (2-tuple of numeric scalar (float or int)) – The end point of the scan line.
- linewidth (int, optional) – Width of the scan, perpendicular to the line
- order (int in {0, 1, 2, 3, 4, 5}, optional) – The order of the spline interpolation to compute image values at non-integer coordinates. 0 means nearest-neighbor interpolation.
- mode (string, one of {'constant', 'nearest', 'reflect', 'wrap'},) – optional How to compute any values falling outside of the image.
- cval (float, optional) – If mode is ‘constant’, what constant value to use outside the image.
Returns: return_value – The intensity profile along the scan line. The length of the profile is the ceil of the computed length of the scan line.
Return type: array
Examples
>>> x = np.array([[1, 1, 1, 2, 2, 2]]) >>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)]) >>> img array([[0, 0, 0, 0, 0, 0], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [0, 0, 0, 0, 0, 0]]) >>> profile_line(img, (2, 1), (2, 4)) array([ 1., 1., 2., 2.])
Notes
The destination point is included in the profile, in contrast to standard numpy indexing.
-
-
class
hyperspy.roi.
Point1DROI
(value)¶ Bases:
hyperspy.roi.BasePointROI
Selects a single point in a 1D space. The coordinate of the point in the 1D space is stored in the ‘value’ trait.
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
-
class
hyperspy.roi.
Point2DROI
(x, y)¶ Bases:
hyperspy.roi.BasePointROI
Selects a single point in a 2D space. The coordinates of the point in the 2D space are stored in the traits ‘x’ and ‘y’.
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
-
class
hyperspy.roi.
RectangularROI
(left, top, right, bottom)¶ Bases:
hyperspy.roi.BaseInteractiveROI
Selects a range in a 2D space. The coordinates of the range in the 2D space are stored in the traits ‘left’, ‘right’, ‘top’ and ‘bottom’. Convenience properties ‘x’, ‘y’, ‘width’ and ‘height’ are also available, but cannot be used for initialization.
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
height
¶ Returns / sets the height of the ROI
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
width
¶ Returns / sets the width of the ROI
-
x
¶ Returns / sets the x coordinate of the ROI without changing its width
-
y
¶ Returns / sets the y coordinate of the ROI without changing its height
-
-
class
hyperspy.roi.
SpanROI
(left, right)¶ Bases:
hyperspy.roi.BaseInteractiveROI
Selects a range in a 1D space. The coordinates of the range in the 1D space are stored in the traits ‘left’ and ‘right’.
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
is_valid
()¶ Determine if the ROI is in a valid state.
This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.
-
hyperspy.samfire module¶
-
class
hyperspy.samfire.
Samfire
(model, workers=None, setup=True, **kwargs)¶ Bases:
object
Smart Adaptive Multidimensional Fitting (SAMFire) object
SAMFire is a more robust way of fitting multidimensional datasets. By extracting starting values for each pixel from already fitted pixels, SAMFire stops the fitting algorithm from getting lost in the parameter space by always starting close to the optimal solution.
SAMFire only picks starting parameters and the order the pixels (in the navigation space) are fitted, and does not provide any new minimisation algorithms.
-
model
¶ Model instance – The complete model
-
optional_components
¶ list – A list of components that can be switched off at some pixels if it returns a better Akaike’s Information Criterion with correction (AICc)
-
workers
¶ int – A number of processes that will perform the fitting parallely
-
pool
¶ samfire_pool instance – A proxy object that manages either multiprocessing or ipyparallel pool
-
strategies
¶ strategy list – A list of strategies that will be used to select pixel fitting order and calculate required starting parameters. Strategies come in two “flavours” - local and global. Local strategies spread the starting values to the nearest pixels and forces certain pixel fitting order. Global strategies look for clusters in parameter values, and suggests most frequent values. Global strategy do not depend on pixel fitting order, hence it is randomised.
-
metadata
¶ dictionary – A dictionary for important samfire parameters
-
active_strategy
¶ strategy – The currently active strategy from the strategies list
-
update_every
¶ int – If segmenter strategy is running, updates the historams every time update_every good fits are found.
-
plot_every
¶ int – When running, samfire plots results every time plot_every good fits are found.
-
save_every
¶ int – When running, samfire saves results every time save_every good fits are found.
-
start
()¶ start SAMFire
-
stop
()¶ stop SAMFire
-
plot
()¶ force plot of currently selected active strategy
-
refresh_database
()¶ refresh current active strategy database. No previous structure is preserved
-
backup
()¶ backs up the current version of the model
-
change_strategy
()¶ changes strategy to a new one. Certain rules apply
-
append
()¶ appends strategy to the strategies list
-
extend
()¶ extends strategies list
-
remove
()¶ removes strategy from strategies list
-
update
()¶ updates the current model with values, received from a worker
-
log
()¶ if _log exists, logs the arguments to the list.
-
generate_values
()¶ creates a generator to calculate values to be sent to the workers
-
active_strategy
Returns the active strategy
-
append
(strategy) appends the given strategy to the end of the strategies list
Parameters: strategy (strategy instance) –
-
backup
(filename=None, on_count=True) Backs-up the samfire results in a file
Parameters: - filename ({str, None}) – the filename. If None, a default value of “backup_”+signal_title is used
- on_count (bool) – if True (default), only saves on the required count of steps
-
change_strategy
(new_strat) Changes current strategy to a new one. Certain rules apply: diffusion -> diffusion : resets all “ignored” pixels diffusion -> segmenter : saves already calculated pixels to be ignored
when(if) subsequently diffusion strategy is runParameters: new_strat ({int | strategy}) – index of the new strategy from the strategies list or the strategy object itself
-
count
= 0¶
-
extend
(iterable) extend the strategies list by the given iterable
Parameters: iterable (an iterable of strategy instances) –
-
generate_values
(need_inds) Returns an iterator that yields the index of the pixel and the value dictionary to be sent to the workers.
Parameters: need_inds (int) – the number of pixels to be returned in the generator
-
log
(*args) If has a list named “_log”, appends the arguments there
-
optional_components
= []
-
pixels_done
¶ Returns the number of pixels that have been solved
-
pixels_left
¶ Returns the number of pixels that are left to solve. This number can increase as SAMFire learns more information about the data.
-
plot
(on_count=False) (if possible) plots current strategy plot. Local strategies plot grayscale navigation signal with brightness representing order of the pixel selection. Global strategies plot a collection of histograms, one per parameter.
Parameters: on_count (bool) – if True, only tries to plot every speficied count, otherwise (default) always plots if possible.
-
plot_every
= 0
-
pool
= None
-
refresh_database
() Refreshes currently selected strategy without preserving any “ignored” pixels
-
remove
(thing) removes given strategy from the strategies list
Parameters: thing (int or strategy instance) – Strategy that is in current strategies list or its index.
-
running_pixels
= []¶
-
save_every
= nan
-
start
(**kwargs) Starts SAMFire.
Parameters: **kwargs (key-word arguments) – Any key-word arguments to be passed to Model.fit() call
-
update
(ind, results=None, isgood=None) Updates the current model with the results, received from the workers. Results are only stored if the results are good enough
Parameters: - ind (tuple) – contains the index of the pixel of the results
- results ({dict, None}) – dictionary of the results. If None, means we are updating in-place (e.g. refreshing the marker or strategies)
- isgood ({bool, None}) – if it is known if the results are good according to the goodness-of-fit test. If None, the pixel is tested
-
hyperspy.signal module¶
-
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
-
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 a marker 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.
- 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) >>> s.plot(plot_markers=True)
Add permanent marker
>>> s = hs.signals.Signal2D(np.random.random((100, 100))) >>> marker = hs.markers.point(50, 60) >>> s.add_marker(marker, permanent=True, plot_marker=True) >>> s.plot(plot_markers=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)
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) –
- 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
-
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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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, default is True) – 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, 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, default is True) – 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)¶ 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.
-
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 | string | 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, 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
(axis, order=1, out=None, rechunk=True)¶ Returns a signal with the n-th order discrete difference along given axis.
Parameters: - axis ({int | string | 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, 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.
See also
max()
,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.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:
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 inmetadata.Signal.Noise_properties.Variance_linear_model
.
-
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, 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()
-
indexmax
(axis, out=None, rechunk=True)¶ Returns a signal with the index of the maximum along an axis.
Parameters: - axis ({int | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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)
-
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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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
See also
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)
-
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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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
See also
max()
,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.var(-1).data.shape (64,64)
-
is_rgb
¶
-
is_rgba
¶
-
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 is set in preferences.
- parallel ({None,bool,int}) – if True, the mapping will be performed in a threaded (parallel) manner.
- 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 aSignal
instance for similar purposes. However, this method has the advantage of being faster because it iterates the numpy array instead of theSignal
.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 | string | axis | tuple | 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, 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 | string | axis | tuple | 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, 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 | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- axis : {int | string | axis | tuple | 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, 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.
- optional (**kwargs,) – Additional key word arguments passed to matplotlib.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
-
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, 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 | string | 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 | string | 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, default is False) – 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 - axis ({'auto' | int | string}) –
-
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 | string | axis | tuple | 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, 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 | string | axis | tuple | 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, 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, default is False) – 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, default is False) – 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
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.
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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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 | string | axis}) – The axis can be passed directly, or specified using the index of the axis in axes_manager or the axis name.
- out ({Signal, 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
-
var
(axis=None, out=None, rechunk=True)¶ Returns a signal with the variances of the signal along at least one axis.
Parameters: - axis ({int | string | axis | tuple | 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, 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)
-
-
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.()
- comp_ids (None, int, or list of ints) –
-
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.()
- comp_ids (None, int, or list of ints) – if None (default), returns maps of all components if the output_dimension was defined when
executing
-
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.()
- comp_ids (None, int, or list of ints) – if None (default), returns maps of all components if the output_dimension was defined when
executing
-
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
-
restore
(name)¶ Returns the restored model
Parameters: name (string) – the name of the model to restore
-
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
-
class
-
class
hyperspy.signal.
SpecialSlicersSignal
(obj, isNavigation)¶
hyperspy.signal_tools module¶
-
class
hyperspy.signal_tools.
BackgroundRemoval
(signal, background_type='Power Law', polynomial_order=2, fast=True, show_progressbar=None)¶ Bases:
hyperspy.signal_tools.SpanSelectorInSignal1D
-
apply
()¶
-
bg_to_plot
(axes_manager=None, fill_with=nan)¶
-
create_background_line
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
on_disabling_span_selector
()¶
-
set_background_estimator
()¶
-
span_selector_changed
()¶
-
-
class
hyperspy.signal_tools.
ButterworthFilter
(signal)¶ Bases:
hyperspy.signal_tools.Smoothing
-
apply
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
model2plot
(axes_manager=None)¶
-
-
class
hyperspy.signal_tools.
DerivativeTextHandler
¶ Bases:
object
-
legend_artist
(legend, orig_handle, fontsize, handlebox)¶
-
-
class
hyperspy.signal_tools.
DerivativeTextParameters
(text, color)¶ Bases:
object
-
class
hyperspy.signal_tools.
ImageContrastEditor
(image)¶ Bases:
traits.has_traits.HasTraits
-
apply
()¶
-
close
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
on_disabling_span_selector
()¶
-
plot_histogram
()¶
-
reset
()¶
-
span_selector_switch
(on)¶
-
update_histogram
()¶
-
update_span_selector_traits
(*args, **kwargs)¶
-
-
class
hyperspy.signal_tools.
IntegrateArea
(signal, signal_range=None)¶ Bases:
hyperspy.signal_tools.SpanSelectorInSignal1D
-
apply
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
-
class
hyperspy.signal_tools.
LineInSignal1D
(signal)¶ Bases:
traits.has_traits.HasTraits
Adds a vertical draggable line to a spectrum that reports its position to the position attribute of the class.
- position : float
- The position of the vertical line in the one dimensional signal. Moving the line changes the position but the reverse is not true.
- on : bool
- Turns on and off the line
- color : wx.Colour
- The color of the line. It automatically redraws the line.
-
draw
()¶
-
switch_on_off
(obj, trait_name, old, new)¶
-
update_position
(*args, **kwargs)¶
-
class
hyperspy.signal_tools.
Load
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.signal_tools.
Signal1DCalibration
(signal)¶ Bases:
hyperspy.signal_tools.SpanSelectorInSignal1D
-
apply
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
-
class
hyperspy.signal_tools.
Signal1DRangeSelector
(signal)¶
-
class
hyperspy.signal_tools.
SimpleMessage
(text='')¶ Bases:
traits.has_traits.HasTraits
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
-
class
hyperspy.signal_tools.
Smoothing
(signal)¶ Bases:
traits.has_traits.HasTraits
-
close
()¶
-
diff_model2plot
(axes_manager=None)¶
-
line_color_rgb
¶
-
plot
()¶
-
turn_diff_line_off
()¶
-
turn_diff_line_on
(diff_order)¶
-
update_lines
()¶
-
-
class
hyperspy.signal_tools.
SmoothingLowess
(*args, **kwargs)¶ Bases:
hyperspy.signal_tools.Smoothing
-
apply
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
model2plot
(axes_manager=None)¶
-
-
class
hyperspy.signal_tools.
SmoothingSavitzkyGolay
(signal)¶ Bases:
hyperspy.signal_tools.Smoothing
-
apply
()¶
-
diff_model2plot
(axes_manager=None)¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
model2plot
(axes_manager=None)¶
-
-
class
hyperspy.signal_tools.
SmoothingTV
(signal)¶ Bases:
hyperspy.signal_tools.Smoothing
-
apply
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
model2plot
(axes_manager=None)¶
-
-
class
hyperspy.signal_tools.
SpanSelectorInSignal1D
(signal)¶ Bases:
traits.has_traits.HasTraits
-
on_disabling_span_selector
()¶
-
reset_span_selector
()¶
-
span_selector_switch
(on)¶
-
update_span_selector_traits
(*args, **kwargs)¶
-
-
class
hyperspy.signal_tools.
SpikesRemoval
(signal, navigation_mask=None, signal_mask=None)¶ Bases:
hyperspy.signal_tools.SpanSelectorInSignal1D
-
apply
()¶
-
create_interpolation_line
()¶
-
detect_spike
()¶
-
find
(back=False)¶
-
get_interpolated_spectrum
(axes_manager=None)¶
-
get_interpolation_range
()¶
-
gui
(display=True, toolkit=None, **kwargs)¶ Display or return interactive GUI element if available.
Parameters: - display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
- toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
-
interpolator
= None¶
-
on_disabling_span_selector
()¶
-
span_selector_changed
()¶
-
update_plot
()¶
-
update_spectrum_line
()¶
-
hyperspy.signals module¶
The Signal class and its specilized subclasses:
- BaseSignal
- 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.
- ComplexSignal
- For generic complex data with arbitrary signal_dimension.
- ComplexSignal1D
- For generic complex data with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is unbinned by default.
- ComplexSignal2D
- For generic complex data with signal_dimension equal 2, i.e. image data of n-dimensions. The signal is unbinned by default.
- EELSSpectrum
- For electron energy-loss data with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is binned by default.
- 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.
- HolographyImage
- For 2D-images taken via electron holography. Electron wave as ComplexSignal2D can be reconstructed from them.
hyperspy.ui_registry module¶
Registry of user interface widgets.
Format {“tool_key” : {“toolkit” : <function(obj, display, **kwargs)>}}
The tool_key` is defined by the "model function" to which the widget provides
and user interface. That function gets the widget function from this registry
and executes it passing the ``obj
, display
and any extra keyword
arguments. When display
is true, function
displays the widget. If
False
it returns a dictionary with whatever is needed to display the
widgets externally (usually for testing or customisation purposes).
-
hyperspy.ui_registry.
add_gui_method
(toolkey)¶
-
hyperspy.ui_registry.
get_gui
(self, toolkey, display=True, toolkit=None, **kwargs)¶
-
hyperspy.ui_registry.
get_partial_gui
(toolkey)¶
-
hyperspy.ui_registry.
register_toolkey
(toolkey)¶ Register a toolkey.
Parameters: toolkey (string) –
-
hyperspy.ui_registry.
register_widget
(toolkit, toolkey)¶ Decorator to register a UI widget.
Parameters: - f (function) – Function that returns or display the UI widget. The signature must
include
obj
,display
and**kwargs
. - toolkit (string) – The name of the widget toolkit e.g. ipywidgets
- toolkey (string) – The “key” of the tool for which the widget provides an interface. If
the toolkey is not in the
UI_REGISTRY
dictionary aNameError
is raised.
Returns: widgets – Dictionary containing the widget objects if display is False, else None.
Return type: dictionary or None
- f (function) – Function that returns or display the UI widget. The signature must
include
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.