Fitting and plotting

Interactive fitting

PyElli offers several classes and decorators to make fitting easy. The central idea is to construct a class containing the measurement data and an optical model which is fitted to the data with lmfit. Since pyElli uses lmfit under the hood you may take advantage of its vast capabilities.

To make creation of the fitting classes as easy as possible pyElli contains decorators to automatically instantiate the class by providing a function containing the optical model.

Here you see an example of invoking such a decorator with a measurement dataframe psi_delta and parameters params, an lmfit Parameter or ParamsHist object to create a FitRho class.

@fit(psi_delta, params)
def model(lbda, params):
    ...

In the model function the actual optical model should be constructed and an Experiment object should be returned. A detailed example on how to use this decorator you find in the basic usage example.

Psi/Delta fitting

Fitting decorator and class to fit Psi/Delta experiments.

Decorator functions for convenient fitting

class elli.fitting.decorator_psi_delta.FitRho(exp_data, params, model, angle=70, **kwargs)[source]

Bases: FitDecorator

A class to fit psi/delta or rho based ellipsometry data with two degress of freedom

Intialize the psi/delta fitting class

Parameters:
  • exp_data (pd.DataFrame) – The dataframe containing an experimental mueller matrix. It should contain 2 columns with labels Ψ and Δ.

  • params (Parameters) – Fitting start parameters

  • model (Callable[[npt.NDArray, Parameters], Result]) – A function taking wavelengths as first parameter and fitting parameters as second, which returns a pyEllis Result object. This function contains the actual model which should be fitted.

  • angle (float, optional) – The angle of incident of the measurement. Used to calculate the Pseudo-Dielectric function. Defaults to 70.

create_widgets()[source]

Create ipywidgets for parameter estimation

fit(method='leastsq')[source]

Execute lmfit with the current fitting parameters

Parameters:

method (str, optional) – The fitting method to use. Any method supported by scipys curve_fit is allowed. Defaults to ‘leastsq’.

Returns:

The fitting result

Return type:

Result

fit_function(params, lbda, rhor, rhoi)[source]

The fit function to minimize the fitting problem

Parameters:
  • params (Parameters) – The lmfit fitting Parameters to construct the simulation

  • lbda (npt.NDArray) – Wavelengths in nm

  • rhor (npt.NDArray) – The real part of the experimental rho

  • rhoi (npt.NDArray) – The imaginary part of the experimental rho

Returns:

Residual between the calculation with current parameters and experimental data

Return type:

npt.NDArray

get_model_data(params=None, repr='psi-delta', append_exp_data=False)[source]

Gets the data from the provided modle with the provided parameters. If no parameters are provided, the fitted parameters are used (which default to the initial parameters if no fit has been triggered).

Parameters:
  • params (Parameters, optional) – The parameters to calculate the model with. If not provided, the fitted parameters are used. Defaults to None.

  • repr (str, optional) – The representation of the model and experiment data. Valid values are ‘psi-delta’ or ‘rho’. Defaults to ‘psi-delta’.

  • append_exp_data (bool, optional) – Appends the experimental data if set to True. Defaults to False.

Raises:

ValueError – Raised if the representation is not a valid value.

Returns:

The model results

Return type:

pd.DataFrame

plot()[source]

Plot the fit results as Psi/Delta

plot_rho()[source]

Plot the fit results as Rho

set_pseudo_diel(update_exp=False, update_names=False)[source]

Sets Plot to Pseudo Dielectric function values

Parameters:
  • update_exp (bool, optional) – Flag to change the experimental data as well. Defaults to False.

  • update_names (bool, optional) – Flag to change the label names. Defaults to False.

set_psi_delta(update_exp=False, update_names=False)[source]

Sets Plot to Psi/Delta values

Parameters:
  • update_exp (bool, optional) – Flag to change the experimental data as well. Defaults to False.

  • update_names (bool, optional) – Flag to change the label names. Defaults to False.

set_residual(update_exp=False, update_names=False)[source]

Sets plots to residual values

Parameters:
  • update_exp (bool, optional) – Flag to change the experimental data as well. Defaults to False.

  • update_names (bool, optional) – Flag to change the label names. Defaults to False.

