pyEELSMODEL.core package

Submodules

pyEELSMODEL.core.component module

copyright University of Antwerp 2021 author: Jo Verbeeck and Daen Jannis

class pyEELSMODEL.core.component.Component(spectrumshape, params=None)

Bases: Spectrum

A Component is a Spectrum that can calculate itself from a number of parameters. Base class from which all components can be derived with specific functionality

calculate()

This calculates the spectral data of the component. Each derived class from Component will need to implement its own functionality here.

Return type:

None.

get_ismultiplier()
getcanconvolute()

Gets wether this component can be convoluted

Parameters:

None.

Return type:

None.

getdescription()

Get a string describing the functionality of the component. Can be used in e.g. help or tooltips in the UI.

Returns:

String describing the functionality.

Return type:

string

getdisplayname()

Get the friendly name of a component. This name can be changed by the user and will typically be used for designating the component in eg. a user interface.

Returns:

A name describing this component.

Return type:

string

getgradient(parameter)

Get a reference to the gradient of this component with respect to parameter, if an analytical gradient is available. This function needs to be overoaded for every specific component

Parameters:

parameter (Parameter) – Reference to an existing parameter in the component.

Returns:

  • A reference to a Spectrum holding the gradient if the parameter was

  • indeed a parameter of this component and has an analytical gradient

  • defined gradient. None in all other cases.

gethasmultiplier()
getmultiplier()

Return a reference to a Multiplier Component if one is attached to this component Otherwise returns None. Multiplier components can be used e.g. to mimick effect of gain variation of a camera.

Raises:

AttributeError – DESCRIPTION.

Returns:

multiplier – Reference to another component which is indicated to be a multiplier of this component.

Return type:

Component

getname()

Get the official and fixed name of a component. This name is a unique identifier of the type of component. This name should not be changed by the user.

Returns:

Unque identifier name of the component.

Return type:

string

getparameter(index)

Return the parameter with index.

Parameters:

index (int) – Index to indicate which parameter to return

Raises:
  • ValueError – When index out of bounds.

  • TypeError – When index is not int

Returns:

Reference to the requested Parameter in the params list.

Return type:

Parameter

getshifter()

Get whether this is a shifter component

Returns:

True if shifter type component.

Return type:

bool

has_parameter(p)
Search if Parameter p is one of the parameters in the parameter list of

this component.

Parameters:

p (Parameter) – Reference to input parameter to find in the parameter list of this component.

Raises:

TypeError – In case p is not a Parameter object.

Returns:

True if parameter p indeed is one of the parameters of this component, False otherwise.

Return type:

bool

indexOK(index)

Check if index is within range of params list

Parameters:

index (int) – index.

Returns:

True: index is good,, False otherwise.

Return type:

bool

ischanged()
load(fh)

Loads different types of data. The possible datatypes are: .hdf5, .hspy, .dm3/.dm4 and .msa.

Parameters:
  • filename (string) – String of the filename where the extention should be ‘.hdf5’

  • flip_sign (boolean) – Indicates whether the offset value should be negative when loading a .dm file. (default: False)

Returns:

s – The spectrum which is contained in the filename

Return type:

Spectrum

print_parameter_values()

Print all parameters of a component as name : value

Return type:

None.

release()
releasemultiplier()
save(fh)
setchanged()

Mark all parameters as changed. This notifies the component that on the next component.calculate() call, the full component needs to be recalculated. Note that it even marks unchangeable Parameters as changed even though their value doesnt.

Return type:

None.

setdescription(description)

Set the description string of the component. This is typically the business of the component itself, but can be changed by the user. The description can be used e.g. inthe UI to provide help explaining the function of the component

Parameters:

description (string) – A description of what the component does.

Return type:

None.

setdisplayname(name)

Sets the displayed name of the component. This name can differ from the actual name of the component and allows the user to change the name to a more meaningful name without affecting the official name that should not change.

Parameters:

name (string) – Display name for the component.

Return type:

None.

seteshift(eshift)

Sets an energy shift for this component which shifts its energy values with respect to the energy axis given when instantiating the component. This can be used to mimick experimental energy drift. In order to make sure the component gets a full recalculation at the next calculate() call, all parameters will be indicated as changed.

Parameters:

eshift (float) – energy shift.

Return type:

None.

sethasmultiplier(b)
setmultiplier(component)

Set a multiplier component to this component. The component needs to be of the multiplier type. The multiplier component will take the output of this component and multiply it with its content

Parameters:

component (Component) – The component which needs to be set as multiplier.

Raises:

AttributeError – DESCRIPTION.

Return type:

None.

setunchanged()

Set all parameters of a Component as unchanged. This is typically done internally after a component.calculate() but can also be called externally to avoid that a component will be recalculated if fiddling with some parameters externally. Note however that if you call this function, the next time you call recalculate the component will falsely assume that it doesnt need to do anything as the parameters are marked as unchanged!

Return type:

None.

setvisible(b)

Sets the visible state of the component. Can indicate whether in a model spectrum showing individual components, this component needs to be visible or not. default True.

Parameters:

b (bool) – visible state.

Return type:

None.

show()

Plot component contents if the component has isvisible==True

Return type:

None.

pyEELSMODEL.core.fitter module

Created on Thu Dec 9 20:46:09 2021

@author: joverbee

class pyEELSMODEL.core.fitter.Fitter(spectrum, model)

Bases: object

Fitter class from which all actual fitters can be derived.

many things are in common for all fitters like:

-calculate goodness of fit (actual implementation can be overridden eg difference between weighted least square or lsq or poisson specific) -do iterations until certain goodness of fit is reached -calculate degrees of freedom -calculate crlb -

CRLB(par, index=None)

