Giter VIP home page Giter VIP logo

pyeis's Introduction

This repository contains PyEIS, A Python-based Electrochemical Impedance Spectroscopy analyzer and simulator. The software is designed to perform impedance simulations and analyze experimental data through the application of circuit elements. Physical processes in electrochemical systems can be represented by analog circuits containing capacitors (C), resistors (R), inductors (I), and some distributed elements such as constant-phase- (Q) and Warburg elements (W). These features make it possible to understand kinetics, double-layers, and mass-transport for a large range of electrochemical applications.

PyEIS has nine main features:

  • Currently contains 26 built-in equivalent circuits
  • Automated graphical representation in Nyquist and Bode plots with a number of plotting options
  • Capable of importing experimental data from Bio-Logic's EC-Lab '.mpt', Gamry's '.DTA', and Solartron's '.z' files
  • Experimental data validation and quality assessment through Boukamp's linear Kramers-Kronig analysis [1] with an automated optimization function that ensures an optimal number of -(RC)- elements ensuring data is neither over- or under-fitted [2]
  • Ability to fit experimental data through the weighed complex non-linear least squares fitting procedure using the lmfit package [3] with any built-in equivalent circuit
  • Batch fitting capabilities that do not require any additional key strokes
  • Extraction of fitted parameters for fast post-analysis
  • Open-source platform that makes it feasible to include any new equivalent circuit
  • Tutorials for simulating impedance, importing experimental data, and fitting experimental data

Following the license agreement, please use the following citation: DOI

Author: Kristian B. Knudsen ([email protected] || [email protected])

How to use PyEIS

PyEIS works in a python 3 environment. It was built, tested, and automated in Jupyter lab and Spyder. To use PyEIS, an independent interface is not available as impedance fitting and post analysis of fitted parameters would become a two-step process. Instead PyEIS works directly in a Python interface and fitted parameters are automatically output in variables directly accessible to plot or analyze vs. potential, current, state-of-charge, cycle number, time, etc. allowing for fast analysis.

The following command overview and two notebooks are tutorials that in a step-by-step manner introduce the functionality of PyEIS:

The PyEIS command overview gives a brief overview of the main functionalities and their dependents. The Simulations with PyEIS notebook covers simulating and plotting impedance spectra’s with different built-in equivalent circuits, fitting generated data with equivalent circuits, and extracting fitted parameters. The Experimental Data Extraction and Fitting with PyEIS notebook covers how to import experimental data, perform linear Kramers-Kronig analysis of the experimental data to assess data quality, how to mask data, fitting and plotting experimental data using equivalent circuits, assessing quality of fit using relative residuals, and extracting fitted parameters such as resistors and capacitors for further post-analysis.

The built-in equivalent circuits are illustrated in the following figure. Here Boukamp's simple notation of circuits [5] is used in the "trivial term", while "Simulation function" describes the function that needs to be called to perform simulations, and "Fit string" describes a circuit string that needs be called in the fitting function.

Software and Installation

PyEIS is available on PyPI and can be install using the following command

  • pip install PyEIS==1.0.10

Dependencies

The following libraries are required by PyEIS

  • numpy >= 1.13.3
  • scipy >= 1.0.1
  • pandas >= 0.22.0
  • mpmath >= 1.1.0
  • lmfit >= 0.9.7
  • matplotlib >= 2.2.2
  • seaborn >= 0.8.1

License

All files in this repository including code, readme, logos, and figures are released under the Apache 2.0 License. Learn more at the Open Source Initiative.

Acknowledgements

PyEIS is the accumulation of Kristian's work studying kinetics, double-layer and capacitive effects, and mass transport limitations in electrochemical cells with Electrochemical Impedance Spectroscopy during his PhD at The Technical University of Denmark, Department of Energy under the supervision of Ass. Prof. Johan Hjelm. He currently maintains a Post Doctoral position at the University of California, Berkeley at the Department of Chemical Engineering with Ass. Prof. Bryan D. McCloskey.

Funding is acknowledged from NASA ARMD Convergent Aeronautics Solutions (CAS) Project (Cooperative Agreement NNX16AR82A).

Google scholar site.

References

[1] Boukamp B.A., Solid State Ionics 20, 31-44 (1986), "A Linear Kronig-Kramers Transform Test for Immittance Data Validation"

[2] M. Schönleber, D. Klotz, and E. Ivers-Tiffée, Electrochimica Acta, 131, 20–27 (2014).