set_rho(update_exp=False, update_names=False)[source]

Sets Plot to Rho values

Parameters:
  • update_exp (bool, optional) – Flag to change the experimental data as well. Defaults to False.

  • update_names (bool, optional) – Flag to change the label names. Defaults to False.

update_selection(change=None)[source]

Update plot after selection of displayed data

Parameters:

change (dict, optional) – A dictionary containing the ipywidgets change event

elli.fitting.decorator_psi_delta.fit(exp_data, params, angle=70, **kwargs)[source]

A parameters decorator for fitting psi/delta valus. Displays an ipywidget float box for each fitting parameter and an interactive plot to estimate parameters.

Parameters:
  • exp_data (pd.DataFrame) – The dataframe containing an experimental mueller matrix. It should contain 2 columns with labels Ψ and Δ.

  • params (Parameters) – Fitting start parameters

  • angle (float, optional) – The angle of incident of the measurement. Used to calculate the Pseudo-Dielectric function. Defaults to 70.

Returns:

fitting parameters as second, which returns a pyEllis Result object. This function contains the actual model which should be fitted and is automatically provided when used as a decorator.

Return type:

Callable[[npt.NDArray, Parameters], Result]

Mueller matrix fitting

Fitting decorator and class to fit mueller matrix experiments.

Decorator functions for convenient fitting of Mueller matrices

class elli.fitting.decorator_mmatrix.FitMuellerMatrix(exp_mm, params, model, **kwargs)[source]

Bases: FitDecorator

A class to fit mueller matrices to experimental data

Intialize the mueller matrix fitting class

Parameters:
  • exp_mm (pd.DataFrame) – The dataframe containing an experimental mueller matrix. It should contain 16 columns with labels Mxy, where xy are the matrix positions.

  • params (Parameters) – Fitting start parameters

  • model (Callable[[npt.NDArray, Parameters], Result]) – A function taking wavelengths as first parameter and fitting parameters as second, which returns a pyEllis Result object. This function contains the actual model which should be fitted

  • **display_single (bool) – Returns a figure containing a single graph, if set to true. Returns a grid of figures otherwise.

  • **sharex (bool) – Ties the zoom of the x-axes together for grid view.

  • **full_scale (bool) – Sets the y-axis scale to [-1, 1] if set to True.

create_widgets()[source]

Create ipywidgets for parameter estimation

fit(method='leastsq')[source]

Execute lmfit with the current fitting parameters

Parameters:

method (str, optional) – The fitting method to use. Any method supported by scipys curve_fit is allowed. Defaults to ‘leastsq’.

Returns:

The fitting result

Return type:

Result

fit_function(params, lbda, mueller_matrix)[source]

The fit function to minimize the fitting problem

Parameters:
  • params (Parameters) – The lmfit fitting Parameters to construct the simulation

  • lbda (npt.NDArray) – Wavelengths in nm

  • mueller_matrix (pd.DataFrame) – The experimental data to compare to the fitted model

Returns:

Residual between the calculation

with current parameters and experimental data

Return type:

npt.NDArray

get_model_data(params=None, append_exp_data=False)[source]

Gets the data from the provided model with the provided parameters. If no parameters are provided, the fitted parameters are used (which default to the initial parameters if no fit has been triggered).

Parameters:
  • params (Parameters, optional) – The parameters to calculate the model with. If not provided, the fitted parameters are used. Defaults to None.

  • append_exp_data (bool, optional) – Appends the experimental data if set to True. Defaults to False.

Returns:

The model results

Return type:

pd.DataFrame

plot(**kwargs)[source]

Plot the fit results

Parameters:
  • **display_single (bool) – Returns a figure containing a single graph, if set to true. Returns a grid of figures otherwise.

  • **sharex (bool) – Ties the zoom of the x-axes together for grid view.

  • **full_scale (bool) – Sets the y-axis scale to [-1, 1] if set to True.

Returns:

The figure containing the data

Return type:

go.Figure

plot_residual(**kwargs)[source]

Plots the residual between the fit and the experimental data