Returns the CRLB bound of the parameter par. If the spectrum is a multispectrum, the results for the different spectra can be modified by inputting another index.

Parameters:
  • par (Parameter) – A parameter which is used in the model to fit the data

  • index (tuple) – The index of the spectrum from which we want the CRLB. Only works when the given spectrum is a multispectrum (default: use the current index).

Returns:

CRLB – The CRLB for the given parameter and spectrum.

Return type:

float

CRLB_map(par)

Returns the CRLB bound of the parameter par. For each scanned point. This only works when a multispectrum is fitted.

Parameters:

par (Parameter) – A parameter which is used in the model to fit the data

Returns:

crlb_map – The CRLB map the given parameter.

Return type:

numpy array (2D)

CRLB_ratio(par1, par2, index=(0, 0))

Returns the CRLB bound of the ratio between par1 and par2 (par1/par2). The results for the different spectra can be modified by inputting another index.

Parameters:
  • par1 (Parameter) – A parameter which is used in the model to fit the data

  • par2 (Parameter) – A parameter which is used in the model to fit the data

  • index (tuple) – The index of the spectrum from which we want the CRLB. Only works when the given spectrum is a multispectrum (default: (0,0)).

Returns:

error – The CRLB bound calculated for the ratio between two parameters.

Return type:

float

LRtestconfidence(index=(0, 0))

Confidence test using the likelyhood ratio of Poisson noise. See publication EELSmodel for explanation on this

LRtestconfidence_string()
calculate_derivmatrix()

Calculates the derivative matrix where each row is a derivative of the model spectrum to a free parameter. The number of columns depends on the size of the spectrum.

Returns:

deriv_matrix – The derivative matrix for each fitted parameter.

Return type:

numpy array (2D)

candolintrick()
property covariance_matrix
createmodelinfo()
degreesoffreedom()

Returns the number of degrees of freedom in the fitter. This depends on the number of free parameters in the model and the number of fitted points in the spectrum

dolintrick(b)
property fittertype
get_bounds()
get_experimental_edge(component, percentile, plotting=False, other_spectra=[])

Calculate the proposed edge when using a multispectrum. The percentile takes the spectra having the highest content of these edges.

Returns:

get_jump_ratio_map(component, onset_energy, interval=10)

Returns a map with the jump ratio between the background and edge calculated by integrating over interval region. This is an experimental function which needs to be more tested and explored.

get_map(param)

Returns the fitted coefficients of the parameter param. This only work if a multispectrum is used to fit.

Parameters:

param (Parameter) – A parameter which is optimized and from which the resulting map is requested.

Returns:

param_map – The coefficient map of the given parameters

Return type:

2d numpy array

get_map_results(comp_elements)

Calculates the maps of the elements.

Parameters:

comp_elements (list) – List containing the components used in the model which have been fitted.

Returns:

  • maps (numpy array) – Contains all the different maps where the indices are the same as the list of components.

  • names (list) – List containing the name for each map. These returns are mainly used for modifying the images if more advanced figures need to be created for publications or reports.

get_param_index(param)

Returns the index of the parameter in the free parameter list. This function is used to ask the fitted value for which parameter. If the given is not in the list it returns None

Parameters:

param (Parameter) – The parameter from which we want to get the index

Returns:

index – The index which corresponds to the given parameter in the fit.

Return type:

int or None

get_start_parameters()
getdolintrick()
getdoresidual()
getlabelist()
getstatus()
gettolerance()
property information_matrix
likelihood_ratio(index=(0, 0))

Defined likelihood ratio from: 10.1016/j.ultramic.2004.06.004 The index will be used when using a multispectrum.

Parameters:

index (tuple) – A tuple showing the index of the used spectrum for the likelihood ratio calculation.

Return type:

None

property model
model_to_multispectrum()

After the fitting of the multispectrum with the given model, the resulting model at every probe position is calculated which will be a multispectrum.

Returns:

sig – The fitted multispectrum at each probe position.

Return type:

MultiSpectrum

model_to_multispectrum_with_comps(comps)

Only uses the components in comps to calculate the fitted model. Similar to model_to_multispectrum_without_comps but the exact opposite

Parameters:

comps (list of Components) – List of components are only used in the calculation of the fit.

Returns:

sig

The fitted multispectrum at each probe position only have the given

components in comps.

Return type:

MultiSpectrum

model_to_multispectrum_without_comps(comps)

Set the parameter values to zero for the components in comps and calculates the fitted model. This can be used to remove the background from the fitted result or to only have the background.

Parameters:

comps (list of Components) – List of components which should not be added to the calcualted model.

Returns:

sig – The fitted multispectrum at each probe position without the given components in comp.

Return type:

MultiSpectrum

multi_LRtestconficence()
multi_fit(start_param=None)

Performs the selected fit over each spectrum in the multispectrum.

Parameters:

start_param (list) – List of starting parameters for the fit. If None, the values of the model are used. The shape of the start_param should be of size (xsize, ysize, numberoffreeparamters). The starting parameters are only needed for the non-linear models.

multi_likelihood_ratio()
numerical_partial_derivative(parameter, fraction=0.001)

Calculates the numerical partial derivative of the parameter.

Parameters:
  • parameter (Parameter) – The parameter from which the numerical derivative will be calculated.

  • fraction (float) – The fraction of the step the parameter does to calculate the numerical gradient (default: 0.001)

partial_derivative(parameter, fraction=0.001)

Calculates the partial derivative of the parameter. It uses the use_gradient attribute to check if the gradient is calculated analytically or numerically.

Parameters:
  • parameter (Parameter) – The parameter from which the partial derivative will be calculated.

  • fraction (float) – The fraction of the step the parameter does to calculate the numerical gradient. (default: 0.001)

Returns:

parial – The partial derivative for the given parameter.

Return type:

numpy array (1D)

plot(index=None, externalplt=None, non_components=[], **kwargs)

Plots the fitter

Parameters:

externalplt (matplotlib reference) – A reference to an external matplotlib reference, if None we use our own matplotlib and create a new figure.

Returns:

fig

Return type:

Figure

set_bounds()

Sets the boundaries for the fitting. It uses the boundaries from each free parameter in the model to get these values.

set_fit_values()

Function which set the fitting values to the model.

set_information_matrix()

Calculates the fischer information matrix followed by formula (16) in https://doi.org/10.1016/j.ultramic.2004.06.004 Used for Poisson noise

set_start_parameters()

Gets the start parameters of the model as initial parameters for the fitting. This function is used when starting values need to be added to the fit.

Returns:

start_param – A list containing the starting values for the fitting

Return type:

List

setcurrentfit(index=(0, 0))

Set the fit to the used index. It will recalculate the model and information matrix for the used index. If the index has not changed, it will not perform any calculation to reduce the calculation time.

Parameters:

index (tuple) – A tuple showing the index of the used spectrum.

Return type:

None

setdoresidual(b)
setfraction(x)
setmaxstep(x)
setminstep(x)
setnmax(n)
settolerance(t)
setusegradients(b)
show_coefficients(index=(0, 0))
show_covariance_matrix()

Shows the covariance matrix and adds the labels of the different components.

Returns:

fig

Return type:

Figure

show_map_result(comp_elements)

Shows the maps for the given components in the list. Note that it only uses the first free parameter of the component. Hence this is mainly used for visualization of the elements maps where the components of the coreloss edges have only one parameter which needs to be fitted.

Parameters:

comp_elements (list) – List containing the components used in the model which have been fitted.

Returns:

  • fig (matplotlib figure) – The figure which is created. This way you can save it or modify it if needed.

  • maps (numpy array) – Contains all the different maps where the indices are the same as the list of components.

  • names (list) – List containing the name for each map. These returns are mainly used for modifying the images if more advanced figures need to be created for publications or reports.

show_variance()

Shows the variance and adds the labels of the different components.

Returns:

fig

Return type:

Figure

property usegradients

pyEELSMODEL.core.model module

copyright University of Antwerp 2021 author: Jo Verbeeck and Daen Jannis

class pyEELSMODEL.core.model.Model(spectrumshape, components=None)

Bases: Spectrum

Model class A Model is a Spectrum that can calculate itself based on a number of Components which each depend on a number of Parameters. Note that all actions like convolving with low loss, adding or multiplying stuff is encoded in the Components, some of which are special types which tells the model how to treat them to come up with a single model result. Philosophy of Model: a model with a number of parameters mimicking an EELS experiment. Everything that happens in experiments needs to be modelled somehow by the components in the model. The model doesnt care whether the spectrum it simulates is a single spectrum or an SI. It is the task of the fitter to deal with the parameters for each position in an SI (different from cpp EELSMODEL!)

addcomponent(component)
calculate(use_ll=True)

Calculate the model by calculating all components. For the linear least squares fitting it would be interesting to not use the low loss for computing the model since we can do the low loss convolution at a later step to improve speed for the linear fitting.

Parameters:

use_ll (boolean) – Indicates if it needs to use the low loss for calculating the model.

Raises:

ValueError – DESCRIPTION.

Return type:

None.

componentshow()

show contents of all component in a separate graph if they are visible

getallparameters()
getcomponentbyparameter(parameter)

Get component that belongs to a given parameter reference.

Parameters:

parameter (Parameter) – Reference to a parameter.

Returns:

comp – reference to a component that has this parameter reference. None if parameter not found in any component in the model.

Return type:

Component

getcomponents()
getconvolutor()
getfreelinparameters()
getfreenonlinparameters()
getfreeparameters()
getgradient(parameter)
getnumcomponents()

Return the number of components in the model.

Returns:

Number of components in the model.

Return type:

int

getnumfreeparameters()

Get total number of free parameters in the model.

Returns:

n_free – Number of free parameters in the model.

Return type:

int

getnumparameters()

Get total number of parameters in the model. This includes the free and the non-free parameters.

Returns:

n_param – Number of parameters in the model.

Return type:

int

hasconvolutor()
hasmultiplier()
hasshifter()
ischanged()
islinear()

Returns whether all free parameters in the model are linear. If this is the case we have a full linear model which allows the use of a linear fitter.

Returns:

boolean – True if linear model, False otherwise.

Return type:

bool

islocked()
lock(b)

Set the locked state of the model. If the model is locked, no components can be added or removed. This is useful during fitting where the model structure should not change.

Parameters:

b (bool) – True=locked, False is unlocked.

Return type:

None.

order_coupled_components()

The components which have parameters which are coupled to other parameters should be first calculated in the model. Therefore the component list should be ordered such that first the coupled parameters are calculated and then the rest.

plot(spectrum=None, externalplt=None, **kwargs)

Plot the Model

Parameters:
  • spectrum (Spectrum) – A spectrum can be plotted simultaneously

  • externalplt (matplotlib reference) – A reference to an external matplotlib reference, if None we use our own matplotlib and create a new figure.

prepare()

Reallocate space to hold parameters. Needs to be called every time the number of components or state of parameters (changeable or linear) changes. The parameterlists are what is handled by the fitter. So good time to call this function is right before a fitting loop to make sure we are working with an up to date status of all parameters. Changing parameter status (changeble or linear) during a fit should not be allowed in the UI. Calling this everytime before calculate would be too time consuming.

Return type:

None.

printcomponents()

Print a list summarising all components.

Return type:

None.

release()
removecomponent(component)

Removes a component from the model.