[3] Newville M., et al. "LMFIT: Non-Linear Least-Square Minimization and Curve-Fitting for Python" (2014) https://doi.org/10.5281/zenodo.11813

[4] Oliphant T.E (2006) "A guide to NumPy" Trelgol Publishing

[5] Boukamp B.A., "Equivalent Circuit. User Manual" University of Twente, The Netherlands, 1989, 2nd edn.

[6] Johansson F. (2013) "Mpmath: A Python Library for arbitrary-precision floating-point arithmetric" v. 0.18, http://mpmath.org

[7] McKinney W., Proceedings of the 9th Python in Science Conference, 51-56 (2010) "Data Structures for Statistical Computing in Python"

[8] Hunter, J.D. Computing in Science & Engineering, 9, 90-95 (2007) "Matplotlib: A 2D Graphics Environment", DOI:10.1109/MCSE.2007.55

pyeis's People

Contributors

kbknudsen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyeis's Issues

import error from .PyEIS_Data_extraction import *

how can I resolve this error

raceback (most recent call last):
File "C:\Users\orhan\PycharmProjects\PyEIS\PyEIS-master\PyEIS\PyEIS.py", line 37, in
from .PyEIS_Data_extraction import *
ImportError: attempted relative import with no known parent package

Please let me know how to fit the type of dataframe with EIS_fit

Hi. I sent you an e-mail which address is gmail.
But I really want to know how to fit the type of dataframe with EIS_fit.
Because my raw data consists of charge and discharge (so it doesn't have frequency range) and EIS data(it has frequency data), I can not use this raw data without preprocessing.
So my mpt file(raw data) couldn't be used in raw.
So I changed this type of raw data into dataframe type.(PyEIS.PyEIS.EIS_exp object at 0x000001B0938DC9D0>)
I can get the Nyquist plot with dataframe type, but I can not fit EIS data with equivalent circuit model.
As checked it, the reason why this phenomena has occured is that dataframe type can not use EIS_fit function.
I want to know is it possible to convert dataframe type with raw data type?
Or, other function to fit ECM with EIS data applicable in dataframe exist?
capture_1

capture_1
capture_@

Typing issues when using fitting='on'

line 4701, in EIS_plot
ax.plot(self.circuit_fit[i].real, -self.circuit_fit[i].imag, lw=0, marker='o', ms=8, mec='r', mew=1, mfc='none', label='')

AttributeError: 'Series' object has no attribute 'real'

What appears to be happening is that the circuit_fit has become a Series inside of a list for some reason. I'm working around it by just throwing in a .tolist() and plotting it myself, but I couldn't track down where it came from in the source.

numpy: 1.18.2
pandas: 1.0.3
python: 3.7.6

Thanks again for the awesome package!

Numpy Type Error when using freq_gen function

Running the second line in the Jupyter notebook tutorial "PyEIS_simulation_tutorial" results in a Type Error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

Can be traced back to line 62 in PyEIS.py:
f_range = np.logspace(np.log10(f_start), np.log10(f_stop), num=np.around(pts_decade*f_decades), endpoint=True)

Where np.around() passes a float to number of points in np.logspace

Unable to load .mpt

Hi, I tried to load my own EIS but failed horribly. Am I missing something?
I suspected the negative -Im(Z)/Ohm values, but I got the same error after I deleted them.


TypeError Traceback (most recent call last)
~\miniconda3\lib\site-packages\pandas\core\ops\array_ops.py in na_arithmetic_op(left, right, op, str_rep)
148 try:
--> 149 result = expressions.evaluate(op, str_rep, left, right)
150 except TypeError:

~\miniconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr)
207 if use_numexpr:
--> 208 return _evaluate(op, op_str, a, b)
209 return _evaluate_standard(op, op_str, a, b)

~\miniconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b)
69 with np.errstate(all="ignore"):
---> 70 return op(a, b)
71

~\miniconda3\lib\site-packages\pandas\core\ops\roperator.py in rmul(left, right)
16 def rmul(left, right):
---> 17 return right * left
18

TypeError: can't multiply sequence by non-int of type 'float'

During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
in
1 from PyEIS import *
2
----> 3 ex1 = EIS_exp(path='EIS/', data=['My_EIS.mpt'])

~\miniconda3\lib\site-packages\PyEIS\PyEIS.py in init(self, path, data, cycle, mask)
2283 else:
2284 print("Too many data files || 15 allowed")
-> 2285 self.df_raw = self.df_raw.assign(w = 2np.piself.df_raw.f) #creats a new coloumn with the angular frequency
2286
2287 #Masking data to each cycle

