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 the Model2D.

A model is constructed as a linear combination of components that are added to the model using append() or extend(). There are many predefined components available in the in the components 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() or multifit(). Once the optimizer reaches the convergence criteria or the maximum number of iterations the new value of the component parameters are stored in the components.

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

signal

It contains the data to fit.

Type

BaseSignal instance

chisq

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

Type

A BaseSignal of floats

dof

Degrees of freedom of the signal (0 if not yet fit)

Type

A BaseSignal of integers

red_chisq

Reduced chi-squared.

Type

BaseSignal instance

components

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

Type

ModelComponents instance

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

    componentslist

    a list of dictionaries of components, one per

    _whitelistdictionary

    a dictionary with keys used as references for saved attributes, for more information, see hyperspy.misc.export_dictionary.export_to_dictionary()

    • any field from _whitelist.keys() *

Examples

>>> s = signals.Signal1D(np.random.random((10,100)))
>>> m = s.create_model()
>>> l1 = components1d.Lorentzian()
>>> l2 = components1d.Lorentzian()
>>> m.append(l1)
>>> m.append(l2)
>>> d = m.as_dictionary()
>>> m2 = s.create_model(dictionary=d)
as_signal(component_list=None, out_of_range_to_nan=True, show_progressbar=None, out=None, parallel=None)

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

Parameters
  • component_list (list of HyperSpy components, optional) – If a list of components is given, only the components given in the list is used in making the returned spectrum. The components can be specified by name, index or themselves.

  • out_of_range_to_nan (bool) – If True the spectral range that is not fitted is filled with nans. Default True.

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

  • out ({None, BaseSignal}) – The signal where to put the result into. Convenient for parallel processing. If None (default), creates a new one. If passed, it is assumed to be of correct shape and dtype and not checked.

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

Returns

BaseSignal

Return type

An instance of the same class as BaseSignal.

Examples

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

Set parameter values for all positions to the current ones.

Parameters
  • component_list (list of components, optional) – If a list of components is given, the operation will be performed only in the value of the parameters of the given components. The components can be specified by name, index or themselves.

  • mask (boolean numpy array or None, optional) – The operation won’t be performed where mask is True.

create_samfire(workers=None, setup=True, **kwargs)

Creates a SAMFire object.

Parameters
  • workers ({None, int}) – the number of workers to initialise. If zero, all computations will be done serially. If None (default), will attempt to use (number-of-cores - 1), however if just one core is available, will use one worker.

  • setup (bool) – if the setup should be run upon initialization.

  • **kwargs – Any that will be passed to the _setup and in turn SamfirePool.

disable_plot_components()
enable_plot_components()
ensure_parameters_in_bounds()

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

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

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

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

  • format (str) – The extension of the file format. It must be one of the fileformats supported by HyperSpy. The default is “hspy”.

  • save_std (bool) – If True, also the standard deviation will be saved.

  • only_free (bool) – If True, only the value of the parameters that are free will be exported.

  • only_active (bool) – If True, only the value of the active parameters will be exported.

Notes

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

extend(iterable)

Extend list by appending elements from the iterable.

fetch_stored_values(only_fixed=False)

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

Parameters

only_fixed (bool, optional) – If True, only the fixed parameters are fetched.

fetch_values_from_array(array, array_std=None)

Fetch the parameter values from the given array, optionally also fetching the standard deviations.

Parameters
  • array (array) – array with the parameter values

  • array_std ({None, array}) – array with the standard deviations of parameters

fit(fitter='leastsq', method='ls', grad=False, bounded=False, ext_bounding=False, update_plot=False, **kwargs)

Fits the model to the experimental data.

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