Parameters:

component (Component) – The component which needs to be removed.

Return type:

None.

resetsigmas()

Reset the error bars on all parameters.

Return type:

None.

savemodel()
saveparams(filehandle, fmt='txt', header=True)

Store all current parameters in a file that is already open this allows to append the parameters of all estimated params in a spectrum image in one big file. TODO work eg with elementtree for XML writing

Parameters:
  • filename (TYPE) – DESCRIPTION.

  • fmt (TYPE, optional) – DESCRIPTION. The default is ‘txt’.

Return type:

None.

setchanged(b)
seteshift(energy)

pyEELSMODEL.core.multispectrum module

copyright University of Antwerp 2021 author: Jo Verbeeck and Daen Jannis

class pyEELSMODEL.core.multispectrum.MultiSpectrum(multispectrumshape, data=None, acq_time=0)

Bases: Spectrum

apply_dark(dark_name)

Remove the dark reference from the detector. This is done on the data of the spectrum itself and no new Spectrum object is created.

Parameters:

dark_name (string) – The filename where the dark reference is stored

apply_dark_and_gain(gain_name, dark_name)

Apply dark and gain. The dark and gain can be saved as a numpy array and applied to the spectrum. This is done on the data of the spectrum itself and no new Spectrum object is created. It assumes that the gain and dark is stored as a .npy file

Parameters:
  • gain_name (string) – The filename where the gain is stored.

  • dark_name (string) – The filename where the dark reference is stored

copy()

Returns a copy of the object

erase()
firstderivative()

Calculates the first derivative of the multispectrum with respect to the energy axis. At this point I do not see any reason on implementing this for the scanning dimensions.

Returns:

s – The first derivative for the multispectrum

Return type:

MultiSpectrum

classmethod from_numpy(data_array, energy_axis)

Creates an Multispectrum object from the data and energy axis using numpy arrays. Usefull when playing with different functions which are not (yet) integrated into pyEELSmodel functionalities.

Parameters:
  • data_array (numpy array (1D)) – The data of the EEL spectrum.

  • energy_axis (numpy array (1D)) – The energy axis used [eV]

Returns:

s – The multispectrum which is inside the filename

Return type:

MultiSpectrum

gaussian_3d(X, Y, Z, sigma)

Computes the 3 dimensional gaussian where sigma can be non isotropic.

Parameters:
  • X (numpy array (3D)) – Meshgrid indicating the x coordinate of the mesh.

  • Y (numpy array (3D)) – Meshgrid indicating the x coordinate of the mesh.

  • Z (numpy array (3D)) – Meshgrid indicating the x coordinate of the mesh.

  • sigma (tuple of floats) – Tuple of length 3 of the sigmas of each gaussian.

Returns:

f – Three dimensional gaussian.

Return type:

numpy array (3D)

gaussiansmooth(sigma, crop=False)

Uses the 3D FFT to compute a gaussian blurred EELS map. Note the this performs a 3d fft which makes that the computation needs a lot of RAM

Parameters:
  • sigma ([a1, a2, a3]) – The sigma value of the 3d gaussian.

  • crop (boolean) – Indicates whether the filtered spectrum will be

Returns:

cop – The gaussian smoothed multispectrum

Return type:

MultiSpectrum

get_interval(interval, even_size=True)
Parameters:
  • interval (tuple) – Interval which has the start and end of the sub spectrum

  • even_size (bool) –

    Makes the size of the returned multispectrum even to accomodate for

    a fast low loss convolution

Raises:
  • ValueError – In case both spectra don’t have the same spectrumshape settings (in which case divide makes no sense).

  • TypeError – In case other is neither a Spectrum, int or float.

Returns:

s – Returns a reference to a -new- spectrum that is the division result.

Return type:

MultiSpectrum

get_multispectrumshape()
geteshift()

Get energy shift. This shift allows to move the whole energy scale up and down by calling seteshift(energy)

Returns:

DESCRIPTION.

Return type:

TYPE

indexOK(id)

Index is valid for the scan dimensions of the EELS map

Parameters:

id (tuple int) – Check if the given index is valid.

Returns:

Returns True if the index is valid.

Return type:

bool

integrate(window=None, index_type=False)

Integrates the signal over the given energy window or the given index.

Parameters:
  • window (tuple) – The window over which to integrate. If index_type is True, the integration window is given with the index instead of energy. If window is None, the integral over the entire energy range is given.

  • index_type (bool) – Indicates if the window should be interpreted as the indices or the energy of the spectrum

Returns:

result – The value of the integration

Return type:

numpy array of float of sizex,sizey

classmethod load(filename, flip_sign=False)

Loads different types of data. The possible datatypes are: .hdf5, .hspy, .dm3/.dm4 and .msa.

Parameters:
  • filename (string) – String of the filename where the extention should be ‘.hdf5’

  • flip_sign (boolean) – Indicates whether the offset value should be negative when loading a .dm file. (default: False)

Returns:

s – The spectrum which is contained in the filename

Return type:

Spectrum

classmethod load_dm(filename, flip_sign=False, dispersion=None)

Loading dm data

Parameters:
  • filename (string) – Filename containing the data.

  • flip_sign (boolean) – Bug when loading in data where the energy axis starts negative. If wrong is set to True, then this bug is worked around.

  • dispersion (float) – Sometimes the dispersion in dual EELS is different, this is a method to force it to be the same.

Returns:

s – The multispectrum which is inside the filename

Return type:

MultiSpectrum

classmethod load_hdf5(filename)

Loads the multispectrum from .hdf5 file

Parameters:

filename (string) – Filename containing the data.

Returns:

s – The multispectrum which is inside the filename

Return type:

MultiSpectrum

classmethod load_hspy(filename)