~\miniconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
62 other = item_from_zerodim(other)
63
---> 64 return method(self, other)
65
66 return new_method

~\miniconda3\lib\site-packages\pandas\core\ops_init_.py in wrapper(left, right)
501 lvalues = extract_array(left, extract_numpy=True)
502 rvalues = extract_array(right, extract_numpy=True)
--> 503 result = arithmetic_op(lvalues, rvalues, op, str_rep)
504
505 return _construct_result(left, result, index=left.index, name=res_name)

~\miniconda3\lib\site-packages\pandas\core\ops\array_ops.py in arithmetic_op(left, right, op, str_rep)
195 else:
196 with np.errstate(all="ignore"):
--> 197 res_values = na_arithmetic_op(lvalues, rvalues, op, str_rep)
198
199 return res_values

~\miniconda3\lib\site-packages\pandas\core\ops\array_ops.py in na_arithmetic_op(left, right, op, str_rep)
149 result = expressions.evaluate(op, str_rep, left, right)
150 except TypeError:
--> 151 result = masked_arith_op(left, right, op)
152
153 return missing.dispatch_fill_zeros(op, left, right, result)

~\miniconda3\lib\site-packages\pandas\core\ops\array_ops.py in masked_arith_op(x, y, op)
110 if mask.any():
111 with np.errstate(all="ignore"):
--> 112 result[mask] = op(xrav[mask], y)
113
114 result, _ = maybe_upcast_putmask(result, ~mask, np.nan)

~\miniconda3\lib\site-packages\pandas\core\ops\roperator.py in rmul(left, right)
15
16 def rmul(left, right):
---> 17 return right * left
18
19

TypeError: can't multiply sequence by non-int of type 'float'

This is EIS file My_EIS.txt

Unable to load .mpt file (EIS imported)

I am unable to load .mpt file which was previously imported to EC-Lab from .txt hence has no cycle_number column:


AttributeError Traceback (most recent call last)
in
1 from PyEIS import *
2
----> 3 ex1 = EIS_exp(path='EIS/', data=['Imported_EIS.mpt'])

~\miniconda3\lib\site-packages\PyEIS\PyEIS.py in init(self, path, data, cycle, mask)
2241 print('Data file(s) could not be identified')
2242
-> 2243 self.cycleno.append(self.df_raw0[j].cycle_number)
2244 if np.min(self.cycleno[j]) <= np.max(self.cycleno[j-1]):
2245 if j > 0: #corrects cycle_number except for the first data file

