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.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.gui 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.emd module
- hyperspy.io_plugins.fei module
- hyperspy.io_plugins.hdf5 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.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
- 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_dm4 module
- hyperspy.tests.io.test_dm_stackbuilder_plugin module
- hyperspy.tests.io.test_emd module
- hyperspy.tests.io.test_fei module
- hyperspy.tests.io.test_hdf5 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
- 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_image module
- hyperspy.tests.signal.test_integrate_in_range module
- hyperspy.tests.signal.test_kramers_kronig_transform 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
- hyperspy.tests.test_travis module
- Module contents
- Subpackages
- hyperspy.utils package
Submodules¶
hyperspy.Release module¶
hyperspy.api module¶
All public packages, functions and classes are available in this module.
When starting HyperSpy using the hyperspy
script (e.g. by executing
hyperspy
in a console, using the context menu entries or using the links in
the Start Menu
, the api
package is imported in the user
namespace as hs
, i.e. by executing the following:
>>> import hyperspy.api as hs
(Note that code snippets are indicated by three greater-than signs)
We recommend to import the HyperSpy API as above also when doing it manually.
The docstring examples assume that hyperspy has been imported as hs,
numpy as np
and matplotlib.pyplot
as plt
.
Functions:
- create_model
- Create a model for curve fitting.
- get_configuration_directory_path
- Return the configuration directory path.
- load
- Load data into 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.
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, subscriptins and iteration. As an iterator, iterate over the navigation coordinates returning the current indices. It can only be indexed and sliced to access the DataAxis objects that it contains. Standard indexing and slicing follows the “natural order” as in Signal, i.e. [nX, nY, ...,sX, sY,...] where n indicates a navigation axis and s a signal axis. In addition AxesManager support indexing using complex numbers a + bj, where b can be one of 0, 1, 2 and 3 and a a valid index. If b is 3 AxesManager is indexed using the order of the axes in the array. If b is 1(2), indexes only the navigation(signal) axes in the natural order. In addition AxesManager supports subscription using axis name.
-
coordinates
¶ tuple – Get and set the current coordinates if the navigation dimension is not 0. If the navigation dimension is 0 it raises AttributeError when attempting to set its value.
- indices : tuple
- Get and set the current indices if the navigation dimension is not 0. If the navigation dimension is 0 it raises AttributeError when attempting to set its value.
- signal_axes, navigation_axes : list
- Contain the corresponding DataAxis objects
Examples
>>> %hyperspy HyperSpy imported! The following commands were just executed: --------------- import numpy as np import hyperspy.api as hs %matplotlib qt import matplotlib.pyplot as plt
>>> # Create a spectrum with random data
>>> s = hs.signals.Signal1D(np.random.random((2,3,4,5))) >>> s.axes_manager <Axes manager, axes: (<axis2 axis, size: 4, index: 0>, <axis1 axis, size: 3, index: 0>, <axis0 axis, size: 2, index: 0>, <axis3 axis, size: 5>)> >>> s.axes_manager[0] <axis2 axis, size: 4, index: 0> >>> s.axes_manager[3j] <axis0 axis, size: 2, index: 0> >>> s.axes_manager[1j] <axis2 axis, size: 4, index: 0> >>> s.axes_manager[2j] <axis3 axis, size: 5> >>> s.axes_manager[1].name="y" >>> s.axes_manager['y'] <y axis, size: 3 index: 0> >>> for i in s.axes_manager: >>> print(i, s.axes_manager.indices) (0, 0, 0) (0, 0, 0) (1, 0, 0) (1, 0, 0) (2, 0, 0) (2, 0, 0) (3, 0, 0) (3, 0, 0) (0, 1, 0) (0, 1, 0) (1, 1, 0) (1, 1, 0) (2, 1, 0) (2, 1, 0) (3, 1, 0) (3, 1, 0) (0, 2, 0) (0, 2, 0) (1, 2, 0) (1, 2, 0) (2, 2, 0) (2, 2, 0) (3, 2, 0) (3, 2, 0) (0, 0, 1) (0, 0, 1) (1, 0, 1) (1, 0, 1) (2, 0, 1) (2, 0, 1) (3, 0, 1) (3, 0, 1) (0, 1, 1) (0, 1, 1) (1, 1, 1) (1, 1, 1) (2, 1, 1) (2, 1, 1) (3, 1, 1) (3, 1, 1) (0, 2, 1) (0, 2, 1) (1, 2, 1) (1, 2, 1) (2, 2, 1) (2, 2, 1) (3, 2, 1) (3, 2, 1)
-
as_dictionary
()¶
-
axes_are_aligned_with_data
¶ Verify if the data axes are aligned with the signal axes.
When the data are aligned with the axes the axes order in self._axes is [nav_n, nav_n-1, ..., nav_0, sig_m, sig_m-1 ..., sig_0].
Returns: aligned Return type: bool
-
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
()¶
-
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_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
()¶
-
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=None, save_std=False, only_free=True)¶ Plot the value of the parameters of the model
Parameters: - folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.
- format (str) –
The format to which the data will be exported. It must be the extension of any format supported by HyperSpy. If None, the default format for exporting as defined in the Preferences will be
used. - save_std (bool) – If True, also the standard deviation will be saved.
- only_free (bool) –
- If True, only the value of the parameters that are free will
- be
exported.
Notes
The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.
-
fetch_stored_values
(only_fixed=False)¶
-
fetch_values_from_array
(p, p_std=None, onlyfree=False)¶
-
init_parameters
(parameter_name_list)¶
-
notebook_interaction
(display=True)¶ Creates interactive notebook widgets for all component parameters, if available. Requires ipywidgets to be installed. :param display: if True (default), attempts to display the widgets.
Otherwise returns the formatted widget object.
-
plot
(only_free=True)¶ Plot the value of the parameters of the model
Parameters: only_free (bool) – - If True, only the value of the parameters that are free will
- be plotted
-
set_parameters_free
(parameter_name_list=None)¶ Sets parameters in a component to free.
Parameters: parameter_name_list (None or list of strings, optional) – If None, will set all the parameters to free. If list of strings, will set all the parameters with the same name as the strings in parameter_name_list to free. Examples
>>> v1 = hs.model.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)¶
-
-
class
hyperspy.component.
Parameter
¶ Bases:
traits.has_traits.HasTraits
Model parameter
-
value
¶ float or array – The value of the parameter for the current location. The value for other locations is stored in map.
-
bmin, bmax
float – Lower and upper bounds of the parameter value.
-
twin
¶ {None, Parameter} – If it is not None, the value of the current parameter is a function of the given Parameter. The function is by default the identity function, but it can be defined by twin_function
-
twin_function
¶ function – Function that, if selt.twin is not None, takes self.twin.value as its only argument and returns a float or array that is returned when getting Parameter.value
-
twin_inverse_function
¶ function – The inverse of twin_function. If it is None then it is not possible to set the value of the parameter twin by setting the value of the current parameter.
-
ext_force_positive
¶ bool – If True, the parameter value is set to be the absolute value of the input value i.e. if we set Parameter.value = -3, the value stored is 3 instead. This is useful to bound a value to be positive in an optimization without actually using an optimizer that supports bounding.
-
ext_bounded
¶ bool – Similar to ext_force_positive, but in this case the bounds are defined by bmin and bmax. It is a better idea to use an optimizer that supports bounding though.
-
as_signal
(field = 'values')¶ Get a parameter map as a signal object
-
plot
()¶ Plots the value of the Parameter at all locations.
-
export
(folder=None, name=None, format=None, save_std=False)¶ Saves the value of the parameter map to the specified format
-
connect, disconnect(function)
Call the functions connected when the value attribute changes.
-
as_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
()¶
-
export
(folder=None, name=None, format=None, save_std=False) Save the data to a file.
All the arguments are optional.
Parameters: - folder (str or None) –
- The path to the folder where the file will be saved.
- If None the current folder is used by default.
- name (str or None) –
- The name of the file. If None the Components name followed
- by the Parameter name attributes will be used by default.
- If a file with the same name exists the name will be modified by appending a number to the file path.
- save_std (bool) – If True, also the standard deviation will be saved
- folder (str or None) –
-
ext_bounded
-
ext_force_positive
-
fetch
()¶ Fetch the stored value and std attributes.
-
notebook_interaction
(display=True)¶ Creates interactive notebook widgets for the parameter, if available. Requires ipywidgets to be installed. :param display: if True (default), attempts to display the parameter widget.
Otherwise returns the formatted widget object.
-
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
-
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.¶
Gaussian2D Normalized 2D elliptical gaussian function ..
hyperspy.decorators module¶
-
hyperspy.decorators.
interactive_range_selector
(f)¶
-
hyperspy.decorators.
only_interactive
(f)¶
-
hyperspy.decorators.
simple_decorator
(decorator)¶ This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn’t modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied.
This decorator was taken from: http://wiki.python.org/moin/PythonDecoratorLibrary
hyperspy.defaults_parser module¶
-
class
hyperspy.defaults_parser.
EDSConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
EELSConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
GeneralConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
MachineLearningConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
ModelConfig
¶ Bases:
traits.has_traits.HasTraits
-
class
hyperspy.defaults_parser.
PlotConfig
¶ Bases:
traits.has_traits.HasTraits
-
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='')¶ Given record_by and signal_type return the matching Signal subclass. :param dtype: :type dtype:
dtype
:param signal_dimension: :type signal_dimension: int :param signal_type: :type signal_type: {“EELS”, “EDS”, “EDS_SEM”, “EDS_TEM”, “DielectricFunction”, “”, str}Returns: Return type: Signal or subclass
-
hyperspy.io.
dict2signal
(signal_dict)¶ Create a signal (or subclass) instance defined by a dictionary :param signal_dict: :type 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', mmap=False, mmap_dir=None, **kwds)¶ Load potentially multiple supported file into an hyperspy structure Supported formats: HDF5, msa, Gatan dm3, Ripple (rpl+raw), Bruker bcf, FEI ser and emi, hdf5, SEMPER unf, EMD, tif and a number of image formats. Any extra keyword is passed to the corresponsing reader. For available options see their individual documentation. :param filenames: 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.Parameters: - 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. It is possible to store the data in a memory mapped temporary file instead of in memory setting mmap_mode. The title is set to the name of the folder containing the files.
- stack_axis ({None, int, str}) – If None, the signals are stacked over a new axis. The data must have the same dimensions. Otherwise the signals are stacked over the axis given by its integer index or its name. The data must have the same shape, except in the dimension corresponding to axis.
- new_axis_name (string) – The name of the new axis when axis is None. If an axis with this name already exists it automatically append ‘-i’, where i are integers, until it finds a name that is not yet in use.
- mmap (bool) – If True and stack is True, then the data is stored in a memory-mapped temporary file.The memory-mapped data is stored on disk, and not directly loaded into memory. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.
- mmap_dir (string) – If mmap_dir is not None, and stack and mmap are True, the memory mapped file will be created in the given directory, otherwise the default directory is used.
- load_to_memory (bool) – for HDF5 files, blockfiles and EMD files, if True (default) loads all data to memory. If False, enables only loading the data upon request
- mmap_mode ({'r', 'r+', 'c'}) – Used when loading blockfiles to determine which mode to use for when loading as memmap (i.e. when load_to_memory=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.
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’)
-
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, hdf5 and SEMPER unf. :param filename: File name (including the extension) :type filename: string
-
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 predifined 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 convinient way to access the model components when working in IPython as it enables tab completion.
-
append
()¶ Append one component to the model.
-
extend
()¶ Append multiple components to the model.
-
remove
()¶ Remove component from model.
-
as_signal
()¶ Generate a 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) Returns a recreation of the dataset using the model. the spectral range that is not fitted is filled with nans.
Parameters: - component_list (list of hyperspy components, optional) – If a list of components is given, only the components given in the list is used in making the returned spectrum. The components can be specified by name, index or themselves.
- out_of_range_to_nan (bool) – If True the spectral range that is not fitted is filled with nans.
- show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
Returns: 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=None, save_std=False, only_free=True, only_active=True) Export the results of the parameters of the model to the desired folder.
Parameters: - folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.
- format (str) – The format to which the data will be exported. It must be the extension of any format supported by HyperSpy. If None, the default format for exporting as defined in the Preferences will be used.
- save_std (bool) – If True, also the standard deviation will be saved.
- only_free (bool) – If True, only the value of the parameters that are free will be exported.
- only_active (bool) – If True, only the value of the active parameters will be exported.
Notes
The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.
-
extend
(iterable)
-
fetch_stored_values
(only_fixed=False) Fetch the value of the parameters that has been previously stored.
Parameters: only_fixed (bool) – If True, only the fixed parameters are fetched. See also
-
fit
(fitter=None, method='ls', grad=False, bounded=False, ext_bounding=False, update_plot=False, **kwargs)¶ Fits the model to the experimental data.
The chi-squared, reduced chi-squared and the degrees of freedom are computed automatically when fitting. They are stored as signals, in the chisq, red_chisq and dof. Note that unless
metadata.Signal.Noise_properties.variance
contains an accurate estimation of the variance of the data, the chi-squared and reduced chi-squared cannot be computed correctly. This is also true for homocedastic noise.Parameters: - fitter ({None, "leastsq", "mpfit", "odr", "Nelder-Mead",) –
- “Powell”, “CG”, “BFGS”, “Newton-CG”, “L-BFGS-B”, “TNC”,
- “Differential Evolution”}
The optimization algorithm used to perform the fitting. If None the fitter defined in preferences.Model.default_fitter is used.
“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 ({None, "leastsq", "mpfit", "odr", "Nelder-Mead",) –
-
insert
(**kwargs)¶
-
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 ({None, numpy.array}) – To mask (do not fit) at certain position pass a numpy.array of type bool where True indicates that the data will not be fitted at the given position.
- fetch_only_fixed (bool) – If True, only the fixed parameters values will be updated when changing the positon.
- autosave (bool) – If True, the result of the fit will be saved automatically with a frequency defined by autosave_every.
- autosave_every (int) – Save the result of fitting every given number of spectra.
- show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
- 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
-
notebook_interaction
()¶ Creates interactive notebook widgets for all components and parameters, if available. Requires ipywidgets to be installed.
-
plot_results
(only_free=True, only_active=True) Plot the value of the parameters of the model
Parameters: - only_free (bool) – If True, only the value of the parameters that are free will be plotted.
- only_active (bool) – If True, only the value of the active parameters will be plotted.
Notes
The name of the files will be determined by each the Component and each Parameter name attributes. Therefore, it is possible to customise the file names modify the name attributes.
-
print_current_values
(only_free=True) Print the value of each parameter of the model.
Parameters: only_free (bool) – - If True, only the value of the parameters that are free will
- be printed.
-
red_chisq
Reduced chi-squared. Calculated from self.chisq and self.dof
-
remove
(thing) 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 whos parameters will changed. The components can be specified by name, index or themselves.
- only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.
Examples
>>> v1 = hs.model.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 whos value will be changed
- value (number) – The new value of the parameter
- component_list (list of hyperspy components, optional) – A list of components whos parameters will changed. The components can be specified by name, index or themselves.
- only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.
Examples
>>> v1 = hs.model.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
-
is_valid
()¶
-
-
class
hyperspy.roi.
Line2DROI
(x1, y1, x2, y2, linewidth)¶ Bases:
hyperspy.roi.BaseInteractiveROI
-
is_valid
()¶
-
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. :param img: The image, either grayscale (2D array) or multichannel
(3D array, where the final axis contains the channel information).Parameters: - 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.
-
is_valid
()¶
-
-
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’.
-
is_valid
()¶
-
-
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.
-
height
¶ Returns / sets the height of the ROI
-
is_valid
()¶
-
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’.
-
is_valid
()¶
-
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.
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 :param std: :type std: float
-
add_marker
(marker, plot_on_signal=True, plot_marker=True)¶ Add a marker to the signal or navigator plot.
Plot the signal, if not yet plotted
Parameters: - marker (hyperspy.drawing._markers) – the marker to add. see plot.markers
- plot_on_signal (bool) – If True, add the marker to the signal If False, add the marker to the navigator
- plot_marker (bool) – if True, plot the marker
Examples
>>> import scipy.misc >>> im = hs.signals.Signal2D(scipy.misc.ascent()) >>> m = hs.plot.markers.rectangle(x1=150, y1=100, x2=400, >>> y2=400, color='red') >>> im.add_marker(m)
-
add_poissonian_noise
(**kwargs)¶ Add Poissonian noise to the data
-
as_signal1D
(spectral_axis, out=None)¶ Return the Signal as a spectrum.
The chosen spectral axis is moved to the last index in the array and the data is made contiguous for effecient iteration over spectra.
Parameters: - spectral_axis ({int | 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.
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)¶ Convert signal to image.
The chosen image axes are moved to the last indices in the array and the data is made contiguous for effecient iteration over images.
Parameters: - image_axes (tuple of {int | 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.
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)¶ 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. 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)¶ 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.
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)¶ 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.
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.
- **kwargs – other keyword arguments (weight and density) are described in np.histogram().
Returns: hist_spec
Return type: An 1D spectrum instance containing the histogram.
See also
print_summary_statistics()
,astroML.density_estimation.histogram()
,numpy.histogram()
Notes
The number of bins estimators are taken from AstroML. Read their documentation for more info.
Examples
>>> s = hs.signals.Signal1D(np.random.normal(size=(10, 100))) Plot the data histogram >>> s.get_histogram().plot() Plot the histogram of the signal at the current coordinates >>> s.get_current_signal().get_histogram().plot()
-
indexmax
(axis, out=None)¶ 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.
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, **kwargs)¶ Apply a function to the signal data at all the coordinates.
The function must operate on numpy arrays and the output must have the same dimensions as the input. The function is applied to the data at each coordinate and the result is stored in the current signal i.e. this method operates in-place. Any extra keyword argument is passed to the function. The keywords can take different values at different coordinates. If the function takes an axis or axes argument, the function is assumed to be vectorial and the signal axes are assigned to axis or axes. Otherwise, the signal is iterated over the navigation axes and a progress bar is displayed to monitor the progress.
Parameters: - function (function) – A function that can be applied to the signal.
- show_progressbar (None or bool) – If True, display a progress bar. If None the default is set in preferences.
- arguments (keyword) – All extra keyword arguments are passed to the
Notes
This method is similar to Python’s
map()
that can also be utilize with 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 sigmal 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)¶ 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.
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)¶ 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.
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)¶ 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.
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)
-
plot
(navigator='auto', axes_manager=None, **kwargs)¶ Plot the signal at the current coordinates.
For multidimensional datasets an optional figure, the “navigator”, with a cursor to navigate that data is raised. In any case it is possible to navigate the data using the sliders. Currently only signals with signal_dimension equal to 0, 1 and 2 can be plotted.
Parameters: - navigator ({"auto", None, "slider", "spectrum", Signal}) – If “auto”, if navigation_dimension > 0, a navigator is provided to explore the data. If navigation_dimension is 1 and the signal is an image the navigator is a spectrum obtained by integrating over the signal axes (the image). If navigation_dimension is 1 and the signal is a spectrum the navigator is an image obtained by stacking horizontally all the spectra in the dataset. If navigation_dimension is > 1, the navigator is an image obtained by integrating the data over the signal axes. Additionaly, if navigation_dimension > 2 a window with one slider per axis is raised to navigate the data. For example, if the dataset consists of 3 navigation axes X, Y, Z and one signal axis, E, the default navigator will be an image obtained by integrating the data over E at the current Z index and a window with sliders for the X, Y and Z axes will be raised. Notice that changing the Z-axis index changes the navigator in this case. If “slider” and the navigation dimension > 0 a window with one slider per axis is raised to navigate the data. If “spectrum” and navigation_dimension > 0 the navigator is always a spectrum obtained by integrating the data over all other axes. If None, no navigator will be provided. Alternatively a Signal instance can be provided. The signal dimension must be 1 (for a spectrum navigator) or 2 (for a image navigator) and navigation_shape must be 0 (for a static navigator) or navigation_shape + signal_shape must be equal to the navigator_shape of the current object (for a dynamic navigator). If the signal dtype is RGB or RGBA this parameters has no effect and is always “slider”.
- axes_manager ({None, axes_manager}) – If None axes_manager is used.
- optional (**kwargs,) – Additional key word arguments passed to matplotlib.imshow()
-
print_summary_statistics
(formatter='%.3f')¶ Prints the five-number summary statistics of the data, the mean and the standard deviation.
Prints the mean, standandard deviation (std), maximum (max), minimum (min), first quartile (Q1), median and third quartile. nans are removed from the calculations.
Parameters: formatter (bool) – Number formatter. See also
-
rebin
(new_shape, out=None)¶ Returns the object with the data rebinned.
Parameters: - new_shape (tuple of ints) – The new shape elements must be divisors of the original shape elements.
- 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
Raises: ValueError
– When there is a mismatch between the number of elements in the signal shape and new_shape or new_shape elements are not divisors of the original signal shape.Examples
>>> import hyperspy.api as hs >>> s = hs.signals.Signal1D(np.zeros((10, 100))) >>> s <Signal1D, title: , dimensions: (10|100)> >>> s.rebin((5, 100)) <Signal1D, title: , dimensions: (5|100)> I
-
rollaxis
(axis, to_axis)¶ 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.
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.:
- hdf5 for HDF5
- 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, 'hdf5', 'rpl', 'msa', 'unf', 'blo', common image) – extensions e.g. ‘tiff’, ‘png’} The extension of the file that defines the file format. If None, the extension is taken from the first not None in the following list: i) the filename ii) tmp_parameters.extension iii) preferences.General.default_file_format in this order.
-
set_signal_origin
(origin)¶ Set the 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 containts e.g. “EELS” for electron energy-loss spectroscopy, “PES” for photoemission spectroscopy. There are some methods that are only available for certain kind of signals, so setting this parameter can enable/disable features.
Parameters: signal_type ({"EELS", "EDS_TEM", "EDS_SEM", "DielectricFunction"}) – Currently there are special features for “EELS” (electron energy-loss spectroscopy), “EDS_TEM” (energy dispersive X-rays of thin samples, normally obtained in a transmission electron microscope), “EDS_SEM” (energy dispersive X-rays of thick samples, normally obtained in a scanning electron microscope) and “DielectricFuction”. Setting the signal_type to the correct acronym is highly advisable when analyzing any signal for which HyperSpy provides extra features. Even if HyperSpy does not provide extra features for the signal that you are analyzing, it is good practice to set signal_type to a value that best describes the data signal type.
-
split
(axis='auto', number_of_parts='auto', step_sizes='auto')¶ Splits the data into several signals.
The split can be defined by giving the number_of_parts, a homogeneous step size or a list of customized step sizes. By default (‘auto’), the function is the reverse of utils.stack().
Parameters: - axis ({'auto' | int | string}) –
Specify the data axis in which to perform the splitting operation. The axis can be specified using the index of the axis in axes_manager or the axis name. - If ‘auto’ and if the object has been created with utils.stack, split will return the former list of signals (options stored in ‘metadata._HyperSpy.Stacking_history’
else the last navigation axis will be used. - number_of_parts ({'auto' | int}) – Number of parts in which the SI will be splitted. The splitting is homegenous. When the axis size is not divisible by the number_of_parts the reminder data is lost without warning. If number_of_parts and step_sizes is ‘auto’, number_of_parts equals the length of the axis, step_sizes equals one and the axis is suppressed from each sub_spectra.
- step_sizes ({'auto' | list of ints | int}) – Size of the splitted parts. If ‘auto’, the step_sizes equals one. If int, the splitting is homogenous.
Examples
>>> s = hs.signals.Signal1D(random.random([4,3,2])) >>> s <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 splitted signals - axis ({'auto' | int | string}) –
-
squeeze
()¶ Remove single-dimensional entries from the shape of an array and the axes.
-
std
(axis=None, out=None)¶ 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.
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)¶ 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.
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)¶ 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. 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 [False]) – If the data should be re-ordered in memory, most likely making a copy. Ensures the fastest available iteration at the expense of memory.
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|)>
>>> s.transpose(signal_axes=5) # roll to leave 5 axes in navigation space <BaseSignal, title: , dimensions: (4, 3, 2, 1|9, 8, 7, 6, 5)>
>>> s.transpose(navigation_axes=3) # roll leave 3 axes in navigation space <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)¶ 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.
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)
-
var
(axis=None, out=None)¶ 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.
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=None, save_figures=False, factor_prefix='bss_factor', factor_format=None, loading_prefix='bss_loading', loading_format=None, comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, same_window=False, no_nans=True, per_row=3, save_figures_format='png')¶ Export results from ICA to any of the supported formats.
Parameters: - comp_ids (None, int, or list of ints) –
if None, returns all components/loadings. if int, returns components/loadings with ids from 0 to given
int.if list of ints, returns components/loadings with ids in iven list.
- folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.
- factor_prefix (string) – The prefix that any exported filenames for factors/components begin with
- factor_format (string) –
The extension of the format that you wish to save to. Determines the kind of output.
- For image formats (tif, png, jpg, etc.), plots are
- created
- using the plotting flags as below, and saved at 600 dpi. One plot per factor is saved.
- For multidimensional formats (rpl, hdf5), arrays are
- saved
- in single files. All factors are contained in the one file.
- For spectral formats (msa), each factor is saved to a separate file.
- loading_prefix (string) – The prefix that any exported filenames for factors/components begin with
- loading_format (string) – The extension of the format that you wish to save to.
- multiple_files (Bool) – If True, on exporting a file per factor and per loading will be created. Otherwise only two files will be created, one for the factors and another for the loadings. The default value can be chosen in the preferences.
- save_figures (Bool) – If True the same figures that are obtained when using the plot methods will be saved with 600 dpi resolution
- options (for save_figures = True ONLY) (Plotting) –
- ---------------------------------------------- –
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window.
- comp_label (string) – the label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window)
- cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.
- per_row (int, the number of plots in each row, when the) –
- same_window – parameter is True.
- save_figures_format (str) – The image format extension.
See also
get_bss_factors()
,get_bss_loadings.()
- comp_ids (None, int, or list of ints) –
-
export_decomposition_results
(comp_ids=None, folder=None, calibrate=True, factor_prefix='factor', factor_format=None, loading_prefix='loading', loading_format=None, comp_label=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, same_window=False, multiple_files=None, no_nans=True, per_row=3, save_figures=False, save_figures_format='png')¶ Export results from a decomposition to any of the supported formats.
Parameters: - comp_ids (None, int, or list of ints) – if None, returns all components/loadings. if int, returns components/loadings with ids from 0 to given int. if list of ints, returns components/loadings with ids in given list.
- folder (str or None) – The path to the folder where the file will be saved. If None the current folder is used by default.
- factor_prefix (string) – The prefix that any exported filenames for factors/components begin with
- factor_format (string) – The extension of the format that you wish to save to.
- loading_prefix (string) – The prefix that any exported filenames for factors/components begin with
- loading_format (string) –
The extension of the format that you wish to save to. Determines the kind of output.
- For image formats (tif, png, jpg, etc.), plots are
- created
- using the plotting flags as below, and saved at 600 dpi. One plot per loading is saved.
- For multidimensional formats (rpl, hdf5), arrays are
- saved
- in single files. All loadings are contained in the one file.
- For spectral formats (msa), each loading is saved to a separate file.
- multiple_files (Bool) –
- If True, on exporting a file per factor and per loading will
- be
created. Otherwise only two files will be created, one for the factors and another for the loadings. The default value can be chosen in the preferences.
- save_figures (Bool) – If True the same figures that are obtained when using the plot methods will be saved with 600 dpi resolution
- options (for save_figures = True ONLY) (Plotting) –
- ---------------------------------------------- –
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window.
- comp_label (string, the label that is either the plot title) – (if plotting in separate windows) or the label in the legend (if plotting in the same window)
- cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.
- per_row (int, the number of plots in each row, when the) –
- same_window – parameter is True.
- save_figures_format (str) – The image format extension.
See also
get_decomposition_factors()
,get_decomposition_loadings.()
-
get_bss_factors
()¶ Return the blind source separtion factors as a Signal.
See also
get_bss_loadings()
,export_bss_results.()
-
get_bss_loadings
()¶ Return the blind source separtion loadings as a Signal.
See also
get_bss_factors()
,export_bss_results.()
-
get_decomposition_factors
()¶ Return the decomposition factors as a Signal.
See also
get_decomposition_loadings()
,export_decomposition_results.()
-
get_decomposition_loadings
()¶ Return the decomposition loadings as a Signal.
See also
get_decomposition_factors()
,export_decomposition_results.()
-
plot_bss_factors
(comp_ids=None, calibrate=True, same_window=None, comp_label='BSS factor', per_row=3)¶ Plot factors from blind source separation results.
Parameters: - comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window. They are not scaled.
- comp_label (string, the label that is either the plot title) –
- plotting in ((if) – separate windows) or the label in the legend (if plotting in the same window)
- cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.
- per_row (int, the number of plots in each row, when the) –
- same_window – parameter is True.
See also
plot_bss_loadings()
,plot_bss_results.()
-
plot_bss_loadings
(comp_ids=None, calibrate=True, same_window=None, comp_label='BSS loading', with_factors=False, cmap=<matplotlib.colors.LinearSegmentedColormap object>, no_nans=False, per_row=3)¶ Plot loadings from ICA
Parameters: - comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window. They are not scaled.
- comp_label (string,) – The label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window). In this case, each loading line can be toggled on and off by clicking on the legended line.
- with_factors (bool) – If True, also returns figure(s) with the factors for the given comp_ids.
- cmap (matplotlib colormap) – The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic.
- no_nans (bool) – If True, removes NaN’s from the loading plots.
- per_row (int) – the number of plots in each row, when the same_window parameter is True.
See also
plot_bss_factors()
,plot_bss_results.()
-
plot_bss_results
(factors_navigator='auto', loadings_navigator='auto', factors_dim=2, loadings_dim=2)¶ Plot the blind source separation factors and loadings.
Unlike plot_bss_factors and plot_bss_loadings, this method displays one component at a time. Therefore it provides a more compact visualization than then other two methods. The loadings and factors are displayed in different windows and each has its own navigator/sliders to navigate them if they are multidimensional. The component index axis is syncronize between the two.
Parameters: - loadings_navigator (factor_navigator,) –
- Signal} – See plot documentation for details.
- loadings_dim (factors_dim,) – Currently HyperSpy cannot plot signals of dimension higher than two. Therefore, to visualize the BSS results when the factors or the loadings have signal dimension greater than 2 we can view the data as spectra(images) by setting this parameter to 1(2). (Default 2)
See also
plot_bss_factors()
,plot_bss_loadings()
,plot_decomposition_results.()
-
plot_decomposition_factors
(comp_ids=None, calibrate=True, same_window=None, comp_label='Decomposition factor', per_row=3)¶ Plot factors from a decomposition.
Parameters: - comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window. They are not scaled.
- comp_label (string, the label that is either the plot title) –
- plotting in ((if) – separate windows) or the label in the legend (if plotting in the same window)
- cmap (The colormap used for the factor image, or for peak) – characteristics, the colormap used for the scatter plot of some peak characteristic.
- per_row (int, the number of plots in each row, when the) –
- same_window – parameter is True.
See also
plot_decomposition_loadings()
,plot_decomposition_results.()
-
plot_decomposition_loadings
(comp_ids=None, calibrate=True, same_window=None, comp_label='Decomposition loading', with_factors=False, cmap=<matplotlib.colors.LinearSegmentedColormap object>, no_nans=False, per_row=3)¶ Plot loadings from PCA.
Parameters: - comp_ids (None, int, or list of ints) – if None, returns maps of all components. if int, returns maps of components with ids from 0 to given int. if list of ints, returns maps of components with ids in given list.
- calibrate (bool) – if True, calibrates plots where calibration is available from the axes_manager. If False, plots are in pixels/channels.
- same_window (bool) – if True, plots each factor to the same window. They are not scaled.
- comp_label (string,) – The label that is either the plot title (if plotting in separate windows) or the label in the legend (if plotting in the same window). In this case, each loading line can be toggled on and off by clicking on the legended line.
- with_factors (bool) – If True, also returns figure(s) with the factors for the given comp_ids.
- cmap (matplotlib colormap) – The colormap used for the factor image, or for peak characteristics, the colormap used for the scatter plot of some peak characteristic.
- no_nans (bool) – If True, removes NaN’s from the loading plots.
- per_row (int) – the number of plots in each row, when the same_window parameter is True.
See also
plot_decomposition_factors()
,plot_decomposition_results.()
-
plot_decomposition_results
(factors_navigator='auto', loadings_navigator='auto', factors_dim=2, loadings_dim=2)¶ Plot the decompostion factors and loadings.
Unlike plot_factors and plot_loadings, this method displays one component at a time. Therefore it provides a more compact visualization than then other two methods. The loadings and factors are displayed in different windows and each has its own navigator/sliders to navigate them if they are multidimensional. The component index axis is syncronize between the two.
Parameters: - loadings_navigator (factor_navigator,) –
- Signal} – See plot documentation for details.
- loadings_dim (factors_dim,) – Currently HyperSpy cannot plot signals of dimension higher than two. Therefore, to visualize the BSS results when the factors or the loadings have signal dimension greater than 2 we can view the data as spectra(images) by setting this parameter to 1(2). (Default 2)
See also
plot_factors()
,plot_loadings()
,plot_bss_results.()
-
-
class
hyperspy.signal.
ModelManager
(signal, dictionary=None)¶ Bases:
object
Container for models
-
class
ModelStub
(mm, name)¶ Bases:
object
-
ModelManager.
pop
(name)¶ Returns the restored model and removes it from storage
Parameters: name (string) – the name of the model to restore and remove
-
ModelManager.
remove
(name)¶ Removes the given model
Parameters: name (string) – the name of the model to remove
-
class
-
class
hyperspy.signal.
SpecialSlicersSignal
(obj, isNavigation)¶
hyperspy.signals module¶
The Signal class and its specilized subclasses:
- Signal
- For generic data with arbitrary signal_dimension. All other signal classes inherit from this one. It should only be used with none of the others is appropriated.
- Signal1D
- For generic data with signal_dimension equal 1, i.e. spectral data of n-dimensions. The signal is unbinned by default.
- Signal2D
- For generic data with signal_dimension equal 2, i.e. image data of n-dimensions. The signal is unbinned by default.
- 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.
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.