Loads hyperspy data file format.

Parameters:

filename (string) – Filename containing the data.

Returns:

  • s (MultiSpectrum) – The multispectrum which is inside the filename

  • df (list) – List containing other acquired data

map_to_line()

Make a map into a line scan :return:

mean(axis=(0, 1))

Mean the real space coordinates with each other. When summed over both direction, a single spectrum is returned instead of a multispectrum

Parameters:

axis (tuple) – The axis over which the mean needs to be performed.

Returns:

s – The summed multispectrum or spectrum

Return type:

MultiSpectrum/Spectrum

property multidata
plot(index=None, externalplt=None, **kwargs)

Plot the spectrum

Parameters:

externalplt (matplotlib reference) – A reference to an external matplotlib reference, if None we use our own matplotlib and create a new figure.

rebin(factor)

Rebins the dataset with given factor which contains three uints indicating the binning factor for each dimension. Rebinning is performed by convoluting the dataset with a tophat function of given size. This makes that some edge artifacts will remain.

Parameters:

factor ([a1, a2, a3]) – The three binning factors. The values of a1, a2 and a3 >= 1 and integer.

Return type:

None.

save_hdf5(filename, metadata=None, overwrite=False)

Saves the spectrum as a hdf5 file. The structure of the file can easily be investigated via a hdfview software.

Parameters:
  • filename (string) – filename of the saved file.

  • metadata (dictionary) – A dictionary containing E0, alpha, beta, elements and edges can be added to the hdf5 file. If None is given, nothing will be saved.

  • overwrite (boolean) – Indicates if the file will be overwritten if it already exists. (default: False)

Return type:

If the file saving workes, a True value is returned.

secondderivative()

Calculates the second derivative of the multispectrum with respect to the energy axis.

Returns:

s – The second derivative for the multispectrum

Return type:

MultiSpectrum

setcurrentmeanspectrum(index, width, height)

Sets the current mean spectrum to the given index using the proper width and height. Usefull for the GUI.

Parameters:

index (tuple) – The index to which the multispectrum is set.

Return type:

None

setcurrentspectrum(index)

Sets the current spectrum to the given index

Parameters:

index (tuple) – The index to which the multispectrum is set.

Return type:

None

show_excluded_region(**kwargs)

Shows the points which are excluded from the fit.

sum(axis=(0, 1))

Sum the real space coordinates with each other. When summed over both direction, a single spectrum is returned instead of a multispectrum

Parameters:

axis (tuple) – The axis over which the sum needs to be performed.

Returns:

m – The summed multispectrum or spectrum

Return type:

MultiSpectrum/Spectrum

swap_xy()

Function which will swap the x and y coordinates of the scan and return this as a new multispectrum.

Returns:

to_logarithm()
upsample(nn)

Upsamples the spectrum with factor nn.

Parameters:

nn (uint) – The number of times the spectrum needs to be upsampled

Returns:

spec_up – The upsampled multispectrum

Return type:

MultiSpectrum

class pyEELSMODEL.core.multispectrum.MultiSpectrumIterator(multispectrum)

Bases: object

MultiSpectrum Iterator class

class pyEELSMODEL.core.multispectrum.MultiSpectrumshape(dispersion, offset, Esize, xsize, ysize)

Bases: object

MultiSpectrumshape is a class holding the main parameters of a spectrum in order to compactly create several spectra with the same size by providing an instance of this class. It holds:

dispersion: float, dispersion in eV/pixel describing the energy scale offset: float, energy of the first pixel in the spectrum in eV size: int, the size of a spectrum in number of pixels (eg typ 1024) xsize: int number of spectra in x direction ysize: int number of spectra in y direction

getspectrumshape()

pyEELSMODEL.core.operator module

Created on Thu Dec 9 20:46:09 2021

@author: joverbee

class pyEELSMODEL.core.operator.Operator

Bases: object

Operator class from which all other operations on the spectrum class are derived

pyEELSMODEL.core.parameter module

copyright University of Antwerp 2021 author: Jo Verbeeck and Daen Jannis

class pyEELSMODEL.core.parameter.Parameter(name, val, changeallowed=True)

Bases: object

Parameter class to store a parameter to be used in e.g. a component that typically has a list of parameters. Parameters hold a single numerical value, can have lower and upper boundaries, can be locked can be coupled to other parameters, can have the ‘linear’ property, indicating that in a component this parameter is linear as opposed to a nonlinear parameter that affects the component in a nonlinear way. Parameters can also be monitored by a Monitor class and they can be watched by a Watcher class

boundaryOK(x, lb, ub)

Check if a proposed value x is within the bounds given by lower bound (lb) and upper bound (ub).

Parameters:
  • x (float) – value to be tested.

  • lb (float) – lower bound.

  • ub (float) – upper bound.

Returns:

returns True if x is within bounds OR if the parameter is not bound.

Return type:

bool

copy()

Returns a copy of the object :return:

couple(parameter, fraction=1.0)

Couples this parameter to another parameter with a certain coupling constant. This will make us into slaves of the master parameter that is passed. We no longer will be changeable and a call to getvalue() will result in the value of the controller parameter.

Parameters:
  • parameter (Parameter) – reference a another parameter to couple to.

  • fraction (float, optional) – coupling constant. The default is 1.0.

Return type:

None.

getcontroller()

Get a reference to the controller parameter if this is a coupled worker.

Returns:

  • Parameter – reference to a master Parameter instance if we are a coupled worker.

  • None – if we are not a coupled worker.

getcouplingfactor()

Return the current value of the coupling factor, irrespective of whether the parameter is actually coupled or not.

Returns:

value of the coupling factor.

Return type:

float

gethasgradient()
getlowerbound()

Returns the current lower bound.