~\miniconda3\lib\site-packages\pandas\core\generic.py in getattr(self, name)
5272 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5273 return self[name]
-> 5274 return object.getattribute(self, name)
5275
5276 def setattr(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'cycle_number'

Imported_EIS.txt

If I manually add this column, I am greeted with another error, similar to the error I will discuss in next issue topic.

AttributeError: 'Series' object has no attribute 'real' using EIS_plot method

I was able to fit an experimental data using ex.EIS_fit(params=params, circuit='R-RQ-RQ',weight_func='modulus')

However when I tried to plot the data using ex2.EIS_plot(legend='potential', bode='log', fitting='on'), it generates the error.

  File "~\Miniconda3\envs\impedance\lib\site-packages\PyEIS\PyEIS.py", line 4701, in EIS_plot
    ax.plot(self.circuit_fit[i].real, -self.circuit_fit[i].imag, lw=0, marker='o', ms=8, mec='r', mew=1, mfc='none', label='')

  File "~\Miniconda3\envs\impedance\lib\site-packages\pandas\core\generic.py", line 5136, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'Series' object has no attribute 'real'

I am using python 3.7.9 in windows 10.

import error when importing from .dta

I get the following error message:

File "c:\Users\woutd\gamry_python\Model fitting\EIS_model_fitting.py", line 4, in
ex1 = EIS_exp(path=datapath, data=['D6_D_Black_0_Points.DTA'], cycle=[1])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyEIS\PyEIS.py", line 2237, in init
self.df_raw0.append(extract_dta(path=path, EIS_name=data[j])) #reads all datafiles
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyEIS\PyEIS_Data_extraction.py", line 122, in extract_dta
data.update({'im': np.abs(data.im)})
^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py", line 2168, in array_ufunc
return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\arraylike.py", line 276, in array_ufunc
result = maybe_dispatch_ufunc_to_dunder_op(self, ufunc, method, *inputs, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "ops_dispatch.pyx", line 105, in pandas._libs.ops_dispatch.maybe_dispatch_ufunc_to_dunder_op
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py", line 1725, in abs
return self.abs()
^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py", line 1718, in abs
res_mgr = self._mgr.apply(np.abs)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\managers.py", line 362, in apply
applied = b.apply(f, **kwargs)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\woutd\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\blocks.py", line 393, in apply
result = func(self.values, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: bad operand type for abs(): 'str'

Someone knows how to fix this problem?
Thanks in advance.
Kind regards.

Print or show plots

In pycharm (vers. 2021.1.2)
all works fine, but nothing is plotted.
as soon as I go into PyEIS.py and put at the end of the functions witch plot something
like EIS_sim at line 5128 fig.show() the problem is solved and the plots are now visible.
This needs to be done in every function witch plots something.

UnboundLocalError: local variable 'R' referenced before assignment

I use the R-RQ-RQ Fit Function [cir_RsRQRQ()] with

fit_params=Parameters()
fit_params.add('Rs', value=190, min=200, max=2000)
fit_params.add('R', value=150, min=100, max=4000)
fit_params.add('Q', value=10**-5, min=10**-7, max=10**-3)
fit_params.add('n', value=.8, min=.5, max=1)
fit_params.add('fs', value=10**-4, min=10**-6, max=10**-3)
fit_params.add('R2', value=2500, min=1000, max=4000)
fit_params.add('Q2', value=10**-4, min=10**-6, max=10**-3)
fit_params.add('n2', value=.8, min=.7, max=1)
fit_params.add('fs2', value=10**-5, min=10**-7, max=10**-3)

What I receive is:

Traceback (most recent call last):
File "C:\Users------------.py", line 73, in
Lennard_HIAT_C_2_5DC_80.EIS_fit(circuit='R-RQ-RQ', params=fit_params, weight_func='modulus')
File "C:\Users\fab54611\Anaconda3\lib\site-packages\PyEIS\PyEIS.py", line 4028, in EIS_fit
self.Fit.append(minimize(leastsq_errorfunc, params, method='leastsq', args=(self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, circuit, weight_func), nan_policy=nan_policy, maxfev=9999990))
File "C:\Users--\Anaconda3\lib\site-packages\lmfit\minimizer.py", line 2583, in minimize
return fitter.minimize(method=method)
File "C:\Users--\Anaconda3\lib\site-packages\lmfit\minimizer.py", line 2352, in minimize
return function(**kwargs)
File "C:\Users--\Anaconda3\lib\site-packages\lmfit\minimizer.py", line 1689, in leastsq
lsout = scipy_leastsq(self.__residual, variables, **lskws)
File "C:\Users--\Anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 410, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
File "C:\Users--\Anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 24, in _check_func
res = atleast_1d(thefunc(((x0[:numinputs],) + args)))
File "C:\Users--\Anaconda3\lib\site-packages\lmfit\minimizer.py", line 587, in __residual
out = self.userfcn(params, self.userargs, **self.userkws)
File "C:\Users--\Anaconda3\lib\site-packages\PyEIS\PyEIS.py", line 2128, in leastsq_errorfunc
re_fit = cir_RsRQRQ_fit(params, w).real
File "C:\Users--\Anaconda3\lib\site-packages\PyEIS\PyEIS.py", line 1249, in cir_RsRQRQ_fit
return Rs + (R/(1+R
Q
(w1j)**n)) + (R2/(1+R2Q2*(w*1j)**n2))
UnboundLocalError: local variable 'R' referenced before assignment

How to fix this?

Error using Lin_kk function

Running the ex4.Lin_KK(legend='potential') function in the tutorial gives me the following error:

   ~\anaconda3\lib\site-packages\PyEIS\PyEIS.py", line 2639, in Lin_KK
     self.KK_rr_re.append(residual_real(re=self.df[i].re, fit_re=self.KK_circuit_fit[i].real, fit_im=-self.KK_circuit_fit[i].imag)) #relative residuals for the real part
 
   ~\anaconda3\lib\site-packages\pandas\core\generic.py", line 5139, in __getattr__
     return object.__getattribute__(self, name)
 
 AttributeError: 'Series' object has no attribute 'real'

I am able to successful run all previous tutorial examples.
Has anyone experienced a similar issue and discovered a solution?
I am running Python 3.8.3 on Windows 10. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.