Fitting

The script will cycle through all files in a selected directory (unless certain files are excluded or explicitly listed) and will store the experimental data. The experimental data can then be fitted to user-defined model.

Formulate the model

The ImpedanceFitter parser understands circuits that follow a simple pattern:

  • Elements in series are connected by a +.

  • Elements in parallel are connected by parallel(A, B).

An example of a circuit could be:

parallel(R, C) + CPE

This stands for a resistor in parallel with a capacitor that are in series with a constant phase element (CPE).

Also nested parallels are possible:

parallel(parallel(L, C), R)

Find all available elements in Section Circuit elements and all available circuits in Section Circuits.

You can also use prefixes. This is needed if you want to combine multiple elements or circuits of the same type. Otherwise, the parameters cannot be distinguished by LMFIT.

For example:

parallel(R_f1, C_f1) + parallel(R_f2, C_f2)

Execute the fit

Using impedancefitter.fitter.Fitter.run(), those files can be fitted to an equivalent circuit model. If there are two models involved that shall be fitted sequentially for each file, refer to impedancefitter.fitter.Fitter.sequential_run(). This method allows one to communicate inferered parameters to the second model. In [Sabuncu2012], an example of such a sequential procedure has been presented.

Add a custom model

If you want to add a custom model that cannot be built by the existing models, you need to follow these steps:

  1. Create a new function for this like

    def example_function(omega, parameterA, parameterB):
        impedance = ...
        return impedance
    

    The first argument of the function needs to be named omega and is the angular frequency! The same holds true for elements. LMFIT generates the model based on the function arguments and always takes the first argument as the independent variable. The other parameters are then accessible by their names.

  2. Give this model a reference name that does not contain numbers or underscores. Link it in impedancefitter.utils._model_function() to the function you defined in the previous step. Add the model to impedancefitter.utils.available_models().

  3. Add the new parameter names and their corresponding LaTex representation to impedancefitter.utils.get_labels().

  4. Write a unit test for the model.

  5. Use the model.

API Reference

class impedancefitter.fitter.Fitter(inputformat, directory=None, **kwargs)[source]

The main fitting object class. All files in the data directory with matching file ending are imported to be fitted.

Parameters
  • inputformat (string) – The inputformat of the data files. Must be one of the formats specified in impedancefitter.utils.available_file_format(). Moreover, the ending of the file must match the inputformat.

  • directory (string, optional) – Path to data directory. Provide the data directory if the data directory is not the current working directory.

  • LogLevel ({‘DEBUG’, ‘INFO’, ‘WARNING’}, optional) – choose level for logger. Case DEBUG: the script will output plots after each fit, case INFO: the script will output results from each fit to the console.

  • excludeEnding (string, optional) – For file ending that should be ignored (if there are files with the same ending as the chosen inputformat). Useful for instance, if there are files like *_data.csv and *_result.csv around and only the first should be fitted.

  • ending (string, optional) – When inputformat is TXT, an alternative file ending is possible. The default is .TXT.

  • minimumFrequency (float, optional) – If you want to use another frequency than the minimum frequency in the dataset.

  • maximumFrequency (float, optional) – If you want to use another frequency than the maximum frequency in the dataset.

  • data_sets (int, optional) – Use only a certain number of data sets instead of all in directory.

  • current_threshold (float, optional) – Use only for data from E4980AL LCR meter to check current. If the current is not close to the threshold, the data point will be neglected.

  • voltage_threshold (float, optional) – Use only for data from E4980AL LCR meter to check voltage. If the voltage is not close to the threshold, the data point will be neglected.

  • E4980AL_tolerance (float, optional) – Set tolerance for current_threshold and/or voltage_threshold.

  • write_output (bool, optional) – Decide if you want to dump output to file. Default is False

  • fileList (list of strings, optional) – provide a list of files that exclusively should be processed. No other files will be processed. This option is particularly good if you have a common fileending of your data (e.g., .csv)

  • show (bool, optional) – Decide if you want to see the plots during the fitting procedure.

  • savefig (bool, optional) – Decide if you want to save the plots. Default is False.

  • trace_b (string, optional) – For TXT files, which contain more than one trace. The data is only read in until trace_b is found. Default is None (then trace_b does not have any effect).

  • skiprows_txt (int, optional) – Number of header rows inside a TXT file. Default is 1.

  • skiprows_trace (int, optional) – Lines between traces blocks in a TXT file. Default is None (then skiprows_trace does not have any effect).

  • delimiter (str, optional) – Only for TXT files. If the TXT file is not tab-separated, this can be specified here.