Returns:

lower bound value.

Return type:

float

getname()

Get name string including “coupled to:” in case this parameter is coupled.

Returns:

the name of the parameter including ‘coupled to…’ in case the parameter is coupled.

Return type:

string

getpurename()

Get the ‘pure’ name of the parameter. This is the exact name as given with setname() or during init() and doesnt include any info on eventual coupling to another parameter.

Returns:

The name of the parameter.

Return type:

string

getupperbound()

Returns the current upper bound.

Returns:

upper bound value.

Return type:

float

getvalue()

Gets the current value of the Parameter. If the parameter is a coupled slave, the value of the master times a coupling constant will be returned

Returns:

Value of parameter or of the master parameter times a coupling

constant if this is a coupled slave.

Return type:

float

interactivevalue(description)

Not implemented.

isbound()

Returns whether a parameter has active bounds.

Returns:

True if parameter is bound, False otherwise.

Return type:

bool

ischangeable()

Returns wether a parameter is changeable with setvalue().

Returns:

True if parameter can be changed, False otherwise.

Return type:

bool

ischanged()

Returns wether a parameter is indicated as changed (typically since last time eg. a Component used it for calculation).

Returns:

True if parameter has changed, False otherwise.

Return type:

bool

iscoupled()

Returns whether a parameter is coupled to another parameter. Checks are performed to see if the coupled parameter is still valid.

Returns:

True if coupled, False otherwise.

Return type:

bool

isdisplayed()
Return whether the parameter is marked as ‘displayed’. This can be set

with setdisplayed(True/False)

Returns:

True is displayed state is set, False otherwise.

Return type:

bool

islinear()

Returns whether this parameter is indicated as linear. This is used e.g. by a model to check if a linear fit can be used (all free parameters are linear) instead of a nonlinear.

Returns:

True if parameter is indicated as linear, False otherwise.

Return type:

bool

printall()

Print some details on the parameter, mostly for debugging and testing.

Return type:

None.

release()

Call this function whenever you no longer need this parameter it warns other coupled Parameter, Monitor and Watcher instances that might be linked to it that they should no longer count on this parameter.

Return type:

None.

releasecoupling()

Stops any coupling of this parameter with another

Return type:

None.

setboundaries(lb, ub, force=False)

Sets numerical boundaries to the parameter but only if the current value fits within those boundaries. The boundaries are inclusive >= and <=. Swapping lower for upper boundary is allowed and will automatically be corrected. If force is True, the value of the parameter will be changed to make the boundaries work.

Parameters:
  • lb (float) – lower boundary.

  • ub (float) – upper boundary.

  • force (bool) – If force is true, then the boundaries are set even if the value of the parameter falls outside this boundary. The new value of the parameter will be set in the center of the boundaries. (default: True)

Returns:

True if bound, False otherwise.

Return type:

bool

setchangeable(b)

Set the changeable state of the parameter. If not changeable, the parameter value can not be updated. This can be used to indicate to a Model which are free parameters and which parameters are fixed.

Parameters:

b (bool) – True if parameter can be changed, False if it can’t be changed.

Return type:

None.

setchanged()

Force the parameter to a changed state. This is useful to e.g. set a coupled slave parameter to the changed state even though that parameter is typically unchangeable as it should follow the master. This is important as a component needs to know that this parameter has changed in order to force a full recalculation when recalculate is called. This can also be used to force a recalculate of a Component as changed parameters will avoid that the Component takes a shortcut because it thinks it already calculated with this parameter value.

Return type:

None.

setdefaults()

Sets default values, typically only called in __init__

Return type:

None.

setdisplayed(b)

Set the displayed state of the parameter. This can be used from a UI to indicate if the UI has to be informed if e.g. something changes.

Parameters:

b (bool) – True if displayed on a UI, False otherwise.

Return type:

None.

sethasgradient(b)
setlinear(b)

Sets a boolean variable to indicate whether a parameter is linear or not. This can be used e.g. by the Fitter to know if a pure linear Model (all free parameters are linear) is present which allows to use a much faster fitting algorithm.

Parameters:

b (bool) – True for linear parameter, False otherwise.

Return type:

None.

setlowerbound(lb)

Sets the lower numerical bound on the parameter. No checking is performed on whether the current value would violate this bound

Parameters:

ub (float) – lower boundary.

Return type:

None.

setname(name)

Sets the name of the parameter. name can be any string, preferably a meaningful description of the parameter

Parameters:

name (string) – name of the parameter.

Return type:

None.

setunchanged()

Sets the parameter to the unchanged state. This can be used by the model to signal that the model has already been calculated with these parameters and we don’t need to repeat the calculation unless someone changes the parameter value.

setupperbound(ub)

Sets the upper numerical bound on the parameter. No checking is performed on whether the current value would violate this bound

Parameters:

ub (float) – upper boundary.

Return type:

None.

setvalue(val)

Sets the value of the parameter. But only if it is not a coupled slave, if this is changeable and if the new value is within the bounds if the parameter is bound.

Parameters:

val (float) – New value of the parameter.

Return type:

True if value was set.

property sigma

Get the error bar on this parameter.

Returns:

sig – value of the error bar for this parameter.

Return type:

float

pyEELSMODEL.core.spectrum module

copyright University of Antwerp 2021 author: Jo Verbeeck and Daen Jannis

class pyEELSMODEL.core.spectrum.Spectrum(spectrumshape, data=None, acq_time=1, pppc=1)

Bases: object

Spectrum object which contains the experimental data.

property acq_time

The acquisition time used for spectra. Can be usefull when splicing multiple spectra together.

apply_dark(dark_name)

Remove the dark reference from the detector. This is done on the data of the spectrum itself and no new Spectrum object is created.