Parameters:
  • **display_single (bool) – Returns a figure containing a single graph, if set to true. Returns a grid of figures otherwise.

  • **sharex (bool) – Ties the zoom of the x-axes together for grid view.

  • **full_scale (bool) – Sets the y-axis scale to [-1, 1] if set to True.

Returns:

The figure containing the data

Return type:

go.Figure

update_selection(_=None)[source]

Update plot after selection of displayed data

Parameters:

_ (dict, optional) – No function. Just for compliance with ABC.

elli.fitting.decorator_mmatrix.fit_mueller_matrix(exp_mm, params, **kwargs)[source]

A parameters decorator for fitting mueller matrices. Displays an ipywidget float box for each fitting parameter and an interactive plot to estimate parameters.

Parameters:
  • exp_mm (pd.DataFrame) – The dataframe containing an experimental mueller matrix. It should contain 16 columns with labels Mxy, where xy are the matrix positions.

  • params (Parameters) – Fitting start parameters

  • **display_single (bool) – Returns a figure containing a single graph, if set to true. Returns a grid of figures otherwise.

  • **sharex (bool) – Ties the zoom of the x-axes together for grid view.

  • **full_scale (bool) – Sets the y-axis scale to [-1, 1] if set to True.

Returns:

A function taking wavelengths as first parameter and fitting parameters as second, which returns a pyEllis Result object. This function contains the actual model which should be fitted and is automatically provided when used as a decorator.

Return type:

Callable[[npt.NDArray, Parameters], Result]

elli.fitting.decorator_mmatrix.mmatrix_to_dataframe(exp_df, mueller_matrix, identifier=None)[source]

Reshape a numpy 4x4 array containing mueller matrix elements to a dataframe with columns Mxy. The index labels for each column are taken from the provided exp_df.

Parameters:
  • exp_df (pd.DataFrame) – The experimental dataframe providing the index and columns for the newly generated dataframe.

  • mueller_matrix (npt.NDArray) – Data to be reshaped into a dataframe

  • identifier (str, optional) – An identifier to append to each column name, in the form Mxy_<identifier>, where Mxy is the old column name. Defaults to None.

Returns:

Contains the data from mueller_matrix in the shape of exp_df

Return type:

pd.DataFrame

Fitting base class

This is the base class providing basic fitting features. This class is not intended to be used directly, it rather should be inherited from in additional fitting classes.

Abstract base class for Decorator functions for convenient fitting

class elli.fitting.decorator.FitDecorator[source]

Bases: ABC

The abstract base class for fitting decorators. Providing features for fit, undo and redo buttons.

abstract fit(method='')[source]

Execute lmfit with the current fitting parameters

Parameters:

method (str, optional) – The fitting method to use. Any method supported by scipys curve_fit is allowed. Defaults to ‘leastsq’.

Returns:

The fitting result

Return type:

Result

fit_button_clicked()[source]

Fit and update plot after the fit button has been clicked

Parameters:

selected (dict) – Dict containing the current widget information of the selection dropdown.

abstract get_model_data(params=None, append_exp_data=False)[source]

Gets the data from the provided model with the provided parameters. If no parameters are provided, the fitted parameters are used (which default to the initial parameters if no fit has been triggered).

Parameters:
  • params (Parameters, optional) – The parameters to calculate the model with. If not provided, the fitted parameters are used. Defaults to None.

  • append_exp_data (bool, optional) – Appends the experimental data if set to True. Defaults to False.

Returns:

The model results

Return type:

pd.DataFrame

re_undo_button_clicked(button)[source]

Redo or undo an operation on the parameters history object

Parameters:

button (widgets.Button) – The button instance, which triggered the event.

reset_to_init_params()[source]

Resets the parameters to the initial values

to_csv(*args, fname, params=None, append_exp_data=False, **kwargs)[source]

Saves the current model to csv. This is just a wrapper to pandas Dataframe and any argument to pandas to_csv may be passed as function arguments.