Variables
  • omega_dict (dict) – Contains frequency lists that were found in the individual files. The keys are the file names, the values the frequencies.

  • Z_dict (dict) – Contains corresponding impedances. Note that the values might be lists when there was more than one impedance data set in the file.

  • fit_data (dict) – Contains the fitting results for each individual file. In case of a sequential run, the dictionary contains two sub-dictionaries with keys model1 and model2 and the results.

  • fittedValues (lmfit.model.ModelResult) – The fitting result of the last data set that was fitted. Exists only when run() was called.

  • fittedValues1 (lmfit.model.ModelResult) – The fitting result of the last data set that was fitted. Exists only when sequential_run() was called and corresponds to the first model in this run.

  • fittedValues2 (lmfit.model.ModelResult) – The fitting result of the last data set that was fitted. Exists only when sequential_run() was called and corresponds to the second model in this run.

cluster_emcee_result(constant=100.0, show=False)[source]

Apply clustering to eliminate low-probability samples.

Parameters
  • constant (float) – The constant, which is used to define the threshold from which on walkers are eliminated.

  • show (bool, optional) – Plot clustering result.

Notes

The clustering approach described in [Hou2012] is implemented in this function. The walkers are sorted by probability and subsequently the difference between adjacent walker probabilities \(\Delta_j\) is evaluated. Then the average difference between the current and the first walkeri (\(\bar{\Delta}_j\)) is evaluated. Both differences are compared and a threshold is defined:

\[\Delta_j > \mathrm{constant} \cdot \bar{\Delta}_j\]

When this inequality becomes true, all walkers with \(k > j\) are thrown away.

References

Hou2012

Hou, F., Goodman, J., Hogg, D. W., Weare, J., & Schwab, C. (2012). An affine-invariant sampler for exoplanet fitting and discovery in radial velocity data. Astrophysical Journal, 745(2). https://doi.org/10.1088/0004-637X/745/2/198

emcee_conf_interval(result)[source]

Compute emcee confidence intervals.

The \(1\sigma\) to \(3\sigma\) confidence intervals are computed for a fitting result generated by emcee since this case is not covered by the original LMFIT implementation.

Parameters

result (lmfit.model.ModelResult) – Result from fit.

Returns

Dictionary containing limits of confidence intervals for all free parameters. The limits are structured in a list with 7 items, which are ordered as follows:

  1. lower limit of \(3\sigma\) confidence interval.

  2. lower limit of \(2\sigma\) confidence interval.

  3. lower limit of \(1\sigma\) confidence interval.

  4. median.

  5. upper limit of \(1\sigma\) confidence interval.

  6. upper limit of \(2\sigma\) confidence interval.

  7. upper limit of \(3\sigma\) confidence interval.

Return type

dict

emcee_report()[source]

Reports acceptance fraction and autocorrelation times.

initialize_model(modelname, log=False)[source]

Interface to LMFIT model class.

The equivalent circuit (represented as a string) is parsed and a LMFIT Model is returned. This can be useful if one wants to compute the impedance values for a given model and use it in a different context.

Parameters
  • modelname (string) – Provide equivalent circuit model to be parsed.

  • log (bool) – Decide, if logscale is used for the model.

Returns

model – The resulting LMFIT model.

Return type

lmfit.model.Model

linkk_test(capacitance=False, inductance=False, c=0.85, maxM=100, show=True, limits=[- 2, 2], weighting='modulus')[source]

Lin-KK test to check Kramers-Kronig validity.

Parameters
  • capacitance (bool, optional) – Add extra capacitance to circuit.

  • inductance (bool, optional) – Add extra inductance to circuit.

  • c (double, optional) – Set threshold for algorithm as described in [Schoenleber2014]. Must be between 0 and 1.

  • maxM (int, optional) – Maximum number of RC elements. Default is 100.

  • show (bool) – Show plots of test result. Default is True.

  • limits (list, optional) – Lower and upper limit of residual.

  • weighting (“modulus” or None) – Apply modulus weighting (as in [Schoenleber2014]) or process unweighted data.