Parameters:

dark_name (string) – The filename where the dark reference is stored

apply_dark_and_gain(gain_name, dark_name)

Apply dark and gain. The dark and gain can be saved as a numpy array and applied to the spectrum. This is done on the data of the spectrum itself and no new Spectrum object is created. It assumes that the gain and dark is stored as a .npy file

Parameters:
  • gain_name (string) – The filename where the gain is stored.

  • dark_name (string) – The filename where the dark reference is stored

bad_index(index: int)

Check if index is in range otherwise raises a ValueError

Parameters:

index (int) – Index from 0..size into the spectral data.

Raises:

ValueError – If index <0 or index>self.size.

Return type:

None.

copy()

Returns a copy of the object

property dispersion
property energy_axis
erase()
property eshift
firstderivative()

Calculates the second derivative of the spectrum. :returns: s – The first derivative for the spectrum :rtype: Spectrum

classmethod from_numpy(data_array, energy_axis)

Creates a Spectrum object from the data and energy axis using numpy arrays. Usefull when playing with different functions which are not (yet) integrated into pyEELSmodel functionalities.

Parameters:
  • data_array (numpy array (1D)) – The data of the EEL spectrum.

  • energy_axis (numpy array (1D)) – The energy axis used [eV]

Returns:

s

Return type:

Spectrum

gaussiansmooth(sigma)

Return a new spectrum which is a gaussian smoothed version of this one.

Parameters:

sigma (float) – Standard deviation of the gaussian with which it will be convolved

Returns:

result – A smoothed spectrum version of the initial spectrum.

Return type:

Spectrum

get_energy_index(E)

Return the first index where E>energy within the spectral range

Parameters:

E (float) – Energy to find in this spectrum [eV].

Returns:

Index of the closest energy bin. 0 when below the energy onset of the spectrum self.size when above the energy range of the spectrum

Return type:

int

get_first_higher_then(x)

Get index of the first pixel having a value higher then x

Parameters:

x (float) – The value of which the pixel value should be larger.

Returns:

  • int – index of the first occurence of data>x.

  • None – if no value higher than x is found

get_interval(interval)

Returns a subspectrum of the given interval.

Parameters:

interval (tuple) – Interval which has the start and end of the sub spectrum [eV]

Returns:

s – Sub spectrum given by the interval.

Return type:

Spectrum

get_max()

Returns the maximum intensity value in the spectrum.

Returns:

Maximum value in the EELS dataset.

Return type:

float or int

get_min()

Returns the minimum intensity value in the spectrum.

Returns:

Minimum value in the EELS dataset.

Return type:

float or int

get_numerical_fwhm()

Small function which calculates the fwhm of a spectrum numerically by subtracting halve of the maximum from the spectrum and finding the smallest values. Note that the zero loss peak should be present else

the result will be garbage.

Returns:

fwhm – The full width halve maximum [eV], None is returned if the offset energy of the spectrum is bigger or equal to zero.

Return type:

float

get_specparameters()

Returns a tuple containing dispersion, offset, size of spectrum. Consider using get_spectrumshape() instead which returns a class holding the same information but in a way it can more easily be used to construct a new spectrum with same basic properties

Returns:

  • dispersion (float) – Energy dispersion in eV/pixel.

  • offset (float) – Energy of the first bin in the spectrum in eV.

  • size (int) – Number of spectral bins.

get_spectrumshape()

Return a Spectrumshape object holding information on the dispersion, offset, size of the Spectrum.

Returns:

shape – A spectrumshape object.

Return type:

Spectrumshape

getmaxenergy()
getmaxindex()

Returns the index containing the highest value in the spectrum. In case of multiple pixels having the same maximum value, index to the first occurence will be returned.

getnonexcludedpoints()

Returns the number of included points in the spectrum, used for the degrees of freedom.

init_poisson_error()

Calculate estimated standard deviation on the data assuming underlying Poisson statistics. Result can be obtained with get_error(). Any non-positive data is ignored and result in a standard deviation of 0

Return type:

None.

integrate(window=None, index_type=False)

Integrates the signal over the given energy window or the given index.

Parameters:
  • window (tuple) – The window over which to integrate. If index_type is True, the integration window is given with the index instead of energy If window is None, the integration is performed over the entire energy range.

  • index_type (bool) – Indicates if the window should be interpreted as the indices or the energy of the spectrum

Returns:

result – The value of the integration

Return type:

float

interp_to_other_energy_axis(spectrum, constant_values=(0, 0))

Interpolates the given spectrum to another given spectrum. The region which does not overlap with the energy axis of spectrum will be given a zero value. Other methods of padding can easily be incorporated using numpys pad functionality. The interpolation is linear and can also be modified using the interp function of scipy.

Parameters:

spectrum (Spectrum) –

The spectrum which holds energy axis to which the spectrum needs to

be interpolated.

Returns:

int_sepc – A new spectrum which is interpolated to the given spectrums energy axis.

Return type:

Spectrum

classmethod load(filename, flip_sign=False, **kwargs)

Loads different types of data. The possible datatypes are: .hdf5, .hspy, .dm3/.dm4 and .msa.

Parameters:
  • filename (string) – String of the filename where the extention should be ‘.hdf5’

  • flip_sign (boolean) – Indicates whether the offset value should be negative when loading a .dm file. (default: False)

Returns:

s – The spectrum which is contained in the filename

Return type:

Spectrum

classmethod load_dm(filename, flip_sign=False)

Load single spectrum from an DM file. There seems to be a bug in the dm loader which gives a positive offset value while it should be negative. This happens mainly for the low loss spectra which contain the zero-loss peak. The flip_sign parameter takes care of this.