Parameters
  • fitter ({"leastsq", "mpfit", "odr", "Nelder-Mead",) –

    “Powell”, “CG”, “BFGS”, “Newton-CG”, “L-BFGS-B”, “TNC”,

    ”Differential Evolution”}

    The optimization algorithm used to perform the fitting. Default is “leastsq”.

    ”leastsq” performs least-squares optimization, and supports bounds on parameters.

    ”mpfit” performs least-squares using the Levenberg–Marquardt algorithm and supports bounds on parameters.

    ”odr” performs the optimization using the orthogonal distance regression algorithm. It does not support bounds.

    ”Nelder-Mead”, “Powell”, “CG”, “BFGS”, “Newton-CG”, “L-BFGS-B” and “TNC” are wrappers for scipy.optimize.minimize(). Only “L-BFGS-B” and “TNC” support bounds.

    ”Differential Evolution” is a global optimization method.

    ”leastsq”, “mpfit” and “odr” can estimate the standard deviation of the estimated value of the parameters if the “metada.Signal.Noise_properties.variance” attribute is defined. Note that if it is not defined, the standard deviation is estimated using a variance of 1. If the noise is heteroscedastic, this can result in a biased estimation of the parameter values and errors. If variance is a Signal instance of the same navigation_dimension as the signal, and method is “ls”, then weighted least squares is performed.

  • method ({'ls', 'ml', 'custom'}) – 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”. ‘custom’ allows passing your own minimisation function as a kwarg “min_function”, with optional gradient kwarg “min_function_grad”. See User Guide for details.

  • 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

multifit()

gui(display=True, toolkit=None, **kwargs)

Display or return interactive GUI element if available.

Parameters
  • display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

  • toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.

insert(**kwargs)

Insert object before index.

load_parameters_from_file(filename)

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

Parameters

filename (str) –

Notes

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

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

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

Parameters
  • mask (NumPy array, optional) – To mask (do not fit) at certain position pass a numpy.array of type bool where True indicates that the data will not be fitted at the given position.

  • fetch_only_fixed (bool) – If True, only the fixed parameters values will be updated when changing the positon. Default False.

  • autosave (bool) – If True, the result of the fit will be saved automatically with a frequency defined by autosave_every. Default False.

  • autosave_every (int) – Save the result of fitting every given number of spectra. Default 10.

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

  • 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

fit()

plot_results(only_free=True, only_active=True)

Plot the value of the parameters of the model

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

  • only_active (bool) – If True, only the value of the active parameters will be plotted.

Notes

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

print_current_values(only_free=True, skip_multi=False, component_list=None)

Print the value of each parameter of the model.

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

  • skip_multi (bool) – If True, parameters with attribute “__iter__” are not printed

  • component_list (None or list of components.) – If None, print all components.

property 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) –

Notes

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

set_boundaries()

Generate the boundary list.

Necessary before fitting with a boundary aware optimizer.

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

Sets the component ‘active’ parameter to a specified value

Parameters
  • value (bool) – The new value of the ‘active’ parameter

  • component_list (list of hyperspy components, optional) – A list of components whose parameters will changed. The components can be specified by name, index or themselves.

  • only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.

Examples

>>> v1 = hs.model.components1D.Voigt()
>>> v2 = hs.model.components1D.Voigt()
>>> m.extend([v1,v2])
>>> m.set_component_active_value(False)
>>> m.set_component_active_value(True, component_list=[v1])
>>> m.set_component_active_value(False, component_list=[v1],
                                 only_current=True)
set_mpfit_parameters_info()
set_parameters_free(component_list=None, parameter_name_list=None)

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

Parameters
  • component_list (None, or list of hyperspy components, optional) – If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves.

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

Examples

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

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

Parameters
  • component_list (None, or list of hyperspy components, optional) – If None, will apply the function to all components in the model. If list of components, will apply the functions to the components in the list. The components can be specified by name, index or themselves.

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

Examples

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

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

Parameters
  • parameter_name (string) – Name of the parameter whose value will be changed

  • value (number) – The new value of the parameter

  • component_list (list of hyperspy components, optional) – A list of components whose parameters will changed. The components can be specified by name, index or themselves.

  • only_current (bool, default False) – If True, will only change the parameter value at the current position in the model. If False, will change the parameter value for all the positions.

Examples

>>> v1 = hs.model.components1D.Voigt()
>>> v2 = hs.model.components1D.Voigt()
>>> m.extend([v1,v2])
>>> m.set_parameters_value('area', 5)
>>> m.set_parameters_value('area', 5, component_list=[v1])
>>> m.set_parameters_value('area', 5, component_list=[v1],
                           only_current=True)
store(name=None)

Stores current model in the original signal

Parameters

name ({None, str}) – Stored model name. Auto-generated if left empty

store_current_values()

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

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

suspend_update(update_on_resume=True)

Prevents plot from updating until ‘with’ clause completes.

See also

update_plot()

update_plot(*args, **kwargs)

Update model plot.

The updating can be suspended using suspend_update.

See also

suspend_update()

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.model.components = <hyperspy.model.DummyComponentsContainer object>
hyperspy.model.reconstruct_component(comp_dictionary, **init_args)