Returns

  • results (dict) – Values of Lin-KK test for each file.

  • mus (dict) – All mu values during Lin-KK run for each file.

  • residuals (dict) – Least-squares residuals during Lin-KK run for each file.

Notes

The implementation of the algorithm follows [Schoenleber2014] closely.

If the option savefig is generally enabled, the plot result of the LinKK-Test will be saved to a pdf-file.

References

Schoenleber2014(1,2,3)

Schönleber, M., Klotz, D., & Ivers-Tiffée, E. (2014). A Method for Improving the Robustness of linear Kramers-Kronig Validity Tests. Electrochimica Acta, 131, 20–27. https://doi.org/10.1016/j.electacta.2014.01.034

model_iterations(modelclass)[source]
Information about number of iterations

if there is an iterative scheme for a modelclass.

Parameters

modelclass (str) – Name of the modelclass. This means that this model is represented in the equivalent circuit.

Returns

Number of iteration steps.

Return type

int

Notes

Double-Shell model

The following iterative procedure is applied:

  1. 1st Fit: The data is fitted against a model comprising the double-shell model. Parameters to be determined in this fitting round: kmed and emed.

  2. 2nd Fit: The parameters kmed and emed are fixed and the data is fitted again. To be determined in this fit: km and em.

  3. 3rd Fit: In addition, the parameters km and em are fixed and the data is fitted again. To be determined in this fit: kcp.

  4. last Fit: In addition, he parameter kcp is fixed. To be determined in this fit: all remaining parameters.

Single-Shell model

The following iterative procedure is applied:

  1. 1st Fit: The data is fitted against a model comprising the single-shell model. Parameters to be determined in this fitting round: kmed and emed.

  2. 2nd Fit: The parameters kmed and emed are fixed and the data is fitted again.

Cole-Cole model

  1. 1st Fit: The data is fitted against a model comprising the Cole-Cole model. Parameters to be determined in this fitting round: kdc and eh.

  2. 2nd Fit: The parameters kdc and eh are fixed and the data is fitted again.

plot_initial_best_fit(sequential=False)[source]

Plot initial and best fit together.

This method reveals how good the initial fit was.

Parameters

sequential (bool, optional) – If a sequential_run() was performed, set this value to True.

plot_uncertainty_interval(sigma=1, sequential=False)[source]

Plot uncertainty interval around best fit.

Parameters
  • sigma ({1, 2, 3}, optional) – Choose sigma for confidence interval.

  • sequential (bool, optional) – Set to True if you performed a sequential run before.

prepare_emcee_run(leastsquaresresult, lnsigma={'max': 0.6931471805599453, 'min': - 6.907755278982137, 'value': - 2.3025850929940455}, nwalkers=100, radius=0.0001, weighted=False, burn=500, steps=10000.0, thin=10)[source]

Prepare initial configuration based on previous least squares run.

Parameters
  • leastsquaresresult (lmfit.ModelResult) – Result of previous least squares run on same model. Basically the initial setting. Could also stem from a previous MCMC run.

  • lnsigma (dict) – Value of initial guess for experimental uncertainty.

  • nwalkers (int) – Number of walkers.

  • radius (float) – Radius of ball around initial guess.

  • burn (int) – Number of steps to be removed from MCMC chain in burn-in phase.

  • steps (int) – Length of MCMC chain.

  • thin (int) – Take only every thin-th step into account.

  • weighted (bool) – If False, lnsigma will be used.

Notes

The result from a previous least squares run is taking and the emcee run is prepared. The walkers are created and their initial positions are assigned. The initial positions are placed in a tight Gaussian ball around the least squares guess. Their radius can be set manually. Important parameters for the MCMC chains are set.

Returns

dictionary, which can be passed to run method via solver_kwargs keyword.

Return type

dict

process_data_from_file(filename, model, parameters, modelclass=None)[source]

Fit data from input file to model.

Wrapper for LMFIT fitting routine.

Parameters
  • filename (str) – Filename, which is contained in the data dictionaries omega_dict and z_dict.

  • model (lmfit.model.Model or lmfit.model.CompositeModel) – The model to fit to.

  • parameters (lmfit.parameter.Parameters) – The model parameters to be used.

  • modelclass (str, optional) – For an iterative scheme, the modelclass is passed to this function.