Parameters:
  • filename (string) – filename of the dm file

  • flip_sign (boolean) – Indicates where the offset value should be set to negative. (default: False)

Returns:

s

Return type:

Spectrum

classmethod load_hdf5(filename, return_metadata=False)

Loads the hdf5 file.

Parameters:

filename (string) – String of the filename where the extention should be ‘.hdf5’

Returns:

s – The spectrum which is contained in the filename

Return type:

Spectrum

classmethod load_hspy()
classmethod loadmsa(filename)

Load single spectrum from an MSA file

Parameters:

filename (string) – The name of the .msa which needs to opened.

Returns:

s – The EEL spectrum in the file

Return type:

Spectrum

normalise(method='sum', window=None)

Normalizes the spectrum using the method identified. The data is over- written

Parameters:
  • method (string) – The normalization method which can be ‘sum’ or ‘max’. (default: ‘sum’)

  • window (tuple) – If the method is ‘sum’, an integration range can be added. If no window is provided the sum under the entire spectrum is taken.

property offset
padding(padding)

Zero padding the spectrum with padding size. This function is used when convolving the zero loss spectrum.

Parameters:

padding (uint) – The number of elements padded on the left and right

Returns:

s – A new spectrum which is zero padded.

Return type:

Spectrum object

plot(externalplt=None, use_e_axis=True, logscale=False, **kwargs)

Plot the spectrum

Parameters:
  • externalplt (matplotlib reference) – A reference to an external matplotlib reference, if None we use our own matplotlib and create a new figure.

  • use_e_axis (bool) – Indicates if the x-axis in the energy axis or if the pixel value of the detector will be used to visualize the data.

property pppc

Get ‘primary particles per count=pppc’. This value defines the number of electrons per given EELS count and is used to include information on the detector step. This is important for scintillating detectors where multiple counts can be generated for a single incoming electron. Knowing this is essential to calculate the effect of Poisson noise for the fitter. This only makes sense for experimental data and should not be used in e.g. components.

Returns:

The pppc value.

Return type:

float

recalibrate_spectrum(coefficients)

Recalibrate the spectrum using the coefficient for changing the dispersion and offset. These coefficients can be retrieved by linear fitting the measured edge onset energies compared to the literature values.

Parameters:

coefficients (numpy array 1D) – This array has two values coming from a linear fit (y = ax + b). The first element is the slope of the fit (a) and the second element is the constant (b).

rescale_spectrum(scale, shift)

Modifies the EELS spectrum by keeping the energy axis the same but shifting and rescaling the spectrum. First the shift is applied and then the scaling is modified.

Parameters:
  • scale (float) – The value with which the dispersion is multiplied.

  • shift (float [eV]) – The shift of the spectrum on the energy axis.

Returns:

int_spec – A new spectrum has been shifted and rescaled but has the same energy axis.

Return type:

Spectrum

reset_exclude_region(index_i=0, index_f=-1)

Reset a range of pixels from index_i to index_f (both inclusive) from being ‘excluded’. This means the Fitter will take into account these spectral regions. Note that you can call this function multiple times on different index ranges to define multiple areas as being not excluded. Note that default behaviour is that all spectral bins are not excluded when creating a spectrum.

Parameters:
  • index_i (int) – starting index for the inclusion area.

  • index_f (int) – end index for the inclusion area.

Return type:

None.

save_hdf5(filename, metadata=None, overwrite=False)

Saves the spectrum as a hdf5 file. The structure of the file can easily be investigated via a hdfview software.

Parameters:
  • filename (string) – filename of the saved file.

  • metadata (dictionary) – A dictionary containing E0, alpha, beta, elements and edges can be added to the hdf5 file. If None is given, nothing will be saved.

  • overwrite (boolean) – Indicates if the file will be overwritten if it already exists. (default: False)

Return type:

If the file saving workes, a True value is returned.

secondderivative()

Calculates the second derivative of the spectrum.

Returns:

s – The second derivative for the spectrum

Return type:

Spectrum

set_exclude_region(index_i, index_f)

Set a range of pixels from index_i to index_f (both inclusive) as ‘excluded’. This means the Fitter will not take into account these spectral regions. Note that you can call this function multiple times on different index ranges to define multiple areas of exclusion.

Parameters:
  • index_i (int) – starting index for the exclusion area.

  • index_f (int) – end index for the exclusion area.

Return type:

None.

set_exclude_region_energy(Ei, Ef)

Sets the excluded region using the energy.

Parameters:
  • Ei (float) – The starting energy of the excluded region.

  • Ef (float) – The end energy of the excluded region.

set_include_region(index_i, index_f)

Set a range of pixels from index_i to index_f (both inclusive) as ‘included’. This means the Fitter will take into account these spectral regions. Note that you can call this function multiple times on different index ranges to define multiple areas of exclusion.

Parameters:
  • index_i (int) – starting index for the inclusion area.

  • index_f (int) – end index for the inclusion area.

Return type:

None.

set_include_region_energy(Ei, Ef)

Sets the included region using the energy.

Parameters:
  • Ei (float) – The starting energy of the excluded region.

  • Ef (float) – The end energy of the excluded region.

setname(name)

Set the name of a spectrum. Can be used when displaying the spectrum. Could hold e.g. the filename if loaded from a file.

show_excluded_region(**kwargs)

Shows the points which are excluded from the fit.

class pyEELSMODEL.core.spectrum.Spectrumshape(dispersion, offset, size)

Bases: object

Spectrumshape is a class holding the main parameters of a spectrum in order to compactly create several spectra with the same size by providing an instance of this class It holds:

dispersion: float, dispersion in eV/pixel describing the energy scale offset: float, energy of the first pixel in the spectrum in eV size: int, the size of a spectrum in number of pixels (eg typ 1024)

Module contents