Parameters:
  • fname (str) – The file name to save the data to.

  • params (Parameters, optional) – The parameters to calculate the model with. If not provided, the fitted parameters are used. Defaults to None.

  • append_exp_data (bool, optional) – Appends the experimental data if set to True. Defaults to False.

update_params(change)[source]

Update plot after a change of fitting parameters

Parameters:
  • change (dict) – A dictionary containing the ipywidgets change event

  • selected (dict) – The selected value of the data display dropdown widget

abstract update_selection(change=None)[source]

Update plot after selection of displayed data

Parameters:

change (dict, optional) – A dictionary containing the ipywidgets change event

update_widgets()[source]

Updates the widget values according to the current parameters.

elli.fitting.decorator.is_in_notebook()[source]

Checks whether the current shell is in a jupyter notebook.

Returns:

True if the shell is in jupyter, False otherwise.

Return type:

bool

Parameter class

The parameter class extending lmfit’s Parameter class by a history of parameter changes.

ParmsHist provides a wrapper around lmfit.Parameters to keep track of the changes made to the parameters.

class elli.fitting.params_hist.ParamsHist[source]

Bases: Parameters

A wrapper around lmfit.Parameters to keep track of the changes made to the parameters.

Parameters:

usersyms (dict, optional) – Dictionary of symbols to add to the asteval.Interpreter (default is None).

clear_history()[source]

Clears the parameters history

commit()[source]

Saves the current parameter set to history.

property history

Gets the entire history

Returns:

The history

Return type:

List[Parameters]

property history_len

The current length of the history

Returns:

The length of the history

Return type:

int

property max_history_len

The maximum length of the history

Returns:

The maximum length of the history

Return type:

int

pop()[source]

Gets to the previous history version and deletes the current element.

revert(hist_pos)[source]

Reverts to an older history version and keeps the entire history.

Parameters:

hist_pos (int) – The history position to revert to.

tracked_add(*args, **kwargs)[source]

Adds a parameter and keeps track of the change in history

update_params(parameters)[source]

Updates the current parameters from a lmfit parameters object.

Parameters:

parameters (lmfit.Parameters) – The lmfit parameters object to update the values from.

update_value(key, value)[source]

Updates a parameter and keeps track of the change in history

Parameters:
  • key (str) – The key to be updated

  • value (float) – The value the key should be updated to

Plotting

Mueller matrix

This is a helper class to plot a mueller matrix dataframe.

Plotting functions for Mueller matrices

elli.plot.mueller_matrix.plot_mmatrix(dataframes, colors=None, dashes=None, names=None, single=True, full_scale=False, sharex=False)[source]

Takes multiple Mueller matrix dataframes with columns Mxy for matrix postion x,y and plots them together. Needs plotly as additional requirement to work.

Parameters:
  • dataframes (Union[pd.Dataframe, List[pd.DataFrame]]) – A dataframe or a list of dataframes containing data of the same index.

  • colors (Optional[List[str]], optional) – A list of colors which are cycled for each dataframes index. Defaults to None.

  • dashes (Optional[List[str]], optional) – A list of dash line styles which are cycled for each dataframes index. Defaults to None.

  • names (Optional[List[str]], optional) – A name for each dataframe index. Defaults to None.

  • single (bool, optional) – Uses a single plot if set and a grid if not set. Defaults to True.

  • full_scale (bool, optional) – Sets the y-axis limits to [-1, 1] if set. Defaults to False.

  • sharex (bool, optional) – Ties the zooming of the x-axis together for each plot in grid view. Defaults to False.

Returns:

A plotly figure containing the data from dataframes as a grid or single view.

Return type:

go.Figure

Structure

Plots a refractive index slice through a stack of materials.

elli.plot.structure.draw_structure(structure, lbda=1000, method='graph', margin=0.15)[source]

Draw the structure.

‘method’ : ‘graph’ or ‘section’ Returns : Axes object

elli.plot.structure.get_index_profile(structure, lbda, v=array([1, 0, 0]))[source]

Returns refractive index profile.

‘v’Unit vector, direction of evaluation of the refraction index.

Default value is v = e_x.

elli.plot.structure.get_permittivity_profile(structure, lbda)[source]

Returns permittivity tensor profile.