Returns

Result of fit as lmfit.model.ModelResult object.

Return type

lmfit.model.ModelResult

run(modelname, solver=None, parameters=None, protocol=None, solver_kwargs={}, modelclass='none', log=False, weighting=None, show=False, report=False, savemodelresult=True)[source]

Main function that iterates through all data sets provided.

Parameters
  • modelname (string) – Name of the model to be parsed. Must be built by those provided in impedancefitter.utils.available_models() and using + and parallel(x, y) as possible representations of series or parallel circuit.

  • solver (string, optional) – Choose an optimizer. Must be available in LMFIT. Default is least_squares

  • parameters (dict, optional) – Provide parameters if you do not want to read them from a yaml file (for instance in parallel UQ runs).

  • protocol (string, optional) – Choose ‘Iterative’ for repeated fits with changing parameter sets, customized approach. If not specified, there is always just one fit for each data set.

  • solver_kwargs (dict, optional) – Customize the employed solver. Interface to the LMFIT routine.

  • modelclass (str, optional) – Pass a modelclass for which the iterative scheme should be used. This is experimental support for iterative schemes, where parameters can be fixed during the fitting routine. In the future, a more intelligent approach could be found. See impedancefitter.Fitter.model_iterations()

  • weighting (str, optional) – Choose a weighting scheme. Default is unit weighting. Also possible: proportional weighting. See [Barsoukov2018] for more information.

  • savemodelresult (bool, optional) – Saves all lmfit.model.ModelResult instances to plot or evaluate uncertainty later.

sequential_run(model1, model2, communicate, solver=None, solver_kwargs={}, parameters1=None, parameters2=None, modelclass1=None, modelclass2=None, protocol=None, weighting=None)[source]

Main function that iterates through all data sets provided.

Here, two models are fitted sequentially and fitted parameters can be communicated from one model to the other.

Parameters
  • model1 (string) – Name of first model. Must be built by those provided in impedancefitter.utils.available_models() and using + and parallel(x, y) as possible representations of series or parallel circuit

  • model2 (string) – Name of second model. Must be built by those provided in impedancefitter.utils.available_models() and using + and parallel(x, y) as possible representations of series or parallel circuit

  • communicate (list of strings) – Names of parameters that should be communicated from model1 to model2. Requires that model2 contains a parameter that is named appropriately.

  • solver (string, optional) – choose an optimizer. Must be available in LMFIT. Default is least_squares

  • solver_kwargs (dict, optional) – Customize the employed solver. Interface to the LMFIT routine.

  • parameters1 (dict, optional) – Parameters of model1. Provide parameters if you do not want to use a yaml file.

  • parameters2 (dict, optional) – Parameters of model2. Provide parameters if you do not want to use a yaml file.

  • modelclass1 (str, optional) – Pass a modelclass for which the iterative scheme should be used. This is experimental support for iterative schemes, where parameters can be fixed during the fitting routine. In the future, a more intelligent approach could be found.

  • modelclass2 (str, optional) – Pass a modelclass for which the iterative scheme should be used. This is experimental support for iterative schemes, where parameters can be fixed during the fitting routine. In the future, a more intelligent approach could be found.

  • protocol (string, optional) – Choose ‘Iterative’ for repeated fits with changing parameter sets, customized approach. If not specified, there is always just one fit for each data set.

  • weighting (str, optional) – Choose a weighting scheme. Default is unit weighting. Also possible: proportional weighting. See [Barsoukov2018] for more information.

visualize_data(savefig=False, Zlog=False, allinone=False, plottype='impedance', show=True)[source]

Visualize impedance data.

Parameters
  • savefig (bool, optional) – Decide if plots should be saved as pdf. Default is False. Saves the file as filename + index of dataset + _impedance_overview.pdf. If allinone is True, then it is allinone_impedance_overview.pdf.

  • Zlog (bool, optional) – Plot impedance on logscale.

  • show (bool, optional) – Decide if you want to immediately see the plot.

  • allinone (bool, optional) – Visualize all data sets in one plot

  • plottype (str, optional) – Choose between standard impedance plot (‘impedance’) and bode plot (‘bode’).