index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
65,010
mdutils.mdutils
new_table
This method takes a list of strings and creates a table. Using arguments ``columns`` and ``rows`` allows to create a table of *n* columns and *m* rows. The ``columns * rows`` operations has to correspond to the number of elements of ``text`` list argument. Moreover, ``argument`` allows to place the table wherever you want from the file. :param columns: this variable defines how many columns will have the table. :type columns: int :param rows: this variable defines how many rows will have the table. :type rows: int :param text: it is a list containing all the strings which will be placed in the table. :type text: list :param text_align: allows to align all the cells to the ``'right'``, ``'left'`` or ``'center'``. By default: ``'center'``. :type text_align: str :param marker: using ``create_marker`` method can place the table anywhere of the markdown file. :type marker: str :return: can return the table created as a string. :rtype: str :Example: >>> from mdutils import MdUtils >>> md = MdUtils(file_name='Example') >>> text_list = ['List of Items', 'Description', 'Result', 'Item 1', 'Description of item 1', '10', 'Item 2', 'Description of item 2', '0'] >>> table = md.new_table(columns=3, rows=3, text=text_list, text_align='center') >>> print(repr(table)) '\n|List of Items|Description|Result|\n| :---: | :---: | :---: |\n|Item 1|Description of item 1|10|\n|Item 2|Description of item 2|0|\n' .. csv-table:: **Table result on Markdown** :header: "List of Items", "Description", "Results" "Item 1", "Description of Item 1", 10 "Item 2", "Description of Item 2", 0
def new_table( self, columns: int, rows: int, text: List[str], text_align: str = "center", marker: str = "", ) -> str: """This method takes a list of strings and creates a table. Using arguments ``columns`` and ``rows`` allows to create a table of *n* columns and *m* rows. The ``columns * rows`` operations has to correspond to the number of elements of ``text`` list argument. Moreover, ``argument`` allows to place the table wherever you want from the file. :param columns: this variable defines how many columns will have the table. :type columns: int :param rows: this variable defines how many rows will have the table. :type rows: int :param text: it is a list containing all the strings which will be placed in the table. :type text: list :param text_align: allows to align all the cells to the ``'right'``, ``'left'`` or ``'center'``. By default: ``'center'``. :type text_align: str :param marker: using ``create_marker`` method can place the table anywhere of the markdown file. :type marker: str :return: can return the table created as a string. :rtype: str :Example: >>> from mdutils import MdUtils >>> md = MdUtils(file_name='Example') >>> text_list = ['List of Items', 'Description', 'Result', 'Item 1', 'Description of item 1', '10', 'Item 2', 'Description of item 2', '0'] >>> table = md.new_table(columns=3, rows=3, text=text_list, text_align='center') >>> print(repr(table)) '\\n|List of Items|Description|Result|\\n| :---: | :---: | :---: |\\n|Item 1|Description of item 1|10|\\n|Item 2|Description of item 2|0|\\n' .. csv-table:: **Table result on Markdown** :header: "List of Items", "Description", "Results" "Item 1", "Description of Item 1", 10 "Item 2", "Description of Item 2", 0 """ new_table = mdutils.tools.Table.Table() text_table = new_table.create_table(columns, rows, text, text_align) if marker: self.file_data_text = self.place_text_using_marker(text_table, marker) else: self.___update_file_data(text_table) return text_table
(self, columns: int, rows: int, text: List[str], text_align: str = 'center', marker: str = '') -> str
65,011
mdutils.mdutils
new_table_of_contents
Table of contents can be created if Headers of 'atx' style have been defined. This method allows to create a table of contents and define a title for it. Moreover, `depth` allows user to define how many levels of headers will be placed in the table of contents. If no marker is defined, the table of contents will be placed automatically after the file's title. :param table_title: The table content's title, by default "Table of contents" :type table_title: str :param depth: allows to include atx headers 1 through 6. Possible values: 1, 2, 3, 4, 5, or 6. :type depth: int :param marker: allows to place the table of contents using a marker. :type marker: str :return: a string with the data is returned. :rtype: str
def new_table_of_contents( self, table_title: str = "Table of contents", depth: int = 1, marker: str = "" ) -> str: """Table of contents can be created if Headers of 'atx' style have been defined. This method allows to create a table of contents and define a title for it. Moreover, `depth` allows user to define how many levels of headers will be placed in the table of contents. If no marker is defined, the table of contents will be placed automatically after the file's title. :param table_title: The table content's title, by default "Table of contents" :type table_title: str :param depth: allows to include atx headers 1 through 6. Possible values: 1, 2, 3, 4, 5, or 6. :type depth: int :param marker: allows to place the table of contents using a marker. :type marker: str :return: a string with the data is returned. :rtype: str """ if marker: self.table_of_contents = "" marker_table_of_contents = self.header.choose_header( level=1, title=table_title, style="setext" ) marker_table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( self._table_titles, depth ) self.file_data_text = self.place_text_using_marker( marker_table_of_contents, marker ) else: marker_table_of_contents = "" self.table_of_contents += self.header.choose_header( level=1, title=table_title, style="setext" ) self.table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( self._table_titles, depth ) return self.table_of_contents + marker_table_of_contents
(self, table_title: str = 'Table of contents', depth: int = 1, marker: str = '') -> str
65,012
mdutils.mdutils
place_text_using_marker
It replace a previous marker created with ``create_marker`` with a text string. This method is going to search for the ``marker`` argument, which has been created previously using ``create_marker`` method, in ``file_data_text`` string. :param text: the new string that will replace the marker. :type text: str :param marker: the marker that has to be replaced. :type marker: str :return: return a new file_data_text with the replace marker. :rtype: str
def place_text_using_marker(self, text: str, marker: str) -> str: """It replace a previous marker created with ``create_marker`` with a text string. This method is going to search for the ``marker`` argument, which has been created previously using ``create_marker`` method, in ``file_data_text`` string. :param text: the new string that will replace the marker. :type text: str :param marker: the marker that has to be replaced. :type marker: str :return: return a new file_data_text with the replace marker. :rtype: str """ return self.file_data_text.replace(marker, text)
(self, text: str, marker: str) -> str
65,013
mdutils.mdutils
read_md_file
Reads a Markdown file and save it to global class `file_data_text`. :param file_name: Markdown file's name that has to be read. :type file_name: str :return: optionally returns the file data content. :rtype: str
def read_md_file(self, file_name: str) -> str: """Reads a Markdown file and save it to global class `file_data_text`. :param file_name: Markdown file's name that has to be read. :type file_name: str :return: optionally returns the file data content. :rtype: str """ file_data = MarkDownFile().read_file(file_name) self.___update_file_data(file_data) return file_data
(self, file_name: str) -> str
65,014
mdutils.mdutils
write
Write text in ``file_Data_text`` string. :param text: a text a string. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :param marker: allows to replace a marker on some point of the file by the text. :type marker: str
def write( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", marker: str = "", wrap_width: int = 0, ) -> str: """Write text in ``file_Data_text`` string. :param text: a text a string. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :param marker: allows to replace a marker on some point of the file by the text. :type marker: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color or align: new_text = self.textUtils.text_format(text, bold_italics_code, color, align) else: new_text = text if marker: self.file_data_text = self.place_text_using_marker(new_text, marker) else: self.___update_file_data(new_text) return new_text
(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', marker: str = '', wrap_width: int = 0) -> str
65,017
mdutils.tools.TextUtils
TextUtils
This class helps to create bold, italics and change color text.
class TextUtils: """This class helps to create bold, italics and change color text.""" @staticmethod def bold(text: str) -> str: """Bold text converter. :param text: a text string. :type text: str :return: a string like this example: ``'**text**'`` :rtype: str""" return "**" + text + "**" @staticmethod def italics(text: str) -> str: """Italics text converter. :param text: a text string. :type text: str :return: a string like this example: ``'_text_'`` :rtype: str""" return "*" + text + "*" @staticmethod def inline_code(text: str) -> str: """Inline code text converter. :param text: a text string. :type text: str :return: a string like this example: ``'``text``'`` :rtype: str""" return "``" + text + "``" @staticmethod def center_text(text: str) -> str: """Place a text string to center. :param text: a text string. :type text: str :return: a string like this exampple: ``'<center>text</center>'`` """ return "<center>" + text + "</center>" @staticmethod def text_color(text: str, color: str = "black") -> str: """Change text color. :param text: it is the text that will be changed its color. :param color: it is the text color: ``'orange'``, ``'blue'``, ``'red'``... or a **RGB** color such as ``'#ffce00'``. :return: a string like this one: ``'<font color='color'>'text'</font>'`` :type text: str :type color: str :rtype: str """ return '<font color="' + color + '">' + text + "</font>" @staticmethod def text_external_link(text: str, link: str = "") -> str: """Using this method can be created an external link of a file or a web page. :param text: Text to be displayed. :type text: str :param link: External Link. :type link: str :return: return a string like this: ``'[Text to be shown](https://write.link.com)'`` :rtype: str""" return "[" + text + "](" + link + ")" @staticmethod def insert_code(code: str, language: str = "") -> str: """This method allows to insert a peace of code. :param code: code string. :type code:str :param language: code language: python. c++, c#... :type language: str :return: markdown style. :rtype: str """ if language == "": return "```\n" + code + "\n```" else: return "```" + language + "\n" + code + "\n```" @staticmethod def text_format( text: str, bold_italics_code: str = "", color: str = "black", align: str = "" ) -> str: """Text format helps to write multiple text format such as bold, italics and color. :param text: it is a string in which will be added the mew format :param bold_italics_code: using `'b'`: **bold**, `'i'`: _italics_ and `'c'`: `inline_code`. :param color: Can change text color. For example: 'red', 'green, 'orange'... :param align: Using this parameter you can align text. :return: return a string with the new text format. :type text: str :type bold_italics_code: str :type color: str :type align: str :rtype: str :Example: >>> from mdutils.tools.TextUtils import TextUtils >>> TextUtils.text_format(text='Some Text Here', bold_italics_code='bi', color='red', align='center') '***<center><font color="red">Some Text Here</font></center>***' """ new_text_format = text if bold_italics_code: if ( ("c" in bold_italics_code) or ("b" in bold_italics_code) or ("i" in bold_italics_code) ): if "c" in bold_italics_code: new_text_format = TextUtils.inline_code(new_text_format) else: raise ValueError( "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." ) if color != "black": new_text_format = TextUtils.text_color(new_text_format, color) if align == "center": new_text_format = TextUtils.center_text(new_text_format) if bold_italics_code: if ( ("c" in bold_italics_code) or ("b" in bold_italics_code) or ("i" in bold_italics_code) ): if "b" in bold_italics_code: new_text_format = TextUtils.bold(new_text_format) if "i" in bold_italics_code: new_text_format = TextUtils.italics(new_text_format) else: raise ValueError( "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." ) return new_text_format @staticmethod def add_tooltip(link: str, tip: str) -> str: """ :param link: :type link: str :param tip: :type tip: str return: ``link + "'" + format + "'"`` """ return link + " '{}'".format(tip)
()
65,018
mdutils.tools.TextUtils
add_tooltip
:param link: :type link: str :param tip: :type tip: str return: ``link + "'" + format + "'"``
@staticmethod def add_tooltip(link: str, tip: str) -> str: """ :param link: :type link: str :param tip: :type tip: str return: ``link + "'" + format + "'"`` """ return link + " '{}'".format(tip)
(link: str, tip: str) -> str
65,019
mdutils.tools.TextUtils
bold
Bold text converter. :param text: a text string. :type text: str :return: a string like this example: ``'**text**'`` :rtype: str
@staticmethod def bold(text: str) -> str: """Bold text converter. :param text: a text string. :type text: str :return: a string like this example: ``'**text**'`` :rtype: str""" return "**" + text + "**"
(text: str) -> str
65,020
mdutils.tools.TextUtils
center_text
Place a text string to center. :param text: a text string. :type text: str :return: a string like this exampple: ``'<center>text</center>'``
@staticmethod def center_text(text: str) -> str: """Place a text string to center. :param text: a text string. :type text: str :return: a string like this exampple: ``'<center>text</center>'`` """ return "<center>" + text + "</center>"
(text: str) -> str
65,021
mdutils.tools.TextUtils
inline_code
Inline code text converter. :param text: a text string. :type text: str :return: a string like this example: ``'``text``'`` :rtype: str
@staticmethod def inline_code(text: str) -> str: """Inline code text converter. :param text: a text string. :type text: str :return: a string like this example: ``'``text``'`` :rtype: str""" return "``" + text + "``"
(text: str) -> str
65,022
mdutils.tools.TextUtils
insert_code
This method allows to insert a peace of code. :param code: code string. :type code:str :param language: code language: python. c++, c#... :type language: str :return: markdown style. :rtype: str
@staticmethod def insert_code(code: str, language: str = "") -> str: """This method allows to insert a peace of code. :param code: code string. :type code:str :param language: code language: python. c++, c#... :type language: str :return: markdown style. :rtype: str """ if language == "": return "```\n" + code + "\n```" else: return "```" + language + "\n" + code + "\n```"
(code: str, language: str = '') -> str
65,023
mdutils.tools.TextUtils
italics
Italics text converter. :param text: a text string. :type text: str :return: a string like this example: ``'_text_'`` :rtype: str
@staticmethod def italics(text: str) -> str: """Italics text converter. :param text: a text string. :type text: str :return: a string like this example: ``'_text_'`` :rtype: str""" return "*" + text + "*"
(text: str) -> str
65,024
mdutils.tools.TextUtils
text_color
Change text color. :param text: it is the text that will be changed its color. :param color: it is the text color: ``'orange'``, ``'blue'``, ``'red'``... or a **RGB** color such as ``'#ffce00'``. :return: a string like this one: ``'<font color='color'>'text'</font>'`` :type text: str :type color: str :rtype: str
@staticmethod def text_color(text: str, color: str = "black") -> str: """Change text color. :param text: it is the text that will be changed its color. :param color: it is the text color: ``'orange'``, ``'blue'``, ``'red'``... or a **RGB** color such as ``'#ffce00'``. :return: a string like this one: ``'<font color='color'>'text'</font>'`` :type text: str :type color: str :rtype: str """ return '<font color="' + color + '">' + text + "</font>"
(text: str, color: str = 'black') -> str
65,025
mdutils.tools.TextUtils
text_external_link
Using this method can be created an external link of a file or a web page. :param text: Text to be displayed. :type text: str :param link: External Link. :type link: str :return: return a string like this: ``'[Text to be shown](https://write.link.com)'`` :rtype: str
@staticmethod def text_external_link(text: str, link: str = "") -> str: """Using this method can be created an external link of a file or a web page. :param text: Text to be displayed. :type text: str :param link: External Link. :type link: str :return: return a string like this: ``'[Text to be shown](https://write.link.com)'`` :rtype: str""" return "[" + text + "](" + link + ")"
(text: str, link: str = '') -> str
65,026
mdutils.tools.TextUtils
text_format
Text format helps to write multiple text format such as bold, italics and color. :param text: it is a string in which will be added the mew format :param bold_italics_code: using `'b'`: **bold**, `'i'`: _italics_ and `'c'`: `inline_code`. :param color: Can change text color. For example: 'red', 'green, 'orange'... :param align: Using this parameter you can align text. :return: return a string with the new text format. :type text: str :type bold_italics_code: str :type color: str :type align: str :rtype: str :Example: >>> from mdutils.tools.TextUtils import TextUtils >>> TextUtils.text_format(text='Some Text Here', bold_italics_code='bi', color='red', align='center') '***<center><font color="red">Some Text Here</font></center>***'
@staticmethod def text_format( text: str, bold_italics_code: str = "", color: str = "black", align: str = "" ) -> str: """Text format helps to write multiple text format such as bold, italics and color. :param text: it is a string in which will be added the mew format :param bold_italics_code: using `'b'`: **bold**, `'i'`: _italics_ and `'c'`: `inline_code`. :param color: Can change text color. For example: 'red', 'green, 'orange'... :param align: Using this parameter you can align text. :return: return a string with the new text format. :type text: str :type bold_italics_code: str :type color: str :type align: str :rtype: str :Example: >>> from mdutils.tools.TextUtils import TextUtils >>> TextUtils.text_format(text='Some Text Here', bold_italics_code='bi', color='red', align='center') '***<center><font color="red">Some Text Here</font></center>***' """ new_text_format = text if bold_italics_code: if ( ("c" in bold_italics_code) or ("b" in bold_italics_code) or ("i" in bold_italics_code) ): if "c" in bold_italics_code: new_text_format = TextUtils.inline_code(new_text_format) else: raise ValueError( "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." ) if color != "black": new_text_format = TextUtils.text_color(new_text_format, color) if align == "center": new_text_format = TextUtils.center_text(new_text_format) if bold_italics_code: if ( ("c" in bold_italics_code) or ("b" in bold_italics_code) or ("i" in bold_italics_code) ): if "b" in bold_italics_code: new_text_format = TextUtils.bold(new_text_format) if "i" in bold_italics_code: new_text_format = TextUtils.italics(new_text_format) else: raise ValueError( "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." ) return new_text_format
(text: str, bold_italics_code: str = '', color: str = 'black', align: str = '') -> str
65,030
pylsqpack._binding
Decoder
Decoder(max_table_capacity: int, blocked_streams: int) QPACK decoder. :param max_table_capacity: the maximum size in bytes of the dynamic table :param blocked_streams: the maximum number of streams that could be blocked
from pylsqpack._binding import Decoder
null
65,031
pylsqpack._binding
DecoderStreamError
null
from pylsqpack._binding import DecoderStreamError
null
65,032
pylsqpack._binding
DecompressionFailed
null
from pylsqpack._binding import DecompressionFailed
null
65,033
pylsqpack._binding
Encoder
Encoder() QPACK encoder.
from pylsqpack._binding import Encoder
null
65,034
pylsqpack._binding
EncoderStreamError
null
from pylsqpack._binding import EncoderStreamError
null
65,035
pylsqpack._binding
StreamBlocked
null
from pylsqpack._binding import StreamBlocked
null
65,037
impedance.models.circuits.circuits
BaseCircuit
Base class for equivalent circuit models
class BaseCircuit: """ Base class for equivalent circuit models """ def __init__(self, initial_guess=[], constants=None, name=None): """ Base constructor for any equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name : str, optional Name for the circuit """ # if supplied, check that initial_guess is valid and store initial_guess = [x for x in initial_guess if x is not None] for i in initial_guess: if not isinstance(i, (float, int, np.int32, np.float64)): raise TypeError(f'value {i} in initial_guess is not a number') # initalize class attributes self.initial_guess = initial_guess if constants is not None: self.constants = constants else: self.constants = {} self.name = name # initialize fit parameters and confidence intervals self.parameters_ = None self.conf_ = None def __eq__(self, other): if self.__class__ == other.__class__: matches = [] for key, value in self.__dict__.items(): if isinstance(value, np.ndarray): matches.append((value == other.__dict__[key]).all()) else: matches.append(value == other.__dict__[key]) return np.array(matches).all() else: raise TypeError('Comparing object is not of the same type.') def fit(self, frequencies, impedance, bounds=None, weight_by_modulus=False, **kwargs): """ Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies impedance: numpy array of dtype 'complex128' Impedance values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 weight_by_modulus : bool, optional Uses the modulus of each data (|Z|) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self """ frequencies = np.array(frequencies, dtype=float) impedance = np.array(impedance, dtype=complex) if len(frequencies) != len(impedance): raise TypeError('length of frequencies and impedance do not match') if self.initial_guess != []: parameters, conf = circuit_fit(frequencies, impedance, self.circuit, self.initial_guess, constants=self.constants, bounds=bounds, weight_by_modulus=weight_by_modulus, **kwargs) self.parameters_ = parameters if conf is not None: self.conf_ = conf else: raise ValueError('No initial guess supplied') return self def _is_fit(self): """ check if model has been fit (parameters_ is not None) """ if self.parameters_ is not None: return True else: return False def predict(self, frequencies, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency """ frequencies = np.array(frequencies, dtype=float) if self._is_fit() and not use_initial: return eval(buildCircuit(self.circuit, frequencies, *self.parameters_, constants=self.constants, eval_string='', index=0)[0], circuit_elements) else: warnings.warn("Simulating circuit based on initial parameters") return eval(buildCircuit(self.circuit, frequencies, *self.initial_guess, constants=self.constants, eval_string='', index=0)[0], circuit_elements) def get_param_names(self): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = self.circuit.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in self.constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in self.constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units def __str__(self): """ Defines the pretty printing of the circuit""" to_print = '\n' if self.name is not None: to_print += 'Name: {}\n'.format(self.name) to_print += 'Circuit string: {}\n'.format(self.circuit) to_print += "Fit: {}\n".format(self._is_fit()) if len(self.constants) > 0: to_print += '\nConstants:\n' for name, value in self.constants.items(): elem = get_element_from_name(name) units = check_and_eval(elem).units if '_' in name and len(units) > 1: unit = units[int(name.split('_')[-1])] else: unit = units[0] to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, value, unit) names, units = self.get_param_names() to_print += '\nInitial guesses:\n' for name, unit, param in zip(names, units, self.initial_guess): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) if self._is_fit(): params, confs = self.parameters_, self.conf_ to_print += '\nFit parameters:\n' for name, unit, param, conf in zip(names, units, params, confs): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) return to_print def plot(self, ax=None, f_data=None, Z_data=None, kind='altair', **kwargs): """ visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax: matplotlib.axes axes to plot on f_data: np.array of type float Frequencies of input data (for Bode plots) Z_data: np.array of type complex Impedance data to plot kind: {'altair', 'nyquist', 'bode'} type of plot to visualize Other Parameters ---------------- **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size` Returns ------- ax: matplotlib.axes axes of the created nyquist plot """ if kind == 'nyquist': if ax is None: _, ax = plt.subplots(figsize=(5, 5)) if Z_data is not None: ax = plot_nyquist(Z_data, ls='', marker='s', ax=ax, **kwargs) if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) Z_fit = self.predict(f_pred) ax = plot_nyquist(Z_fit, ls='-', marker='', ax=ax, **kwargs) return ax elif kind == 'bode': if ax is None: _, ax = plt.subplots(nrows=2, figsize=(5, 5)) if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') ax = plot_bode(f_data, Z_data, ls='', marker='s', axes=ax, **kwargs) if self._is_fit(): Z_fit = self.predict(f_pred) ax = plot_bode(f_pred, Z_fit, ls='-', marker='', axes=ax, **kwargs) return ax elif kind == 'altair': plot_dict = {} if Z_data is not None and f_data is not None: plot_dict['data'] = {'f': f_data, 'Z': Z_data} if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) Z_fit = self.predict(f_pred) if self.name is not None: name = self.name else: name = 'fit' plot_dict[name] = {'f': f_pred, 'Z': Z_fit, 'fmt': '-'} chart = plot_altair(plot_dict, **kwargs) return chart else: raise ValueError("Kind must be one of 'altair'," + f"'nyquist', or 'bode' (received {kind})") def save(self, filepath): """ Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object """ model_string = self.circuit model_name = self.name initial_guess = self.initial_guess if self._is_fit(): parameters_ = list(self.parameters_) model_conf_ = list(self.conf_) data_dict = {"Name": model_name, "Circuit String": model_string, "Initial Guess": initial_guess, "Constants": self.constants, "Fit": True, "Parameters": parameters_, "Confidence": model_conf_, } else: data_dict = {"Name": model_name, "Circuit String": model_string, "Initial Guess": initial_guess, "Constants": self.constants, "Fit": False} with open(filepath, 'w') as f: json.dump(data_dict, f) def load(self, filepath, fitted_as_initial=False): """ Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model """ json_data_file = open(filepath, 'r') json_data = json.load(json_data_file) model_name = json_data["Name"] model_string = json_data["Circuit String"] model_initial_guess = json_data["Initial Guess"] model_constants = json_data["Constants"] self.initial_guess = model_initial_guess self.circuit = model_string print(self.circuit) self.constants = model_constants self.name = model_name if json_data["Fit"]: if fitted_as_initial: self.initial_guess = np.array(json_data['Parameters']) else: self.parameters_ = np.array(json_data["Parameters"]) self.conf_ = np.array(json_data["Confidence"])
(initial_guess=[], constants=None, name=None)
65,038
impedance.models.circuits.circuits
__eq__
null
def __eq__(self, other): if self.__class__ == other.__class__: matches = [] for key, value in self.__dict__.items(): if isinstance(value, np.ndarray): matches.append((value == other.__dict__[key]).all()) else: matches.append(value == other.__dict__[key]) return np.array(matches).all() else: raise TypeError('Comparing object is not of the same type.')
(self, other)
65,039
impedance.models.circuits.circuits
__init__
Base constructor for any equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name : str, optional Name for the circuit
def __init__(self, initial_guess=[], constants=None, name=None): """ Base constructor for any equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name : str, optional Name for the circuit """ # if supplied, check that initial_guess is valid and store initial_guess = [x for x in initial_guess if x is not None] for i in initial_guess: if not isinstance(i, (float, int, np.int32, np.float64)): raise TypeError(f'value {i} in initial_guess is not a number') # initalize class attributes self.initial_guess = initial_guess if constants is not None: self.constants = constants else: self.constants = {} self.name = name # initialize fit parameters and confidence intervals self.parameters_ = None self.conf_ = None
(self, initial_guess=[], constants=None, name=None)
65,040
impedance.models.circuits.circuits
__str__
Defines the pretty printing of the circuit
def __str__(self): """ Defines the pretty printing of the circuit""" to_print = '\n' if self.name is not None: to_print += 'Name: {}\n'.format(self.name) to_print += 'Circuit string: {}\n'.format(self.circuit) to_print += "Fit: {}\n".format(self._is_fit()) if len(self.constants) > 0: to_print += '\nConstants:\n' for name, value in self.constants.items(): elem = get_element_from_name(name) units = check_and_eval(elem).units if '_' in name and len(units) > 1: unit = units[int(name.split('_')[-1])] else: unit = units[0] to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, value, unit) names, units = self.get_param_names() to_print += '\nInitial guesses:\n' for name, unit, param in zip(names, units, self.initial_guess): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) if self._is_fit(): params, confs = self.parameters_, self.conf_ to_print += '\nFit parameters:\n' for name, unit, param, conf in zip(names, units, params, confs): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) return to_print
(self)
65,041
impedance.models.circuits.circuits
_is_fit
check if model has been fit (parameters_ is not None)
def _is_fit(self): """ check if model has been fit (parameters_ is not None) """ if self.parameters_ is not None: return True else: return False
(self)
65,042
impedance.models.circuits.circuits
fit
Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies impedance: numpy array of dtype 'complex128' Impedance values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 weight_by_modulus : bool, optional Uses the modulus of each data (|Z|) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self
def fit(self, frequencies, impedance, bounds=None, weight_by_modulus=False, **kwargs): """ Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies impedance: numpy array of dtype 'complex128' Impedance values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 weight_by_modulus : bool, optional Uses the modulus of each data (|Z|) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self """ frequencies = np.array(frequencies, dtype=float) impedance = np.array(impedance, dtype=complex) if len(frequencies) != len(impedance): raise TypeError('length of frequencies and impedance do not match') if self.initial_guess != []: parameters, conf = circuit_fit(frequencies, impedance, self.circuit, self.initial_guess, constants=self.constants, bounds=bounds, weight_by_modulus=weight_by_modulus, **kwargs) self.parameters_ = parameters if conf is not None: self.conf_ = conf else: raise ValueError('No initial guess supplied') return self
(self, frequencies, impedance, bounds=None, weight_by_modulus=False, **kwargs)
65,043
impedance.models.circuits.circuits
get_param_names
Converts circuit string to names and units
def get_param_names(self): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = self.circuit.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in self.constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in self.constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units
(self)
65,044
impedance.models.circuits.circuits
load
Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model
def load(self, filepath, fitted_as_initial=False): """ Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model """ json_data_file = open(filepath, 'r') json_data = json.load(json_data_file) model_name = json_data["Name"] model_string = json_data["Circuit String"] model_initial_guess = json_data["Initial Guess"] model_constants = json_data["Constants"] self.initial_guess = model_initial_guess self.circuit = model_string print(self.circuit) self.constants = model_constants self.name = model_name if json_data["Fit"]: if fitted_as_initial: self.initial_guess = np.array(json_data['Parameters']) else: self.parameters_ = np.array(json_data["Parameters"]) self.conf_ = np.array(json_data["Confidence"])
(self, filepath, fitted_as_initial=False)
65,045
impedance.models.circuits.circuits
plot
visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax: matplotlib.axes axes to plot on f_data: np.array of type float Frequencies of input data (for Bode plots) Z_data: np.array of type complex Impedance data to plot kind: {'altair', 'nyquist', 'bode'} type of plot to visualize Other Parameters ---------------- **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size` Returns ------- ax: matplotlib.axes axes of the created nyquist plot
def plot(self, ax=None, f_data=None, Z_data=None, kind='altair', **kwargs): """ visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax: matplotlib.axes axes to plot on f_data: np.array of type float Frequencies of input data (for Bode plots) Z_data: np.array of type complex Impedance data to plot kind: {'altair', 'nyquist', 'bode'} type of plot to visualize Other Parameters ---------------- **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size` Returns ------- ax: matplotlib.axes axes of the created nyquist plot """ if kind == 'nyquist': if ax is None: _, ax = plt.subplots(figsize=(5, 5)) if Z_data is not None: ax = plot_nyquist(Z_data, ls='', marker='s', ax=ax, **kwargs) if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) Z_fit = self.predict(f_pred) ax = plot_nyquist(Z_fit, ls='-', marker='', ax=ax, **kwargs) return ax elif kind == 'bode': if ax is None: _, ax = plt.subplots(nrows=2, figsize=(5, 5)) if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') ax = plot_bode(f_data, Z_data, ls='', marker='s', axes=ax, **kwargs) if self._is_fit(): Z_fit = self.predict(f_pred) ax = plot_bode(f_pred, Z_fit, ls='-', marker='', axes=ax, **kwargs) return ax elif kind == 'altair': plot_dict = {} if Z_data is not None and f_data is not None: plot_dict['data'] = {'f': f_data, 'Z': Z_data} if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) Z_fit = self.predict(f_pred) if self.name is not None: name = self.name else: name = 'fit' plot_dict[name] = {'f': f_pred, 'Z': Z_fit, 'fmt': '-'} chart = plot_altair(plot_dict, **kwargs) return chart else: raise ValueError("Kind must be one of 'altair'," + f"'nyquist', or 'bode' (received {kind})")
(self, ax=None, f_data=None, Z_data=None, kind='altair', **kwargs)
65,046
impedance.models.circuits.circuits
predict
Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency
def predict(self, frequencies, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency """ frequencies = np.array(frequencies, dtype=float) if self._is_fit() and not use_initial: return eval(buildCircuit(self.circuit, frequencies, *self.parameters_, constants=self.constants, eval_string='', index=0)[0], circuit_elements) else: warnings.warn("Simulating circuit based on initial parameters") return eval(buildCircuit(self.circuit, frequencies, *self.initial_guess, constants=self.constants, eval_string='', index=0)[0], circuit_elements)
(self, frequencies, use_initial=False)
65,047
impedance.models.circuits.circuits
save
Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object
def save(self, filepath): """ Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object """ model_string = self.circuit model_name = self.name initial_guess = self.initial_guess if self._is_fit(): parameters_ = list(self.parameters_) model_conf_ = list(self.conf_) data_dict = {"Name": model_name, "Circuit String": model_string, "Initial Guess": initial_guess, "Constants": self.constants, "Fit": True, "Parameters": parameters_, "Confidence": model_conf_, } else: data_dict = {"Name": model_name, "Circuit String": model_string, "Initial Guess": initial_guess, "Constants": self.constants, "Fit": False} with open(filepath, 'w') as f: json.dump(data_dict, f)
(self, filepath)
65,048
nleis.nleis
EISandNLEIS
null
class EISandNLEIS: ### ToDO: add SSO method and SO method def __init__(self, circuit_1='',circuit_2='',initial_guess = [] ,constants = None, name=None, **kwargs): """ Constructor for a customizable equivalent circuit model Parameters ---------- circuit_1: string A string that should be interpreted as an equivalent circuit for linear EIS circuit_2: string A string that should be interpreted as an equivalent circuit for NLEIS initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name: str, optional Name for the model Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)) for EIS. For NLEIS, the circuit should be grouped by d(cathode,anode) Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: A two electrode cell with sperical porous cathode and anode, resistor, and inductor is represents as, EIS: circuit_1 = 'L0-R0-TDS0-TDS1' NLEIS: circuit_2 = 'd(TDSn0-TDSn1)' """ # if supplied, check that initial_guess is valid and store initial_guess = [x for x in initial_guess if x is not None] for i in initial_guess: if not isinstance(i, (float, int, np.int32, np.float64)): raise TypeError(f'value {i} in initial_guess is not a number') # initalize class attributes # self.initial_guess = list(initial_guess) self.initial_guess = initial_guess self.circuit_1 = circuit_1 self.circuit_2 = circuit_2 elements_1 = extract_circuit_elements(circuit_1) elements_2 = extract_circuit_elements(circuit_2) for element in elements_2: if element.replace('n', '') not in elements_1 or ('n' not in element and element != ''): raise TypeError('The pairing of linear and nonlinear elements must be presented correctly for simultaneous fitting.'+ ' Double check the EIS circuit: ' + f'{circuit_1}' + ' and the NLEIS circuit: '+ f'{circuit_2}' +'. The parsed elements are '+f'{elements_1}'+' for circuit_1, and ' + f'{elements_2}'+ ' for circuit_2.') input_elements = elements_1 + elements_2 if constants is not None: self.constants = constants self.constants_1 = {} self.constants_2 = {} ## New code for constant separatation ## in the current development the differentiation between linear and nonlinear is separated by 'n' ## using get_element_from_name to get the raw element and adding n to the end for elem in self.constants: raw_elem = get_element_from_name(elem) raw_circuit_elem = elem.split('_')[0] if raw_circuit_elem not in input_elements: raise ValueError(f'{raw_elem} not in ' + f'input elements ({input_elements})') raw_num_params = check_and_eval(raw_elem).num_params if raw_num_params<=1: ## currently there is no single parameter nonlinear element, ## so this can work, but might be changed in the future self.constants_1[elem]=self.constants[elem] else: param_num = int(elem.split('_')[-1]) if raw_elem[-1] != 'n': if param_num>=raw_num_params: raise ValueError(f'{elem} is out of the range of the maximum allowed ' + f'number of parameters ({raw_num_params})') self.constants_1[elem]=self.constants[elem] len_elem = len(raw_elem) nl_elem = elem[0:len_elem]+'n'+elem[len_elem:] raw_nl_elem = get_element_from_name(nl_elem) if raw_nl_elem in circuit_elements.keys(): self.constants_2[nl_elem]=self.constants[elem] else: self.constants_2[elem]=self.constants[elem] if raw_elem[-1] == 'n': if param_num>=raw_num_params: raise ValueError(f'{elem} is out of the range of the maximum allowed ' + f'number of parameters ({raw_num_params})') num_params = check_and_eval(raw_elem[0:-1]).num_params len_elem = len(raw_elem[0:-1]) if param_num<num_params: self.constants_1[elem[0:len_elem]+elem[len_elem+1:]]=self.constants[elem] self.constants_2[elem]=self.constants[elem] else: self.constants = {} self.constants_1 = {} self.constants_2 = {} ### new code for circuit length calculation using circuit element ### producing edited circuit ### i.e. circuit_1 = L0-R0-TDP0-TDS1; circuit_2 = TDPn0-TDSn1; edited_circuit = L0-R0-TDPn0-TDSn1 if elements_1 != [''] or elements_2 !=['']: if elements_1 == [''] or elements_2 ==['']: raise ValueError('Either circuit_1 or circuit_2 cannot be empty') edited_circuit = '' for elem in elements_1: nl_elem = elem[0:-1]+'n'+elem[-1] if nl_elem in elements_2: edited_circuit += '-'+ nl_elem else: edited_circuit += '-'+ elem self.edited_circuit = edited_circuit[1:] else: self.edited_circuit = '' circuit_len = calculateCircuitLength(self.edited_circuit) if len(self.initial_guess) + len(self.constants) != circuit_len: raise ValueError('The number of initial guesses ' + f'({len(self.initial_guess)}) + ' + 'the number of constants ' + f'({len(self.constants)})' + ' must be equal to ' + f'the circuit length ({circuit_len})') self.name = name # initialize fit parameters and confidence intervals self.parameters_ = None self.conf_ = None self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) def __eq__(self, other): if self.__class__ == other.__class__: matches = [] for key, value in self.__dict__.items(): if isinstance(value, np.ndarray): matches.append((value == other.__dict__[key]).all()) else: matches.append(value == other.__dict__[key]) return np.array(matches).all() else: raise TypeError('Comparing object is not of the same type.') def fit(self, frequencies, Z1,Z2, bounds = None, opt='max',max_f=10,cost = 0.5, **kwargs): """ Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies Z1: numpy array of dtype 'complex128' EIS values to fit Z1: numpy array of dtype 'complex128' NLEIS values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. When bounds are provided, the input will normalized to stabilize the algorithm Normalization : str, optional Default is max normalization. Other normalization will be supported in the future max_f: int The the maximum frequency of interest for NLEIS kwargs : Keyword arguments passed to simul_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self """ # check that inputs are valid: # frequencies: array of numbers # impedance: array of complex numbers # impedance and frequency match in length frequencies = np.array(frequencies, dtype=float) Z1 = np.array(Z1, dtype=complex) Z2 = np.array(Z2, dtype=complex) if len(frequencies) != len(Z1): raise TypeError('length of frequencies and impedance do not match for EIS') if self.initial_guess != []: parameters, conf = simul_fit(frequencies, Z1,Z2, self.circuit_1,self.circuit_2,self.edited_circuit, self.initial_guess, constants_1=self.constants_1,constants_2=self.constants_2, bounds=bounds, opt=opt,cost = cost,max_f = max_f, **kwargs) # self.parameters_ = list(parameters) self.parameters_ = parameters if conf is not None: # self.conf_ = list(conf) self.conf_ = conf self.conf1, self.conf2 = individual_parameters(self.circuit_1,self.conf_,self.constants_1,self.constants_2) self.p1, self.p2 = individual_parameters(self.circuit_1,self.parameters_,self.constants_1,self.constants_2) else: raise ValueError('no initial guess supplied') return self def _is_fit(self): """ check if model has been fit (parameters_ is not None) """ if self.parameters_ is not None: return True else: return False def predict(self, frequencies, max_f=10, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: ndarray of numeric dtype max_f: int The the maximum frequency of interest for NLEIS use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance """ if not isinstance(frequencies, np.ndarray): raise TypeError('frequencies is not of type np.ndarray') if not (np.issubdtype(frequencies.dtype, np.integer) or np.issubdtype(frequencies.dtype, np.floating)): raise TypeError('frequencies array should have a numeric ' + f'dtype (currently {frequencies.dtype})') f1 =frequencies mask = np.array(frequencies)<max_f f2 = frequencies[mask] if self._is_fit() and not use_initial: x1,x2 = wrappedImpedance(self.circuit_1, self.constants_1,self.circuit_2,self.constants_2,f1,f2,self.parameters_) return x1,x2 else: warnings.warn("Simulating circuit based on initial parameters") x1,x2 = wrappedImpedance(self.circuit_1, self.constants_1,self.circuit_2,self.constants_2,f1,f2,self.initial_guess) return(x1,x2) def get_param_names(self,circuit,constants): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = circuit.replace('d', '').replace('(', '').replace(')', '')#edit for nleis.py names = names.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units def __str__(self): """ Defines the pretty printing of the circuit """ to_print = '\n' if self.name is not None: to_print += 'Name: {}\n'.format(self.name) to_print += 'EIS Circuit string: {}\n'.format(self.circuit_1) to_print += 'NLEIS Circuit string: {}\n'.format(self.circuit_2) to_print += "Fit: {}\n".format(self._is_fit()) if len(self.constants) > 0: to_print += '\nConstants:\n' for name, value in self.constants.items(): elem = get_element_from_name(name) units = check_and_eval(elem).units if '_' in name: unit = units[int(name.split('_')[-1])] else: unit = units[0] to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, value, unit) names1, units1= self.get_param_names(self.circuit_1,self.constants_1) names2, units2 = self.get_param_names(self.circuit_2,self.constants_2) to_print += '\nEIS Initial guesses:\n' p1, p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) for name, unit, param in zip(names1, units1, p1): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) to_print += '\nNLEIS Initial guesses:\n' for name, unit, param in zip(names2, units2, p2): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) if self._is_fit(): params1, confs1 = self.p1, self.conf1 to_print += '\nEIS Fit parameters:\n' for name, unit, param, conf in zip(names1, units1, params1, confs1): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) params2, confs2 = self.p2, self.conf2 to_print += '\nNLEIS Fit parameters:\n' for name, unit, param, conf in zip(names2, units2, params2, confs2): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) return to_print def extract(self): """ extract the printing of the circuit in a dictionary """ names1, units1 = self.get_param_names(self.circuit_1,self.constants_1) dic1={} if self._is_fit(): params1 = self.p1 for names, param in zip(names1, params1): dic1[names] = param names2, units2 = self.get_param_names(self.circuit_2,self.constants_2) dic2={} if self._is_fit(): params2 = self.p2 for names, param in zip(names2, params2): dic2[names] = param return dic1,dic2 def plot(self, ax=None, f_data=None, Z1_data =None, Z2_data= None, kind='nyquist', max_f = 10, **kwargs): ''' visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax : matplotlib.axes, axes to plot on f_data : np.array of type float Frequencies of input data (for Bode plots) Z1_data : np.array of type complex DESCRIPTION. The default is None. Z2_data : np.array of type complex DESCRIPTION. The default is None. kind : {'altair', 'nyquist', 'bode'} type of plot to visualize max_f : TYPE, optional DESCRIPTION. The default is 10. **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size` ''' if kind == 'nyquist': if ax is None: _, ax = plt.subplots(1,2,figsize=(10, 5)) ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z1_data is not None: ax[0] = plot_first(ax[0], Z1_data, scale=1, fmt='s', **kwargs) ## impedance.py style # plot_nyquist(Z1_data, ls='', marker='s', ax=ax[0], **kwargs) if Z2_data is not None: mask = mask =np.array(f_pred)<max_f ax[1] = plot_second(ax[1], Z2_data[mask], scale=1, fmt='s', **kwargs) ## impedance.py style # plot_nyquist(Z2_data, units='Ohms/A', ls='', marker='s', ax=ax[1], **kwargs) Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) ax[0] = plot_first(ax[0], Z1_fit, scale=1, fmt='-', **kwargs) # plot_nyquist(Z1_fit, ls='-', marker='', ax=ax[0], **kwargs) ax[1] = plot_second(ax[1], Z2_fit, scale=1, fmt='-', **kwargs) # plot_nyquist(Z2_fit,units='Ohms/A', ls='-', marker='', ax=ax[1], **kwargs) ax[0].legend(['data','fit']) ax[1].legend(['data','fit']) return ax elif kind == 'bode': if ax is None: _, ax = plt.subplots(2,2, figsize=(8, 8)) if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z1_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') ax[:,0] = plot_bode(f_data, Z1_data, ls='', marker='s', axes=ax[:,0], **kwargs) if Z2_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') mask =np.array(f_pred)<max_f f2 = f_data[mask] Z2 = Z2_data[mask] ax[:,1] = plot_bode(f2,Z2, units='Ohms/A', ls='', marker='s', axes=ax[:,1], **kwargs) ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) f1 = f_data f2 = f_data[np.array(f_data)<max_f] ax[:,0] = plot_bode(f1, Z1_fit, ls='-', marker='o', axes=ax[:,0], **kwargs) ax[:,1] = plot_bode(f2, Z2_fit,units='Ohms/A', ls='-', marker='o', axes=ax[:,1], **kwargs) ax[0,0].set_ylabel(r'$|Z_{1}(\omega)|$ ' + '$[{}]$'.format('Ohms'), fontsize=20) ax[1,0].set_ylabel(r'$-\phi_{Z_{1}}(\omega)$ ' + r'$[^o]$', fontsize=20) ax[0,1].set_ylabel(r'$|Z_{2}(\omega)|$ ' + '$[{}]$'.format('Ohms/A'), fontsize=20) ax[1,1].set_ylabel(r'$-\phi_{Z_{2}}(\omega)$ ' + r'$[^o]$', fontsize=20) ax[0,0].legend(['Data','Fit'],fontsize=20) ax[0,1].legend(['Data','Fit'],fontsize=20) ax[1,0].legend(['Data','Fit'],fontsize=20) ax[1,1].legend(['Data','Fit'],fontsize=20) return ax elif kind == 'altair': plot_dict_1 = {} plot_dict_2 = {} if Z1_data is not None and Z2_data is not None and f_data is not None: plot_dict_1['data'] = {'f': f_data, 'Z': Z1_data} mask = np.array(f_data)<max_f plot_dict_2['data'] = {'f': f_data[mask], 'Z': Z2_data[mask]} ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if self.name is not None: name = self.name else: name = 'fit' Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) mask = np.array(f_pred)<max_f plot_dict_1[name] = {'f': f_pred, 'Z': Z1_fit, 'fmt': '-'} plot_dict_2[name] = {'f': f_pred[mask], 'Z': Z2_fit, 'fmt': '-'} chart1 = plot_altair(plot_dict_1,k=1,units = 'Ω', **kwargs) chart2 = plot_altair(plot_dict_2,k=2,units = 'Ω/A', **kwargs) return chart1,chart2 else: raise ValueError("Kind must be one of 'altair'," + f"'nyquist', or 'bode' (received {kind})") def save(self, filepath): """ Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object """ model_string_1 = self.circuit_1 model_string_2 = self.circuit_2 edited_circuit_str = self.edited_circuit model_name = self.name initial_guess = self.initial_guess if self._is_fit(): parameters_ = list(self.parameters_) model_conf_ = list(self.conf_) # parameters_ = self.parameters_ # model_conf_ = self.conf_ data_dict = {"Name": model_name, "Circuit String 1": model_string_1, "Circuit String 2": model_string_2, "Initial Guess": initial_guess, "Constants": self.constants, "Constants 1": self.constants_1, "Constants 2": self.constants_2, "Fit": True, "Parameters": parameters_, "Confidence": model_conf_, "Edited Circuit Str": edited_circuit_str } else: data_dict = {"Name": model_name, "Circuit String 1": model_string_1, "Circuit String 2": model_string_2, "Initial Guess": initial_guess, "Constants": self.constants, "Constants 1": self.constants_1, "Constants 2": self.constants_2, "Edited Circuit Str": edited_circuit_str, "Fit": False} with open(filepath, 'w') as f: json.dump(data_dict, f) def load(self, filepath, fitted_as_initial=False): """ Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model """ json_data_file = open(filepath, 'r') json_data = json.load(json_data_file) model_name = json_data["Name"] model_string_1 = json_data["Circuit String 1"] model_string_2 = json_data["Circuit String 2"] model_initial_guess = json_data["Initial Guess"] model_constants = json_data["Constants"] self.initial_guess = model_initial_guess self.circuit_1 = model_string_1 self.circuit_2 = model_string_2 self.edited_circuit = json_data["Edited Circuit Str"] self.constants = model_constants self.constants_1 =json_data["Constants 1"] self.constants_2 =json_data["Constants 2"] self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) self.name = model_name if json_data["Fit"]: if fitted_as_initial: self.initial_guess = json_data['Parameters'] self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) else: self.parameters_ = np.array(json_data["Parameters"]) self.conf_ = np.array(json_data["Confidence"]) self.conf1, self.conf2 = individual_parameters(self.circuit_1,self.conf_,self.constants_1,self.constants_2) self.p1, self.p2 = individual_parameters(self.circuit_1,self.parameters_,self.constants_1,self.constants_2)
(circuit_1='', circuit_2='', initial_guess=[], constants=None, name=None, **kwargs)
65,050
nleis.nleis
__init__
Constructor for a customizable equivalent circuit model Parameters ---------- circuit_1: string A string that should be interpreted as an equivalent circuit for linear EIS circuit_2: string A string that should be interpreted as an equivalent circuit for NLEIS initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name: str, optional Name for the model Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)) for EIS. For NLEIS, the circuit should be grouped by d(cathode,anode) Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: A two electrode cell with sperical porous cathode and anode, resistor, and inductor is represents as, EIS: circuit_1 = 'L0-R0-TDS0-TDS1' NLEIS: circuit_2 = 'd(TDSn0-TDSn1)'
def __init__(self, circuit_1='',circuit_2='',initial_guess = [] ,constants = None, name=None, **kwargs): """ Constructor for a customizable equivalent circuit model Parameters ---------- circuit_1: string A string that should be interpreted as an equivalent circuit for linear EIS circuit_2: string A string that should be interpreted as an equivalent circuit for NLEIS initial_guess: numpy array Initial guess of the circuit values constants : dict, optional Parameters and values to hold constant during fitting (e.g. {"R0": 0.1}) name: str, optional Name for the model Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)) for EIS. For NLEIS, the circuit should be grouped by d(cathode,anode) Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: A two electrode cell with sperical porous cathode and anode, resistor, and inductor is represents as, EIS: circuit_1 = 'L0-R0-TDS0-TDS1' NLEIS: circuit_2 = 'd(TDSn0-TDSn1)' """ # if supplied, check that initial_guess is valid and store initial_guess = [x for x in initial_guess if x is not None] for i in initial_guess: if not isinstance(i, (float, int, np.int32, np.float64)): raise TypeError(f'value {i} in initial_guess is not a number') # initalize class attributes # self.initial_guess = list(initial_guess) self.initial_guess = initial_guess self.circuit_1 = circuit_1 self.circuit_2 = circuit_2 elements_1 = extract_circuit_elements(circuit_1) elements_2 = extract_circuit_elements(circuit_2) for element in elements_2: if element.replace('n', '') not in elements_1 or ('n' not in element and element != ''): raise TypeError('The pairing of linear and nonlinear elements must be presented correctly for simultaneous fitting.'+ ' Double check the EIS circuit: ' + f'{circuit_1}' + ' and the NLEIS circuit: '+ f'{circuit_2}' +'. The parsed elements are '+f'{elements_1}'+' for circuit_1, and ' + f'{elements_2}'+ ' for circuit_2.') input_elements = elements_1 + elements_2 if constants is not None: self.constants = constants self.constants_1 = {} self.constants_2 = {} ## New code for constant separatation ## in the current development the differentiation between linear and nonlinear is separated by 'n' ## using get_element_from_name to get the raw element and adding n to the end for elem in self.constants: raw_elem = get_element_from_name(elem) raw_circuit_elem = elem.split('_')[0] if raw_circuit_elem not in input_elements: raise ValueError(f'{raw_elem} not in ' + f'input elements ({input_elements})') raw_num_params = check_and_eval(raw_elem).num_params if raw_num_params<=1: ## currently there is no single parameter nonlinear element, ## so this can work, but might be changed in the future self.constants_1[elem]=self.constants[elem] else: param_num = int(elem.split('_')[-1]) if raw_elem[-1] != 'n': if param_num>=raw_num_params: raise ValueError(f'{elem} is out of the range of the maximum allowed ' + f'number of parameters ({raw_num_params})') self.constants_1[elem]=self.constants[elem] len_elem = len(raw_elem) nl_elem = elem[0:len_elem]+'n'+elem[len_elem:] raw_nl_elem = get_element_from_name(nl_elem) if raw_nl_elem in circuit_elements.keys(): self.constants_2[nl_elem]=self.constants[elem] else: self.constants_2[elem]=self.constants[elem] if raw_elem[-1] == 'n': if param_num>=raw_num_params: raise ValueError(f'{elem} is out of the range of the maximum allowed ' + f'number of parameters ({raw_num_params})') num_params = check_and_eval(raw_elem[0:-1]).num_params len_elem = len(raw_elem[0:-1]) if param_num<num_params: self.constants_1[elem[0:len_elem]+elem[len_elem+1:]]=self.constants[elem] self.constants_2[elem]=self.constants[elem] else: self.constants = {} self.constants_1 = {} self.constants_2 = {} ### new code for circuit length calculation using circuit element ### producing edited circuit ### i.e. circuit_1 = L0-R0-TDP0-TDS1; circuit_2 = TDPn0-TDSn1; edited_circuit = L0-R0-TDPn0-TDSn1 if elements_1 != [''] or elements_2 !=['']: if elements_1 == [''] or elements_2 ==['']: raise ValueError('Either circuit_1 or circuit_2 cannot be empty') edited_circuit = '' for elem in elements_1: nl_elem = elem[0:-1]+'n'+elem[-1] if nl_elem in elements_2: edited_circuit += '-'+ nl_elem else: edited_circuit += '-'+ elem self.edited_circuit = edited_circuit[1:] else: self.edited_circuit = '' circuit_len = calculateCircuitLength(self.edited_circuit) if len(self.initial_guess) + len(self.constants) != circuit_len: raise ValueError('The number of initial guesses ' + f'({len(self.initial_guess)}) + ' + 'the number of constants ' + f'({len(self.constants)})' + ' must be equal to ' + f'the circuit length ({circuit_len})') self.name = name # initialize fit parameters and confidence intervals self.parameters_ = None self.conf_ = None self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2)
(self, circuit_1='', circuit_2='', initial_guess=[], constants=None, name=None, **kwargs)
65,051
nleis.nleis
__str__
Defines the pretty printing of the circuit
def __str__(self): """ Defines the pretty printing of the circuit """ to_print = '\n' if self.name is not None: to_print += 'Name: {}\n'.format(self.name) to_print += 'EIS Circuit string: {}\n'.format(self.circuit_1) to_print += 'NLEIS Circuit string: {}\n'.format(self.circuit_2) to_print += "Fit: {}\n".format(self._is_fit()) if len(self.constants) > 0: to_print += '\nConstants:\n' for name, value in self.constants.items(): elem = get_element_from_name(name) units = check_and_eval(elem).units if '_' in name: unit = units[int(name.split('_')[-1])] else: unit = units[0] to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, value, unit) names1, units1= self.get_param_names(self.circuit_1,self.constants_1) names2, units2 = self.get_param_names(self.circuit_2,self.constants_2) to_print += '\nEIS Initial guesses:\n' p1, p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) for name, unit, param in zip(names1, units1, p1): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) to_print += '\nNLEIS Initial guesses:\n' for name, unit, param in zip(names2, units2, p2): to_print += ' {:>5} = {:.2e} [{}]\n'.format(name, param, unit) if self._is_fit(): params1, confs1 = self.p1, self.conf1 to_print += '\nEIS Fit parameters:\n' for name, unit, param, conf in zip(names1, units1, params1, confs1): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) params2, confs2 = self.p2, self.conf2 to_print += '\nNLEIS Fit parameters:\n' for name, unit, param, conf in zip(names2, units2, params2, confs2): to_print += ' {:>5} = {:.2e}'.format(name, param) to_print += ' (+/- {:.2e}) [{}]\n'.format(conf, unit) return to_print
(self)
65,052
nleis.nleis
_is_fit
check if model has been fit (parameters_ is not None)
def _is_fit(self): """ check if model has been fit (parameters_ is not None) """ if self.parameters_ is not None: return True else: return False
(self)
65,053
nleis.nleis
extract
extract the printing of the circuit in a dictionary
def extract(self): """ extract the printing of the circuit in a dictionary """ names1, units1 = self.get_param_names(self.circuit_1,self.constants_1) dic1={} if self._is_fit(): params1 = self.p1 for names, param in zip(names1, params1): dic1[names] = param names2, units2 = self.get_param_names(self.circuit_2,self.constants_2) dic2={} if self._is_fit(): params2 = self.p2 for names, param in zip(names2, params2): dic2[names] = param return dic1,dic2
(self)
65,054
nleis.nleis
fit
Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies Z1: numpy array of dtype 'complex128' EIS values to fit Z1: numpy array of dtype 'complex128' NLEIS values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. When bounds are provided, the input will normalized to stabilize the algorithm Normalization : str, optional Default is max normalization. Other normalization will be supported in the future max_f: int The the maximum frequency of interest for NLEIS kwargs : Keyword arguments passed to simul_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self
def fit(self, frequencies, Z1,Z2, bounds = None, opt='max',max_f=10,cost = 0.5, **kwargs): """ Fit the circuit model Parameters ---------- frequencies: numpy array Frequencies Z1: numpy array of dtype 'complex128' EIS values to fit Z1: numpy array of dtype 'complex128' NLEIS values to fit bounds: 2-tuple of array_like, optional Lower and upper bounds on parameters. When bounds are provided, the input will normalized to stabilize the algorithm Normalization : str, optional Default is max normalization. Other normalization will be supported in the future max_f: int The the maximum frequency of interest for NLEIS kwargs : Keyword arguments passed to simul_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- self: returns an instance of self """ # check that inputs are valid: # frequencies: array of numbers # impedance: array of complex numbers # impedance and frequency match in length frequencies = np.array(frequencies, dtype=float) Z1 = np.array(Z1, dtype=complex) Z2 = np.array(Z2, dtype=complex) if len(frequencies) != len(Z1): raise TypeError('length of frequencies and impedance do not match for EIS') if self.initial_guess != []: parameters, conf = simul_fit(frequencies, Z1,Z2, self.circuit_1,self.circuit_2,self.edited_circuit, self.initial_guess, constants_1=self.constants_1,constants_2=self.constants_2, bounds=bounds, opt=opt,cost = cost,max_f = max_f, **kwargs) # self.parameters_ = list(parameters) self.parameters_ = parameters if conf is not None: # self.conf_ = list(conf) self.conf_ = conf self.conf1, self.conf2 = individual_parameters(self.circuit_1,self.conf_,self.constants_1,self.constants_2) self.p1, self.p2 = individual_parameters(self.circuit_1,self.parameters_,self.constants_1,self.constants_2) else: raise ValueError('no initial guess supplied') return self
(self, frequencies, Z1, Z2, bounds=None, opt='max', max_f=10, cost=0.5, **kwargs)
65,055
nleis.nleis
get_param_names
Converts circuit string to names and units
def get_param_names(self,circuit,constants): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = circuit.replace('d', '').replace('(', '').replace(')', '')#edit for nleis.py names = names.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units
(self, circuit, constants)
65,056
nleis.nleis
load
Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model
def load(self, filepath, fitted_as_initial=False): """ Imports a model from JSON Parameters ---------- filepath: str filepath to JSON file to load model from fitted_as_initial: bool If true, loads the model's fitted parameters as initial guesses Otherwise, loads the model's initial and fitted parameters as a completed model """ json_data_file = open(filepath, 'r') json_data = json.load(json_data_file) model_name = json_data["Name"] model_string_1 = json_data["Circuit String 1"] model_string_2 = json_data["Circuit String 2"] model_initial_guess = json_data["Initial Guess"] model_constants = json_data["Constants"] self.initial_guess = model_initial_guess self.circuit_1 = model_string_1 self.circuit_2 = model_string_2 self.edited_circuit = json_data["Edited Circuit Str"] self.constants = model_constants self.constants_1 =json_data["Constants 1"] self.constants_2 =json_data["Constants 2"] self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) self.name = model_name if json_data["Fit"]: if fitted_as_initial: self.initial_guess = json_data['Parameters'] self.p1, self.p2 = individual_parameters(self.circuit_1,self.initial_guess,self.constants_1,self.constants_2) else: self.parameters_ = np.array(json_data["Parameters"]) self.conf_ = np.array(json_data["Confidence"]) self.conf1, self.conf2 = individual_parameters(self.circuit_1,self.conf_,self.constants_1,self.constants_2) self.p1, self.p2 = individual_parameters(self.circuit_1,self.parameters_,self.constants_1,self.constants_2)
(self, filepath, fitted_as_initial=False)
65,057
nleis.nleis
plot
visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax : matplotlib.axes, axes to plot on f_data : np.array of type float Frequencies of input data (for Bode plots) Z1_data : np.array of type complex DESCRIPTION. The default is None. Z2_data : np.array of type complex DESCRIPTION. The default is None. kind : {'altair', 'nyquist', 'bode'} type of plot to visualize max_f : TYPE, optional DESCRIPTION. The default is 10. **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size`
def plot(self, ax=None, f_data=None, Z1_data =None, Z2_data= None, kind='nyquist', max_f = 10, **kwargs): ''' visualizes the model and optional data as a nyquist, bode, or altair (interactive) plots Parameters ---------- ax : matplotlib.axes, axes to plot on f_data : np.array of type float Frequencies of input data (for Bode plots) Z1_data : np.array of type complex DESCRIPTION. The default is None. Z2_data : np.array of type complex DESCRIPTION. The default is None. kind : {'altair', 'nyquist', 'bode'} type of plot to visualize max_f : TYPE, optional DESCRIPTION. The default is 10. **kwargs : optional If kind is 'nyquist' or 'bode', used to specify additional `matplotlib.pyplot.Line2D` properties like linewidth, line color, marker color, and labels. If kind is 'altair', used to specify nyquist height as `size` ''' if kind == 'nyquist': if ax is None: _, ax = plt.subplots(1,2,figsize=(10, 5)) ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z1_data is not None: ax[0] = plot_first(ax[0], Z1_data, scale=1, fmt='s', **kwargs) ## impedance.py style # plot_nyquist(Z1_data, ls='', marker='s', ax=ax[0], **kwargs) if Z2_data is not None: mask = mask =np.array(f_pred)<max_f ax[1] = plot_second(ax[1], Z2_data[mask], scale=1, fmt='s', **kwargs) ## impedance.py style # plot_nyquist(Z2_data, units='Ohms/A', ls='', marker='s', ax=ax[1], **kwargs) Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) ax[0] = plot_first(ax[0], Z1_fit, scale=1, fmt='-', **kwargs) # plot_nyquist(Z1_fit, ls='-', marker='', ax=ax[0], **kwargs) ax[1] = plot_second(ax[1], Z2_fit, scale=1, fmt='-', **kwargs) # plot_nyquist(Z2_fit,units='Ohms/A', ls='-', marker='', ax=ax[1], **kwargs) ax[0].legend(['data','fit']) ax[1].legend(['data','fit']) return ax elif kind == 'bode': if ax is None: _, ax = plt.subplots(2,2, figsize=(8, 8)) if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if Z1_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') ax[:,0] = plot_bode(f_data, Z1_data, ls='', marker='s', axes=ax[:,0], **kwargs) if Z2_data is not None: if f_data is None: raise ValueError('f_data must be specified if' + ' Z_data for a Bode plot') mask =np.array(f_pred)<max_f f2 = f_data[mask] Z2 = Z2_data[mask] ax[:,1] = plot_bode(f2,Z2, units='Ohms/A', ls='', marker='s', axes=ax[:,1], **kwargs) ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) f1 = f_data f2 = f_data[np.array(f_data)<max_f] ax[:,0] = plot_bode(f1, Z1_fit, ls='-', marker='o', axes=ax[:,0], **kwargs) ax[:,1] = plot_bode(f2, Z2_fit,units='Ohms/A', ls='-', marker='o', axes=ax[:,1], **kwargs) ax[0,0].set_ylabel(r'$|Z_{1}(\omega)|$ ' + '$[{}]$'.format('Ohms'), fontsize=20) ax[1,0].set_ylabel(r'$-\phi_{Z_{1}}(\omega)$ ' + r'$[^o]$', fontsize=20) ax[0,1].set_ylabel(r'$|Z_{2}(\omega)|$ ' + '$[{}]$'.format('Ohms/A'), fontsize=20) ax[1,1].set_ylabel(r'$-\phi_{Z_{2}}(\omega)$ ' + r'$[^o]$', fontsize=20) ax[0,0].legend(['Data','Fit'],fontsize=20) ax[0,1].legend(['Data','Fit'],fontsize=20) ax[1,0].legend(['Data','Fit'],fontsize=20) ax[1,1].legend(['Data','Fit'],fontsize=20) return ax elif kind == 'altair': plot_dict_1 = {} plot_dict_2 = {} if Z1_data is not None and Z2_data is not None and f_data is not None: plot_dict_1['data'] = {'f': f_data, 'Z': Z1_data} mask = np.array(f_data)<max_f plot_dict_2['data'] = {'f': f_data[mask], 'Z': Z2_data[mask]} ## we don't need the if else statement if we want to enable plot without fit # if self._is_fit(): if f_data is not None: f_pred = f_data else: f_pred = np.logspace(5, -3) if self.name is not None: name = self.name else: name = 'fit' Z1_fit,Z2_fit = self.predict(f_pred,max_f=max_f) mask = np.array(f_pred)<max_f plot_dict_1[name] = {'f': f_pred, 'Z': Z1_fit, 'fmt': '-'} plot_dict_2[name] = {'f': f_pred[mask], 'Z': Z2_fit, 'fmt': '-'} chart1 = plot_altair(plot_dict_1,k=1,units = 'Ω', **kwargs) chart2 = plot_altair(plot_dict_2,k=2,units = 'Ω/A', **kwargs) return chart1,chart2 else: raise ValueError("Kind must be one of 'altair'," + f"'nyquist', or 'bode' (received {kind})")
(self, ax=None, f_data=None, Z1_data=None, Z2_data=None, kind='nyquist', max_f=10, **kwargs)
65,058
nleis.nleis
predict
Predict impedance using an equivalent circuit model Parameters ---------- frequencies: ndarray of numeric dtype max_f: int The the maximum frequency of interest for NLEIS use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance
def predict(self, frequencies, max_f=10, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: ndarray of numeric dtype max_f: int The the maximum frequency of interest for NLEIS use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance """ if not isinstance(frequencies, np.ndarray): raise TypeError('frequencies is not of type np.ndarray') if not (np.issubdtype(frequencies.dtype, np.integer) or np.issubdtype(frequencies.dtype, np.floating)): raise TypeError('frequencies array should have a numeric ' + f'dtype (currently {frequencies.dtype})') f1 =frequencies mask = np.array(frequencies)<max_f f2 = frequencies[mask] if self._is_fit() and not use_initial: x1,x2 = wrappedImpedance(self.circuit_1, self.constants_1,self.circuit_2,self.constants_2,f1,f2,self.parameters_) return x1,x2 else: warnings.warn("Simulating circuit based on initial parameters") x1,x2 = wrappedImpedance(self.circuit_1, self.constants_1,self.circuit_2,self.constants_2,f1,f2,self.initial_guess) return(x1,x2)
(self, frequencies, max_f=10, use_initial=False)
65,059
nleis.nleis
save
Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object
def save(self, filepath): """ Exports a model to JSON Parameters ---------- filepath: str Destination for exporting model object """ model_string_1 = self.circuit_1 model_string_2 = self.circuit_2 edited_circuit_str = self.edited_circuit model_name = self.name initial_guess = self.initial_guess if self._is_fit(): parameters_ = list(self.parameters_) model_conf_ = list(self.conf_) # parameters_ = self.parameters_ # model_conf_ = self.conf_ data_dict = {"Name": model_name, "Circuit String 1": model_string_1, "Circuit String 2": model_string_2, "Initial Guess": initial_guess, "Constants": self.constants, "Constants 1": self.constants_1, "Constants 2": self.constants_2, "Fit": True, "Parameters": parameters_, "Confidence": model_conf_, "Edited Circuit Str": edited_circuit_str } else: data_dict = {"Name": model_name, "Circuit String 1": model_string_1, "Circuit String 2": model_string_2, "Initial Guess": initial_guess, "Constants": self.constants, "Constants 1": self.constants_1, "Constants 2": self.constants_2, "Edited Circuit Str": edited_circuit_str, "Fit": False} with open(filepath, 'w') as f: json.dump(data_dict, f)
(self, filepath)
65,060
impedance.models.circuits.elements
ElementError
null
class ElementError(Exception): ...
null
65,061
nleis.nleis
NLEISCustomCircuit
null
class NLEISCustomCircuit(BaseCircuit): ### this class can be fully integrated into CustomCircuit in the future ### , but for the stable performance of nleis.py, we overwrite it here def __init__(self, circuit='', **kwargs): """ Constructor for a customizable equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values circuit: string A string that should be interpreted as an equivalent circuit Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)). Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: Randles circuit is given by 'R0-p(R1-Wo1,C1)' """ super().__init__(**kwargs) self.circuit = circuit.replace(" ", "") circuit_len = calculateCircuitLength(self.circuit) if len(self.initial_guess) + len(self.constants) != circuit_len: raise ValueError('The number of initial guesses ' + f'({len(self.initial_guess)}) + ' + 'the number of constants ' + f'({len(self.constants)})' + ' must be equal to ' + f'the circuit length ({circuit_len})') def fit(self, frequencies, impedance, bounds=None, weight_by_modulus=False, max_f =10, **kwargs): ''' Fit the circuit model Parameters ---------- frequencies : numpy array Frequencies. impedance : numpy array of dtype 'complex128' Impedance values to fit. bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. weight_by_modulus : bool, optional Uses the modulus of each data (`|Z|`) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False max_f : float , 10 Truncation for 2nd-NLEIS based on previous experiments. The default is 10. **kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping. Raises ------ TypeError DESCRIPTION. ValueError DESCRIPTION. Returns ------- self: returns an instance of self ''' frequencies = np.array(frequencies, dtype=float) impedance = np.array(impedance, dtype=complex) if len(frequencies) != len(impedance): raise TypeError('length of frequencies and impedance do not match') mask = np.array(frequencies)<max_f frequencies = frequencies[mask] impedance = impedance[mask] if self.initial_guess != []: parameters, conf = circuit_fit(frequencies, impedance, self.circuit, self.initial_guess, constants=self.constants, bounds=bounds, weight_by_modulus=weight_by_modulus, **kwargs) self.parameters_ = parameters if conf is not None: self.conf_ = conf else: raise ValueError('No initial guess supplied') return self def predict(self, frequencies, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency """ frequencies = np.array(frequencies, dtype=float) if self._is_fit() and not use_initial: return eval(buildCircuit(self.circuit, frequencies, *self.parameters_, constants=self.constants, eval_string='', index=0)[0], circuit_elements) else: warnings.warn("Simulating circuit based on initial parameters") return eval(buildCircuit(self.circuit, frequencies, *self.initial_guess, constants=self.constants, eval_string='', index=0)[0], circuit_elements) def get_param_names(self): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = self.circuit.replace('d', '').replace('(', '').replace(')', '')#edited for nleis.py names = names.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in self.constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in self.constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units def extract(self): """ extract the printing of the circuit """ names, units = self.get_param_names() dic={} if self._is_fit(): params, confs = self.parameters_, self.conf_ for name, unit, param, conf in zip(names, units, params, confs): dic[name] = param return dic
(circuit='', **kwargs)
65,063
nleis.nleis
__init__
Constructor for a customizable equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values circuit: string A string that should be interpreted as an equivalent circuit Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)). Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: Randles circuit is given by 'R0-p(R1-Wo1,C1)'
def __init__(self, circuit='', **kwargs): """ Constructor for a customizable equivalent circuit model Parameters ---------- initial_guess: numpy array Initial guess of the circuit values circuit: string A string that should be interpreted as an equivalent circuit Notes ----- A custom circuit is defined as a string comprised of elements in series (separated by a `-`) and elements in parallel (grouped as (x,y)). Each element can be appended with an integer (e.g. R0) or an underscore and an integer (e.g. CPE_1) to make keeping track of multiple elements of the same type easier. Example: Randles circuit is given by 'R0-p(R1-Wo1,C1)' """ super().__init__(**kwargs) self.circuit = circuit.replace(" ", "") circuit_len = calculateCircuitLength(self.circuit) if len(self.initial_guess) + len(self.constants) != circuit_len: raise ValueError('The number of initial guesses ' + f'({len(self.initial_guess)}) + ' + 'the number of constants ' + f'({len(self.constants)})' + ' must be equal to ' + f'the circuit length ({circuit_len})')
(self, circuit='', **kwargs)
65,066
nleis.nleis
extract
extract the printing of the circuit
def extract(self): """ extract the printing of the circuit """ names, units = self.get_param_names() dic={} if self._is_fit(): params, confs = self.parameters_, self.conf_ for name, unit, param, conf in zip(names, units, params, confs): dic[name] = param return dic
(self)
65,067
nleis.nleis
fit
Fit the circuit model Parameters ---------- frequencies : numpy array Frequencies. impedance : numpy array of dtype 'complex128' Impedance values to fit. bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. weight_by_modulus : bool, optional Uses the modulus of each data (`|Z|`) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False max_f : float , 10 Truncation for 2nd-NLEIS based on previous experiments. The default is 10. **kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping. Raises ------ TypeError DESCRIPTION. ValueError DESCRIPTION. Returns ------- self: returns an instance of self
def fit(self, frequencies, impedance, bounds=None, weight_by_modulus=False, max_f =10, **kwargs): ''' Fit the circuit model Parameters ---------- frequencies : numpy array Frequencies. impedance : numpy array of dtype 'complex128' Impedance values to fit. bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. weight_by_modulus : bool, optional Uses the modulus of each data (`|Z|`) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False max_f : float , 10 Truncation for 2nd-NLEIS based on previous experiments. The default is 10. **kwargs : Keyword arguments passed to impedance.models.circuits.fitting.circuit_fit, and subsequently to scipy.optimize.curve_fit or scipy.optimize.basinhopping. Raises ------ TypeError DESCRIPTION. ValueError DESCRIPTION. Returns ------- self: returns an instance of self ''' frequencies = np.array(frequencies, dtype=float) impedance = np.array(impedance, dtype=complex) if len(frequencies) != len(impedance): raise TypeError('length of frequencies and impedance do not match') mask = np.array(frequencies)<max_f frequencies = frequencies[mask] impedance = impedance[mask] if self.initial_guess != []: parameters, conf = circuit_fit(frequencies, impedance, self.circuit, self.initial_guess, constants=self.constants, bounds=bounds, weight_by_modulus=weight_by_modulus, **kwargs) self.parameters_ = parameters if conf is not None: self.conf_ = conf else: raise ValueError('No initial guess supplied') return self
(self, frequencies, impedance, bounds=None, weight_by_modulus=False, max_f=10, **kwargs)
65,068
nleis.nleis
get_param_names
Converts circuit string to names and units
def get_param_names(self): """ Converts circuit string to names and units """ # parse the element names from the circuit string names = self.circuit.replace('d', '').replace('(', '').replace(')', '')#edited for nleis.py names = names.replace('p', '').replace('(', '').replace(')', '') names = names.replace(',', '-').replace(' ', '').split('-') full_names, all_units = [], [] for name in names: elem = get_element_from_name(name) num_params = check_and_eval(elem).num_params units = check_and_eval(elem).units if num_params > 1: for j in range(num_params): full_name = '{}_{}'.format(name, j) if full_name not in self.constants.keys(): full_names.append(full_name) all_units.append(units[j]) else: if name not in self.constants.keys(): full_names.append(name) all_units.append(units[0]) return full_names, all_units
(self)
65,071
nleis.nleis
predict
Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency
def predict(self, frequencies, use_initial=False): """ Predict impedance using an equivalent circuit model Parameters ---------- frequencies: array-like of numeric type use_initial: boolean If true and the model was previously fit use the initial parameters instead Returns ------- impedance: ndarray of dtype 'complex128' Predicted impedance at each frequency """ frequencies = np.array(frequencies, dtype=float) if self._is_fit() and not use_initial: return eval(buildCircuit(self.circuit, frequencies, *self.parameters_, constants=self.constants, eval_string='', index=0)[0], circuit_elements) else: warnings.warn("Simulating circuit based on initial parameters") return eval(buildCircuit(self.circuit, frequencies, *self.initial_guess, constants=self.constants, eval_string='', index=0)[0], circuit_elements)
(self, frequencies, use_initial=False)
65,073
impedance.models.circuits.elements
OverwriteError
null
class OverwriteError(ElementError): ...
null
65,074
nleis.nleis_elements_pair
RCD
EIS: Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0 = Rct p1 = Cdl p2 = Aw p3 = τd [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,075
nleis.nleis_elements_pair
RCDn
2nd-NLEIS: Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0 = Rct p1 = Cdl p2 = Aw p3 = τd p4 = κ p5 = ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,076
nleis.nleis_elements_pair
RCO
EIS: Randles circuit Notes ----- .. math:: p0 = Rct p1 = Cdl
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,077
nleis.nleis_elements_pair
RCOn
2nd-NLEIS: Randles circuit from Ji et al. [1] Notes ----- .. math:: p0 = Rct p1 = Cdl p2 = ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,078
nleis.nleis_elements_pair
RCS
EIS: Randles circuit with spherical diffusion from Ji et al. [1] Notes ----- .. math:: p0 = Rct p1 = Cdl p2 = Aw p3 = τd [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,079
nleis.nleis_elements_pair
RCSn
2nd-NLEIS: Randles circuit with spherical diffusion from Ji et al. [1] Notes ----- .. math:: p0 = Rct p1 = Cdl p2 = Aw p3 = τd p4 = κ p5 = ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,080
nleis.nleis_elements_pair
TDC
EIS: A macrohomogeneous porous electrode model with cylindrical diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0=Rpore p1=Rct p2=Cdl p3=Aw p4=τd [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,081
nleis.nleis_elements_pair
TDCn
2nd-NLEIS: A macrohomogeneous porous electrode model with cylindrical diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0=Rpore p1=Rct p2=Cdl p3=Aw p4=τd p5=κ p6=ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,082
nleis.nleis_elements_pair
TDP
EIS: A macrohomogeneous porous electrode model with planar diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0 = Rpore p1 = Rct p2 = Cdl p3 = Aw p4 = τd [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,083
nleis.nleis_elements_pair
TDPn
2nd-NLEIS: A macrohomogeneous porous electrode model with planar diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0 = Rpore p1 = Rct p2 = Cdl p3 = Aw p4 = τd p5 = κ p6 = ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,084
nleis.nleis_elements_pair
TDS
EIS: A macrohomogeneous porous electrode model with spherical diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0=Rpore p1=Rct p2=Cdl p3=Aw p4=τd [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,085
nleis.nleis_elements_pair
TDSn
2nd-NLEIS: A macrohomogeneous porous electrode model with spherical diffusion and zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0=Rpore p1=Rct p2=Cdl p3=Aw p4=τd p5=κ p6=ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,086
nleis.nleis_elements_pair
TLM
EIS: General discrete transmission line model built Randles circuit Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Rct,surface p4: Cdl,surface p5: N (number of circuit element)
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,087
nleis.nleis_elements_pair
TLMD
EIS: general discrete transmission line model built based on the Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,088
nleis.nleis_elements_pair
TLMDn
2nd-NLEIS: Second harmonic nonlinear discrete transmission line model built based on the Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) p8: κ,bulk p9: ε,bulk p10: ε,surface
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,089
nleis.nleis_elements_pair
TLMS
EIS: General discrete transmission line model built based on the Randles circuit with spherical diffusion from Ji et al.[1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,090
nleis.nleis_elements_pair
TLMSn
2nd-NLEIS: Second harmonic nonlinear discrete transmission line model built based on the Randles circuit with spherical diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) p8: κ,bulk p9: ε,bulk p10: ε,surface
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,091
nleis.nleis_elements_pair
TLMn
2nd-NLEIS: Second harmonic nonlinear discrete transmission line model built based on the nonlinear Randles circuit from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Rct,surface p4: Cdl,surface p5: N (number of circuit element) p6: ε,bulk p7: ε,surface [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,092
nleis.nleis_elements_pair
TPO
EIS: A macrohomogeneous porous electrode model with zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0=Rpore p1=Rct p2=Cdl [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,093
nleis.nleis_elements_pair
TPOn
2nd-NLEIS: A macrohomogeneous porous electrode model with zero solid resistivity from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct p2: Cdl p3: ε [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,094
nleis.fitting
buildCircuit
recursive function that transforms a circuit, parameters, and frequencies into a string that can be evaluated Parameters ---------- circuit: str frequencies: list/tuple/array of floats parameters: list/tuple/array of floats constants: dict Returns ------- eval_string: str Python expression for calculating the resulting fit index: int Tracks parameter index through recursive calling of the function
def buildCircuit(circuit, frequencies, *parameters, constants=None, eval_string='', index=0): """ recursive function that transforms a circuit, parameters, and frequencies into a string that can be evaluated Parameters ---------- circuit: str frequencies: list/tuple/array of floats parameters: list/tuple/array of floats constants: dict Returns ------- eval_string: str Python expression for calculating the resulting fit index: int Tracks parameter index through recursive calling of the function """ parameters = np.array(parameters).tolist() frequencies = np.array(frequencies).tolist() circuit = circuit.replace(' ', '') def parse_circuit(circuit, parallel=False, series=False,difference=False): """ Splits a circuit string by either dashes (series) or commas (parallel) outside of any paranthesis. Removes any leading 'p(' or trailing ')' when in parallel mode or 'd('or trailing ')' when in difference mode '' """ assert parallel != series or series != difference or difference != parallel, \ 'Exactly one of parallel or series or difference must be True' def count_parens(string): return string.count('('), string.count(')') if parallel: special = ',' if circuit.endswith(')') and circuit.startswith('p('): circuit = circuit[2:-1] if difference: special = ',' if circuit.endswith(')') and circuit.startswith('d('): circuit = circuit[2:-1] if series: special = '-' split = circuit.split(special) result = [] skipped = [] for i, sub_str in enumerate(split): if i not in skipped: if '(' not in sub_str and ')' not in sub_str: result.append(sub_str) else: open_parens, closed_parens = count_parens(sub_str) if open_parens == closed_parens: result.append(sub_str) else: uneven = True while i < len(split) - 1 and uneven: sub_str += special + split[i+1] open_parens, closed_parens = count_parens(sub_str) uneven = open_parens != closed_parens i += 1 skipped.append(i) result.append(sub_str) return result parallel = parse_circuit(circuit, parallel=True) series = parse_circuit(circuit, series=True) difference = parse_circuit(circuit, difference=True) if series is not None and len(series) > 1: eval_string += "s([" split = series elif parallel is not None and len(parallel) > 1: eval_string += "p([" split = parallel ## added for nleis.py elif difference is not None and len(difference) > 1: eval_string += "d([" split = difference elif series == parallel == difference : # only single element split = series for i, elem in enumerate(split): if ',' in elem or '-' in elem : eval_string, index = buildCircuit(elem, frequencies, *parameters, constants=constants, eval_string=eval_string, index=index) else: param_string = "" raw_elem = get_element_from_name(elem) elem_number = check_and_eval(raw_elem).num_params param_list = [] for j in range(elem_number): if elem_number > 1: current_elem = elem + '_{}'.format(j) else: current_elem = elem if current_elem in constants.keys(): param_list.append(constants[current_elem]) else: param_list.append(parameters[index]) index += 1 param_string += str(param_list) new = raw_elem + '(' + param_string + ',' + str(frequencies) + ')' eval_string += new if i == len(split) - 1: if len(split) > 1: # do not add closing brackets if single element eval_string += '])' else: eval_string += ',' return eval_string, index
(circuit, frequencies, *parameters, constants=None, eval_string='', index=0)
65,095
nleis.fitting
calculateCircuitLength
Calculates the number of elements in the circuit. Parameters ---------- circuit : str Circuit string. Returns ------- length : int Length of circuit.
def calculateCircuitLength(circuit): """ Calculates the number of elements in the circuit. Parameters ---------- circuit : str Circuit string. Returns ------- length : int Length of circuit. """ length = 0 if circuit: extracted_elements = extract_circuit_elements(circuit) for elem in extracted_elements: raw_element = get_element_from_name(elem) num_params = check_and_eval(raw_element).num_params length += num_params return length
(circuit)
65,096
impedance.models.circuits.fitting
check_and_eval
Checks if an element is valid, then evaluates it. Parameters ---------- element : str Circuit element. Raises ------ ValueError Raised if an element is not in the list of allowed elements. Returns ------- Evaluated element.
def check_and_eval(element): """ Checks if an element is valid, then evaluates it. Parameters ---------- element : str Circuit element. Raises ------ ValueError Raised if an element is not in the list of allowed elements. Returns ------- Evaluated element. """ allowed_elements = circuit_elements.keys() if element not in allowed_elements: raise ValueError(f'{element} not in ' + f'allowed elements ({allowed_elements})') else: return eval(element, circuit_elements)
(element)
65,097
nleis.fitting
circuit_fit
Main function for fitting an equivalent circuit to data. By default, this function uses `scipy.optimize.curve_fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>`_ to fit the equivalent circuit. This function generally works well for simple circuits. However, the final results may be sensitive to the initial conditions for more complex circuits. In these cases, the `scipy.optimize.basinhopping <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html>`_ global optimization algorithm can be used to attempt a better fit. Parameters ---------- frequencies : numpy array Frequencies impedances : numpy array of dtype 'complex128' Impedances circuit : string String defining the equivalent circuit to be fit initial_guess : list of floats Initial guesses for the fit parameters constants : dictionary, optional Parameters and their values to hold constant during fitting (e.g. {"RO": 0.1}). Defaults to {} bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 weight_by_modulus : bool, optional Uses the modulus of each data (`|Z|`) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False global_opt : bool, optional If global optimization should be used (uses the basinhopping algorithm). Defaults to False kwargs : Keyword arguments passed to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- p_values : list of floats best fit parameters for specified equivalent circuit p_errors : list of floats one standard deviation error estimates for fit parameters Notes ----- Need to do a better job of handling errors in fitting. Currently, an error of -1 is returned.
def circuit_fit(frequencies, impedances, circuit, initial_guess, constants={}, bounds=None, weight_by_modulus=False, global_opt=False, **kwargs): """ Main function for fitting an equivalent circuit to data. By default, this function uses `scipy.optimize.curve_fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>`_ to fit the equivalent circuit. This function generally works well for simple circuits. However, the final results may be sensitive to the initial conditions for more complex circuits. In these cases, the `scipy.optimize.basinhopping <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html>`_ global optimization algorithm can be used to attempt a better fit. Parameters ---------- frequencies : numpy array Frequencies impedances : numpy array of dtype 'complex128' Impedances circuit : string String defining the equivalent circuit to be fit initial_guess : list of floats Initial guesses for the fit parameters constants : dictionary, optional Parameters and their values to hold constant during fitting (e.g. {"RO": 0.1}). Defaults to {} bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 weight_by_modulus : bool, optional Uses the modulus of each data (`|Z|`) as the weighting factor. Standard weighting scheme when experimental variances are unavailable. Only applicable when global_opt = False global_opt : bool, optional If global optimization should be used (uses the basinhopping algorithm). Defaults to False kwargs : Keyword arguments passed to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- p_values : list of floats best fit parameters for specified equivalent circuit p_errors : list of floats one standard deviation error estimates for fit parameters Notes ----- Need to do a better job of handling errors in fitting. Currently, an error of -1 is returned. """ f = np.array(frequencies, dtype=float) Z = np.array(impedances, dtype=complex) # set upper and lower bounds on a per-element basis if bounds is None: bounds = set_default_bounds(circuit, constants=constants) if not global_opt: if 'maxfev' not in kwargs: kwargs['maxfev'] = int(1e5) if 'ftol' not in kwargs: kwargs['ftol'] = 1e-13 # weighting scheme for fitting if weight_by_modulus: abs_Z = np.abs(Z) kwargs['sigma'] = np.hstack([abs_Z, abs_Z]) popt, pcov = curve_fit(wrapCircuit(circuit, constants), f, np.hstack([Z.real, Z.imag]), p0=initial_guess, bounds=bounds, **kwargs) # Calculate one standard deviation error estimates for fit parameters, # defined as the square root of the diagonal of the covariance matrix. # https://stackoverflow.com/a/52275674/5144795 perror = np.sqrt(np.diag(pcov)) else: if 'seed' not in kwargs: kwargs['seed'] = 0 def opt_function(x): """ Short function for basinhopping to optimize over. We want to minimize the RMSE between the fit and the data. Parameters ---------- x : args Parameters for optimization. Returns ------- function Returns a function (RMSE as a function of parameters). """ return rmse(wrapCircuit(circuit, constants)(f, *x), np.hstack([Z.real, Z.imag])) class BasinhoppingBounds(object): """ Adapted from the basinhopping documetation https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html """ def __init__(self, xmin, xmax): self.xmin = np.array(xmin) self.xmax = np.array(xmax) def __call__(self, **kwargs): x = kwargs['x_new'] tmax = bool(np.all(x <= self.xmax)) tmin = bool(np.all(x >= self.xmin)) return tmax and tmin basinhopping_bounds = BasinhoppingBounds(xmin=bounds[0], xmax=bounds[1]) results = basinhopping(opt_function, x0=initial_guess, accept_test=basinhopping_bounds, **kwargs) popt = results.x # Calculate perror jac = results.lowest_optimization_result['jac'][np.newaxis] try: # jacobian -> covariance # https://stats.stackexchange.com/q/231868 pcov = inv(np.dot(jac.T, jac)) * opt_function(popt) ** 2 # covariance -> perror (one standard deviation # error estimates for fit parameters) perror = np.sqrt(np.diag(pcov)) except (ValueError, np.linalg.LinAlgError): warnings.warn('Failed to compute perror') perror = None return popt, perror
(frequencies, impedances, circuit, initial_guess, constants={}, bounds=None, weight_by_modulus=False, global_opt=False, **kwargs)
65,098
nleis.nleis_elements_pair
d
Subtract the second electrode from the first electrode in 2nd-NLEIS Notes ----- .. math::
def d(difference): ''' Subtract the second electrode from the first electrode in 2nd-NLEIS Notes ----- .. math:: ''' z = len(difference[0])*[0 + 0*1j] z += difference[0] z += -difference[-1] return z
(difference)
65,099
nleis.nleis_elements_pair
element
decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(num_params, units, overwrite=False)
65,100
nleis.fitting
extract_circuit_elements
Extracts circuit elements from a circuit string. Parameters ---------- circuit : str Circuit string. Returns ------- extracted_elements : list list of extracted elements.
def extract_circuit_elements(circuit): """ Extracts circuit elements from a circuit string. Parameters ---------- circuit : str Circuit string. Returns ------- extracted_elements : list list of extracted elements. """ p_string = [x for x in circuit if x not in 'p(),-,d()'] extracted_elements = [] current_element = [] length = len(p_string) for i, char in enumerate(p_string): if char not in ints: current_element.append(char) else: # min to prevent looking ahead past end of list if p_string[min(i+1, length-1)] not in ints: current_element.append(char) extracted_elements.append(''.join(current_element)) current_element = [] else: current_element.append(char) extracted_elements.append(''.join(current_element)) return extracted_elements
(circuit)
65,102
impedance.models.circuits.elements
get_element_from_name
null
def get_element_from_name(name): excluded_chars = "0123456789_" return "".join(char for char in name if char not in excluded_chars)
(name)
65,103
nleis.nleis_fitting
individual_parameters
Parameters ---------- circuit : string DESCRIPTION. parameters : list of floats DESCRIPTION. constants_1 : dict DESCRIPTION. constants_2 : dict DESCRIPTION. Returns ------- TYPE DESCRIPTION. TYPE DESCRIPTION.
def individual_parameters(circuit,parameters,constants_1,constants_2): ''' Parameters ---------- circuit : string DESCRIPTION. parameters : list of floats DESCRIPTION. constants_1 : dict DESCRIPTION. constants_2 : dict DESCRIPTION. Returns ------- TYPE DESCRIPTION. TYPE DESCRIPTION. ''' if circuit == '': return [],[] parameters = list(parameters) elements_1 = extract_circuit_elements(circuit) p1 = [] p2 = [] index = 0 for elem in elements_1: raw_elem = get_element_from_name(elem) elem_number_1 = check_and_eval(raw_elem).num_params if elem[0]=='T' or elem[0:2] =='RC' : ### this might be improvable, but depends on how we want to define the name ## check for nonlinear element elem_number_2 = check_and_eval(raw_elem+'n').num_params else: elem_number_2 = elem_number_1 for j in range(elem_number_2): if elem_number_1 > 1: if j<elem_number_1: current_elem_1 = elem + '_{}'.format(j) else: current_elem_1 = None len_elem = len(raw_elem) current_elem_2 = elem[0:len_elem]+'n'+elem[len_elem:] + '_{}'.format(j) else: current_elem_1 = elem current_elem_2 = elem if current_elem_1 in constants_1.keys() : continue elif current_elem_2 in constants_2.keys() and current_elem_1 not in constants_1.keys(): continue else: if elem_number_1 ==1: p1.append(parameters[index]) elif elem_number_1>1 and j<elem_number_1: p1.append(parameters[index]) p2.append(parameters[index]) else: p2.append(parameters[index]) index += 1 return p1,p2
(circuit, parameters, constants_1, constants_2)
65,105
nleis.nleis_elements_pair
mTi
EIS: current distribution of discrete transmission line model built based on the Randles circuit from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Rct,surface p4: Cdl,surface p5: N (number of circuit element) [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,106
nleis.nleis_elements_pair
mTiD
EIS: current distribution of discrete transmission line model built based on the Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,107
nleis.nleis_elements_pair
mTiDn
2nd-NLEIS: current distribution of Second harmonic nonlinear discrete transmission line model built based on the Randles circuit with planar diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) p8: κ,bulk p9: ε,bulk p10: ε,surface
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,108
nleis.nleis_elements_pair
mTiS
EIS: current distribution of nonlinear discrete transmission line model built based on the Randles circuit with spherical diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) [1] Y. Ji, D.T. Schwartz, Second-Harmonic Nonlinear Electrochemical Impedance Spectroscopy: I. Analytical theory and equivalent circuit representations for planar and porous electrodes. J. Electrochem. Soc. (2023). `doi: 10.1149/1945-7111/ad15ca <https://doi.org/10.1149/1945-7111/ad15ca>`_.
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,109
nleis.nleis_elements_pair
mTiSn
2nd-NLEIS: nonlinear current distribution of nonlinear discrete transmission line model built based on the Randles circuit with spherical diffusion from Ji et al. [1] Notes ----- .. math:: p0: Rpore p1: Rct,bulk p2: Cdl,bulk p3: Aw,bulk p4: τ,bulk p5: Rct,surface p6: Cdl,surface p7: N (number of circuit element) p8: κ,bulk p9: ε,bulk p10: ε,surface
def element(num_params, units, overwrite=False): """ decorator to store metadata for a circuit element Parameters ---------- num_params : int number of parameters for an element units : list of str list of units for the element parameters overwrite : bool (default False) if true, overwrites any existing element; if false, raises OverwriteError if element name already exists. """ def decorator(func): def wrapper(p, f): typeChecker(p, f, func.__name__, num_params) return func(p, f) wrapper.num_params = num_params wrapper.units = units wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ global circuit_elements if func.__name__ in ["s", "p"]: raise ElementError("cannot redefine elements 's' (series)" + "or 'p' (parallel)") elif func.__name__ in circuit_elements and not overwrite: raise OverwriteError( f"element {func.__name__} already exists. " + "If you want to overwrite the existing element," + "use `overwrite=True`." ) else: circuit_elements[func.__name__] = wrapper return wrapper return decorator
(p, f)
65,114
nleis.visualization
plot_altair
Plots impedance as an interactive Nyquist/Bode plot using altair Parameters ---------- data_dict: dict dictionary with keys 'f': frequencies 'Z': impedance 'fmt': {'-' for a line, else circles} size: int size in pixels of Nyquist height/width background: str hex color string for chart background (default = '#FFFFFF') Returns ------- chart: altair.Chart
def plot_altair(data_dict,k = 1, units = 'Ω', size=400, background='#FFFFFF'): """ Plots impedance as an interactive Nyquist/Bode plot using altair Parameters ---------- data_dict: dict dictionary with keys 'f': frequencies 'Z': impedance 'fmt': {'-' for a line, else circles} size: int size in pixels of Nyquist height/width background: str hex color string for chart background (default = '#FFFFFF') Returns ------- chart: altair.Chart """ Z_df = pd.DataFrame(columns=['f', 'z_real', 'z_imag', 'kind', 'fmt']) for kind in data_dict.keys(): f = data_dict[kind]['f'] Z = data_dict[kind]['Z'] fmt = data_dict[kind].get('fmt', 'o') df = pd.DataFrame({'f': f, 'z_real': Z.real, 'z_imag': Z.imag, 'kind': kind, 'fmt': fmt}) Z_df = pd.concat([Z_df,df]) # Z_df.append(df) range_x = max(Z_df['z_real']) - min(Z_df['z_real']) range_y = max(-Z_df['z_imag']) - min(-Z_df['z_imag']) rng = max(range_x, range_y) min_x = min(Z_df['z_real']) max_x = min(Z_df['z_real']) + rng min_y = min(-Z_df['z_imag']) max_y = min(-Z_df['z_imag']) + rng nearest = alt.selection_single(on='mouseover', nearest=True, empty='none', fields=['f']) ## potential future improvement # nearest = alt.selection_point(on='mouseover', nearest=True, # empty='none', fields=['f']) fmts = Z_df['fmt'].unique() nyquists, bode_mags, bode_phss = [], [], [] if '-' in fmts: df = Z_df.groupby('fmt').get_group('-') ##### These are changed to introduce harmonics and units nyquist = alt.Chart(df).mark_line().encode( x=alt.X('z_real:Q', axis=alt.Axis(title="Z{}' [{}]".format(k, units)), scale=alt.Scale(domain=[min_x, max_x], nice=False, padding=5),sort=None), y=alt.Y('neg_z_imag:Q', axis=alt.Axis(title="-Z{}'' [{}]".format(k, units)), scale=alt.Scale(domain=[min_y, max_y], nice=False, padding=5),sort=None), color='kind:N' ).properties( height=size, width=size ).transform_calculate( neg_z_imag='-datum.z_imag' ) bode = alt.Chart(df).mark_line().encode( alt.X('f:Q', axis=alt.Axis(title="f [Hz]"), scale=alt.Scale(type='log', nice=False),sort=None), color='kind:N' ).properties( width=size, height=size/2 - 25 ).transform_calculate( mag="sqrt(pow(datum.z_real,2) + pow(datum.z_imag,2))", neg_phase="-(180/PI)*atan2(datum.z_imag,datum.z_real)" ) bode_mag = bode.encode(y=alt.Y('mag:Q', axis=alt.Axis(title="|Z{}|' [{}]".format(k, units)),sort=None)) bode_phs = bode.encode(y=alt.Y('neg_phase:Q', axis=alt.Axis(title="-ϕ [°]"),sort=None)) nyquists.append(nyquist) bode_mags.append(bode_mag) bode_phss.append(bode_phs) nyquists if 'o' in fmts: df = Z_df.groupby('fmt').get_group('o') nyquist = alt.Chart(df).mark_circle().encode( x=alt.X('z_real:Q', axis=alt.Axis(title="Z{}' [{}]".format(k, units)), scale=alt.Scale(domain=[min_x, max_x], nice=False, padding=5),sort=None), y=alt.Y('neg_z_imag:Q', axis=alt.Axis(title="-Z{}'' [{}]".format(k, units)), scale=alt.Scale(domain=[min_y, max_y], nice=False, padding=5),sort=None), size=alt.condition(nearest, alt.value(80), alt.value(30)), color=alt.Color('kind:N', legend=alt.Legend(title='Legend')) ).add_selection( nearest ).properties( height=size, width=size ).transform_calculate( neg_z_imag='-datum.z_imag' ).interactive() bode = alt.Chart(df).mark_circle().encode( alt.X('f:Q', axis=alt.Axis(title="f [Hz]"), scale=alt.Scale(type='log', nice=False),sort=None), size=alt.condition(nearest, alt.value(80), alt.value(30)), color='kind:N' ).add_selection( nearest ).properties( width=size, height=size/2 - 25 ).transform_calculate( mag="sqrt(pow(datum.z_real,2) + pow(datum.z_imag,2))", neg_phase="-(180/PI)*atan2(datum.z_imag,datum.z_real)" ).interactive() bode_mag = bode.encode(y=alt.Y('mag:Q', axis=alt.Axis(title="|Z{}|' [{}]".format(k, units)),sort=None)) bode_phs = bode.encode(y=alt.Y('neg_phase:Q', axis=alt.Axis(title="-ϕ [°]"),sort=None)) nyquists.append(nyquist) bode_mags.append(bode_mag) bode_phss.append(bode_phs) full_bode = alt.layer(*bode_mags) & alt.layer(*bode_phss) return (full_bode | alt.layer(*nyquists)).configure(background=background)
(data_dict, k=1, units='Ω', size=400, background='#FFFFFF')
65,115
impedance.visualization
plot_bode
Plots impedance as a Bode plot using matplotlib Parameters ---------- f: np.array of floats frequencies Z: np.array of complex numbers impedance data scale: float scale for the magnitude y-axis units: string units for :math:`|Z(\omega)|` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') axes: list of 2 matplotlib.axes.Axes (optional) axes on which to plot the bode plot Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes
def plot_bode(f, Z, scale=1, units='Ohms', fmt='.-', axes=None, labelsize=20, ticksize=14, **kwargs): """ Plots impedance as a Bode plot using matplotlib Parameters ---------- f: np.array of floats frequencies Z: np.array of complex numbers impedance data scale: float scale for the magnitude y-axis units: string units for :math:`|Z(\\omega)|` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') axes: list of 2 matplotlib.axes.Axes (optional) axes on which to plot the bode plot Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes """ Z = np.array(Z, dtype=complex) if axes is None: _, axes = plt.subplots(nrows=2) ax_mag, ax_phs = axes ax_mag.plot(f, np.abs(Z), fmt, **kwargs) ax_phs.plot(f, -np.angle(Z, deg=True), fmt, **kwargs) # Set the y-axis labels ax_mag.set_ylabel(r'$|Z(\omega)|$ ' + '$[{}]$'.format(units), fontsize=labelsize) ax_phs.set_ylabel(r'$-\phi_Z(\omega)$ ' + r'$[^o]$', fontsize=labelsize) for ax in axes: # Set the frequency axes title and make log scale ax.set_xlabel('f [Hz]', fontsize=labelsize) ax.set_xscale('log') # Make the tick labels larger ax.tick_params(axis='both', which='major', labelsize=ticksize) # Change the number of labels on each axis to five ax.locator_params(axis='y', nbins=5, tight=True) # Add a light grid ax.grid(visible=True, which='major', axis='both', alpha=.5) # Change axis units to 10**log10(scale) and resize the offset text limits = -np.log10(scale) if limits != 0: ax_mag.ticklabel_format(style='sci', axis='y', scilimits=(limits, limits)) y_offset = ax_mag.yaxis.get_offset_text() y_offset.set_size(18) return axes
(f, Z, scale=1, units='Ohms', fmt='.-', axes=None, labelsize=20, ticksize=14, **kwargs)
65,116
nleis.visualization
plot_first
Plots impedance as a Nyquist plot using matplotlib Parameters ---------- ax: matplotlib.axes.Axes axes on which to plot the nyquist plot Z: np.array of complex numbers impedance data scale: float the scale for the axes units: string units for :math:`Z(\omega)` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes
def plot_first(ax, Z, scale=1, fmt='.-', **kwargs): """ Plots impedance as a Nyquist plot using matplotlib Parameters ---------- ax: matplotlib.axes.Axes axes on which to plot the nyquist plot Z: np.array of complex numbers impedance data scale: float the scale for the axes units: string units for :math:`Z(\\omega)` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes """ ax.plot(np.real(Z), -np.imag(Z), fmt, **kwargs) # Make the axes square ax.set_aspect(aspect = 1 ,anchor='C',adjustable='datalim') # Set the labels to -imaginary vs real ax.set_xlabel(r'$\tilde{Z}_{1}^{\prime}(\omega)$' + ' [$\Omega$]', fontsize=20) ax.set_ylabel(r'$-\tilde{Z}_{1}^{\prime\prime}(\omega)$' + ' [$\Omega$]', fontsize=20) # Make the tick labels larger ax.tick_params(axis='both', which='major', labelsize=20) # Change the number of labels on each axis to five ax.locator_params(axis='x', nbins=5, tight=True) ax.locator_params(axis='y', nbins=5, tight=True) # Add a light grid ax.grid(visible=True, which='major', axis='both', alpha=.5) # Change axis units to 10**log10(scale) and resize the offset text #ax.ticklabel_format(style='sci', axis='both') formatter = ticker.ScalarFormatter(useMathText=True) formatter.set_scientific(True) formatter.set_powerlimits((-1,1)) ax.yaxis.set_major_formatter(formatter) ax.xaxis.set_major_formatter(formatter) limits = -np.log10(scale) if limits != 0: ax.ticklabel_format(style='sci', axis='both', scilimits=(limits, limits)) y_offset = ax.yaxis.get_offset_text() y_offset.set_size(18) t = ax.xaxis.get_offset_text() t.set_size(18) return ax
(ax, Z, scale=1, fmt='.-', **kwargs)
65,117
nleis.visualization
plot_second
Plots impedance as a Nyquist plot using matplotlib Parameters ---------- ax: matplotlib.axes.Axes axes on which to plot the nyquist plot Z: np.array of complex numbers impedance data scale: float the scale for the axes units: string units for :math:`Z(\omega)` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes
def plot_second(ax, Z, scale=1, fmt='.-', **kwargs): """ Plots impedance as a Nyquist plot using matplotlib Parameters ---------- ax: matplotlib.axes.Axes axes on which to plot the nyquist plot Z: np.array of complex numbers impedance data scale: float the scale for the axes units: string units for :math:`Z(\\omega)` fmt: string format string passed to matplotlib (e.g. '.-' or 'o') Other Parameters ---------------- **kwargs : `matplotlib.pyplot.Line2D` properties, optional Used to specify line properties like linewidth, line color, marker color, and line labels. Returns ------- ax: matplotlib.axes.Axes """ ax.plot(np.real(Z), -np.imag(Z), fmt, **kwargs) # Make the axes square ax.set_aspect(aspect = 1 ,anchor='C',adjustable='datalim') # Set the labels to -imaginary vs real ax.set_xlabel(r'$\tilde{Z}_{2}^{\prime}(\omega)$' + ' [$\Omega / A$]', fontsize=20) ax.set_ylabel(r'$-\tilde{Z}_{2}^{\prime\prime}(\omega)$' + ' [$\Omega / A$]', fontsize=20) # Make the tick labels larger ax.tick_params(axis='both', which='major', labelsize=20) # Change the number of labels on each axis to five ax.locator_params(axis='x', nbins=5, tight=True) ax.locator_params(axis='y', nbins=5, tight=True) # Add a light grid ax.grid(visible=True, which='major', axis='both', alpha=.5) # Change axis units to 10**log10(scale) and resize the offset text formatter = ticker.ScalarFormatter(useMathText=True) formatter.set_scientific(True) formatter.set_powerlimits((-1,1)) ax.yaxis.set_major_formatter(formatter) ax.xaxis.set_major_formatter(formatter) limits = -np.log10(scale) if limits != 0: ax.ticklabel_format(style='scientific', axis='both', scilimits=(limits, limits)) y_offset = ax.yaxis.get_offset_text() y_offset.set_size(18) t = ax.xaxis.get_offset_text() t.set_size(18) return ax
(ax, Z, scale=1, fmt='.-', **kwargs)
65,119
nleis.nleis_fitting
simul_fit
Main function for the simultaneous fitting of EIS and NLEIS edata. By default, this function uses `scipy.optimize.curve_fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>`_ to fit the equivalent circuit. Parameters ---------- frequencies : numpy array Frequencies Z1 : numpy array of dtype 'complex128' EIS Z1 : numpy array of dtype 'complex128' NLEIS circuit_1 : string String defining the EIS equivalent circuit to be fit circuit_2 : string String defining the NLEIS equivalent circuit to be fit initial_guess : list of floats Initial guesses for the fit parameters constants : dictionary, optional Parameters and their values to hold constant during fitting (e.g. {"RO": 0.1}). Defaults to {} bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 opt : str, optional Default is max normalization. Other normalization will be supported in the future cost : float, default = 0.5 cost function: cost > 0.5 means more weight on EIS while cost < 0.5 means more weight on NLEIS max_f: int The the maximum frequency of interest for NLEIS positive : bool, optional Defaults to True for only positive nyquist plot param_norm : bool, optional Defaults to True for better convergence kwargs : Keyword arguments passed to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- p_values : list of floats best fit parameters for EIS and NLEIS data p_errors : list of floats one standard deviation error estimates for fit parameters
def simul_fit(frequencies, Z1, Z2, circuit_1,circuit_2, edited_circuit, initial_guess, constants_1={},constants_2={}, bounds = None, opt='max',cost = 0.5,max_f=10,param_norm = True,positive = True, **kwargs): """ Main function for the simultaneous fitting of EIS and NLEIS edata. By default, this function uses `scipy.optimize.curve_fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>`_ to fit the equivalent circuit. Parameters ---------- frequencies : numpy array Frequencies Z1 : numpy array of dtype 'complex128' EIS Z1 : numpy array of dtype 'complex128' NLEIS circuit_1 : string String defining the EIS equivalent circuit to be fit circuit_2 : string String defining the NLEIS equivalent circuit to be fit initial_guess : list of floats Initial guesses for the fit parameters constants : dictionary, optional Parameters and their values to hold constant during fitting (e.g. {"RO": 0.1}). Defaults to {} bounds : 2-tuple of array_like, optional Lower and upper bounds on parameters. Defaults to bounds on all parameters of 0 and np.inf, except the CPE alpha which has an upper bound of 1 opt : str, optional Default is max normalization. Other normalization will be supported in the future cost : float, default = 0.5 cost function: cost > 0.5 means more weight on EIS while cost < 0.5 means more weight on NLEIS max_f: int The the maximum frequency of interest for NLEIS positive : bool, optional Defaults to True for only positive nyquist plot param_norm : bool, optional Defaults to True for better convergence kwargs : Keyword arguments passed to scipy.optimize.curve_fit or scipy.optimize.basinhopping Returns ------- p_values : list of floats best fit parameters for EIS and NLEIS data p_errors : list of floats one standard deviation error estimates for fit parameters """ ### Todo fix the negtive loglikelihood ### set upper and lower bounds on a per-element basis if bounds is None: combined_constant = constants_2.copy() combined_constant.update(constants_1) bounds = set_default_bounds(edited_circuit, constants=combined_constant) ub = np.ones(len(bounds[1])) else: if param_norm: ub = bounds[1] bounds = bounds/ub else: ub = np.ones(len(bounds[1])) initial_guess = initial_guess/ub if positive: mask1 = np.array(Z1.imag)<0 frequencies = frequencies[mask1] Z1 = Z1[mask1] Z2 = Z2[mask1] mask2 = np.array(frequencies)<max_f Z2 = Z2[mask2] else: mask2 = np.array(frequencies)<max_f Z2 = Z2[mask2] Z1stack = np.hstack([Z1.real, Z1.imag]) Z2stack = np.hstack([Z2.real, Z2.imag]) Zstack = np.hstack([Z1stack,Z2stack]) # weighting scheme for fitting if opt == 'max': if 'maxfev' not in kwargs: kwargs['maxfev'] = 1e5 if 'ftol' not in kwargs: kwargs['ftol'] = 1e-13 Z1max = max(np.abs(Z1)) Z2max = max(np.abs(Z2)) sigma1 = np.ones(len(Z1stack))*Z1max/(cost**0.5) sigma2 = np.ones(len(Z2stack))*Z2max/((1-cost)**0.5) kwargs['sigma'] = np.hstack([sigma1, sigma2]) popt, pcov = curve_fit(wrapCircuit_simul(circuit_1, constants_1,circuit_2,constants_2,ub,max_f), frequencies, Zstack, p0=initial_guess, bounds=bounds, **kwargs) # Calculate one standard deviation error estimates for fit parameters, # defined as the square root of the diagonal of the covariance matrix. # https://stackoverflow.com/a/52275674/5144795 # and the following for the bounded and normalized case # https://stackoverflow.com/questions/14854339/in-scipy-how-and-why-does-curve-fit-calculate-the-covariance-of-the-parameter-es perror = np.sqrt(np.diag(ub*pcov*ub.T)) return popt*ub, perror if opt == 'neg': ### This method does not provides converge solution at current development bounds = tuple(tuple((bounds[0][i], bounds[1][i])) for i in range(len(bounds[0]))) res = minimize(wrapNeg_log_likelihood(frequencies,Z1,Z2,circuit_1, constants_1,circuit_2,constants_2,ub,max_f,cost = cost), x0=initial_guess,bounds=bounds, **kwargs) return (res.x*ub,None)
(frequencies, Z1, Z2, circuit_1, circuit_2, edited_circuit, initial_guess, constants_1={}, constants_2={}, bounds=None, opt='max', cost=0.5, max_f=10, param_norm=True, positive=True, **kwargs)
65,120
nleis.nleis_elements_pair
typeChecker
null
def typeChecker(p, f, name, length): assert isinstance(p, list), \ 'in {}, input must be of type list'.format(name) for i in p: assert isinstance(i, (float, int, np.int32, np.float64)), \ 'in {}, value {} in {} is not a number'.format(name, i, p) for i in f: assert isinstance(i, (float, int, np.int32, np.float64)), \ 'in {}, value {} in {} is not a number'.format(name, i, f) assert len(p) == length, \ 'in {}, input list must be length {}'.format(name, length) return
(p, f, name, length)
65,123
nleis.nleis_fitting
wrappedImpedance
Parameters ---------- circuit_1 : string constants_1 : dict circuit_2 : string constants_2 : dict f1 : list of floats f2 : list of floats parameters : list of floats Returns ------- Z1 and Z2
def wrappedImpedance(circuit_1, constants_1,circuit_2,constants_2,f1,f2,parameters): ''' Parameters ---------- circuit_1 : string constants_1 : dict circuit_2 : string constants_2 : dict f1 : list of floats f2 : list of floats parameters : list of floats Returns ------- Z1 and Z2 ''' p1,p2 = individual_parameters(circuit_1,parameters,constants_1,constants_2) x1 = eval(buildCircuit(circuit_1, f1, *p1, constants=constants_1, eval_string='', index=0)[0], circuit_elements) x2 = eval(buildCircuit(circuit_2, f2, *p2, constants=constants_2, eval_string='', index=0)[0], circuit_elements) return(x1,x2)
(circuit_1, constants_1, circuit_2, constants_2, f1, f2, parameters)
65,127
pantab._reader
frame_from_hyper
See api.rst for documentation
def frame_from_hyper( source: Union[str, pathlib.Path], *, table: pantab_types.TableNameType, return_type: Literal["pandas", "polars", "pyarrow"] = "pandas", ): """See api.rst for documentation""" if isinstance(table, (str, tab_api.Name)) or not table.schema_name: table = tab_api.TableName("public", table) query = f"SELECT * FROM {table}" return frame_from_hyper_query(source, query, return_type=return_type)
(source: Union[str, pathlib.Path], *, table: Union[str, tableauhyperapi.name.Name, tableauhyperapi.tablename.TableName], return_type: Literal['pandas', 'polars', 'pyarrow'] = 'pandas')
65,128
pantab._reader
frame_from_hyper_query
See api.rst for documentation.
def frame_from_hyper_query( source: Union[str, pathlib.Path], query: str, *, return_type: Literal["pandas", "polars", "pyarrow"] = "pandas", ): """See api.rst for documentation.""" # Call native library to read tuples from result set capsule = libpantab.read_from_hyper_query(str(source), query) stream = pa.RecordBatchReader._import_from_c_capsule(capsule) tbl = stream.read_all() if return_type == "pyarrow": return tbl elif return_type == "polars": import polars as pl return pl.from_arrow(tbl) elif return_type == "pandas": import pandas as pd return tbl.to_pandas(types_mapper=pd.ArrowDtype) raise NotImplementedError("Please choose an appropriate 'return_type' value")
(source: Union[str, pathlib.Path], query: str, *, return_type: Literal['pandas', 'polars', 'pyarrow'] = 'pandas')
65,129
pantab._writer
frame_to_hyper
See api.rst for documentation
def frame_to_hyper( df, database: Union[str, pathlib.Path], *, table: pantab_types.TableNameType, table_mode: Literal["a", "w"] = "w", not_null_columns: Optional[set[str]] = None, json_columns: Optional[set[str]] = None, geo_columns: Optional[set[str]] = None, ) -> None: """See api.rst for documentation""" frames_to_hyper( {table: df}, database, table_mode=table_mode, not_null_columns=not_null_columns, json_columns=json_columns, geo_columns=geo_columns, )
(df, database: Union[str, pathlib.Path], *, table: Union[str, tableauhyperapi.name.Name, tableauhyperapi.tablename.TableName], table_mode: Literal['a', 'w'] = 'w', not_null_columns: Optional[set[str]] = None, json_columns: Optional[set[str]] = None, geo_columns: Optional[set[str]] = None) -> NoneType
65,130
pantab._reader
frames_from_hyper
See api.rst for documentation.
def frames_from_hyper( source: Union[str, pathlib.Path], return_type: Literal["pandas", "polars", "pyarrow"] = "pandas", ): """See api.rst for documentation.""" result = {} table_names = [] with tempfile.TemporaryDirectory() as tmp_dir, tab_api.HyperProcess( tab_api.Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU ) as hpe: tmp_db = shutil.copy(source, tmp_dir) with tab_api.Connection(hpe.endpoint, tmp_db) as connection: for schema in connection.catalog.get_schema_names(): for table in connection.catalog.get_table_names(schema=schema): table_names.append(table) for table in table_names: result[table] = frame_from_hyper( source=source, table=table, return_type=return_type, ) return result
(source: Union[str, pathlib.Path], return_type: Literal['pandas', 'polars', 'pyarrow'] = 'pandas')
65,131
pantab._writer
frames_to_hyper
See api.rst for documentation.
def frames_to_hyper( dict_of_frames: dict[pantab_types.TableNameType, Any], database: Union[str, pathlib.Path], *, table_mode: Literal["a", "w"] = "w", not_null_columns: Optional[set[str]] = None, json_columns: Optional[set[str]] = None, geo_columns: Optional[set[str]] = None, ) -> None: """See api.rst for documentation.""" _validate_table_mode(table_mode) if not_null_columns is None: not_null_columns = set() if json_columns is None: json_columns = set() if geo_columns is None: geo_columns = set() tmp_db = pathlib.Path(tempfile.gettempdir()) / f"{uuid.uuid4()}.hyper" if table_mode == "a" and pathlib.Path(database).exists(): shutil.copy(database, tmp_db) def convert_to_table_name(table: pantab_types.TableNameType): # nanobind expects a tuple of (schema, table) strings if isinstance(table, (str, tab_api.Name)) or not table.schema_name: table = tab_api.TableName("public", table) return (table.schema_name.name.unescaped, table.name.unescaped) data = { convert_to_table_name(key): _get_capsule_from_obj(val) for key, val in dict_of_frames.items() } libpantab.write_to_hyper( data, path=str(tmp_db), table_mode=table_mode, not_null_columns=not_null_columns, json_columns=json_columns, geo_columns=geo_columns, ) # In Python 3.9+ we can just pass the path object, but due to bpo 32689 # and subsequent typeshed changes it is easier to just pass as str for now shutil.move(str(tmp_db), database)
(dict_of_frames: dict[typing.Union[str, tableauhyperapi.name.Name, tableauhyperapi.tablename.TableName], typing.Any], database: Union[str, pathlib.Path], *, table_mode: Literal['a', 'w'] = 'w', not_null_columns: Optional[set[str]] = None, json_columns: Optional[set[str]] = None, geo_columns: Optional[set[str]] = None) -> NoneType
65,133
xvfbwrapper
Xvfb
null
class Xvfb(object): # Maximum value to use for a display. 32-bit maxint is the # highest Xvfb currently supports MAX_DISPLAY = 2147483647 SLEEP_TIME_BEFORE_START = 0.1 def __init__(self, width=800, height=680, colordepth=24, tempdir=None, **kwargs): self.width = width self.height = height self.colordepth = colordepth self._tempdir = tempdir or tempfile.gettempdir() if not self.xvfb_exists(): msg = 'Can not find Xvfb. Please install it and try again.' raise EnvironmentError(msg) self.extra_xvfb_args = ['-screen', '0', '{}x{}x{}'.format( self.width, self.height, self.colordepth)] for key, value in kwargs.items(): self.extra_xvfb_args += ['-{}'.format(key), value] if 'DISPLAY' in os.environ: self.orig_display = os.environ['DISPLAY'].split(':')[1] else: self.orig_display = None self.proc = None def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop() def start(self): self.new_display = self._get_next_unused_display() display_var = ':{}'.format(self.new_display) self.xvfb_cmd = ['Xvfb', display_var] + self.extra_xvfb_args with open(os.devnull, 'w') as fnull: self.proc = subprocess.Popen(self.xvfb_cmd, stdout=fnull, stderr=fnull, close_fds=True) # give Xvfb time to start time.sleep(self.__class__.SLEEP_TIME_BEFORE_START) ret_code = self.proc.poll() if ret_code is None: self._set_display_var(self.new_display) else: self._cleanup_lock_file() raise RuntimeError('Xvfb did not start') def stop(self): try: if self.orig_display is None: del os.environ['DISPLAY'] else: self._set_display_var(self.orig_display) if self.proc is not None: try: self.proc.terminate() self.proc.wait() except OSError: pass self.proc = None finally: self._cleanup_lock_file() def _cleanup_lock_file(self): ''' This should always get called if the process exits safely with Xvfb.stop() (whether called explicitly, or by __exit__). If you are ending up with /tmp/X123-lock files when Xvfb is not running, then Xvfb is not exiting cleanly. Always either call Xvfb.stop() in a finally block, or use Xvfb as a context manager to ensure lock files are purged. ''' self._lock_display_file.close() try: os.remove(self._lock_display_file.name) except OSError: pass def _get_next_unused_display(self): ''' In order to ensure multi-process safety, this method attempts to acquire an exclusive lock on a temporary file whose name contains the display number for Xvfb. ''' tempfile_path = os.path.join(self._tempdir, '.X{0}-lock') while True: rand = randint(1, self.__class__.MAX_DISPLAY) self._lock_display_file = open(tempfile_path.format(rand), 'w') try: fcntl.flock(self._lock_display_file, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: continue else: return rand def _set_display_var(self, display): os.environ['DISPLAY'] = ':{}'.format(display) def xvfb_exists(self): """Check that Xvfb is available on PATH and is executable.""" paths = os.environ['PATH'].split(os.pathsep) return any(os.access(os.path.join(path, 'Xvfb'), os.X_OK) for path in paths)
(width=800, height=680, colordepth=24, tempdir=None, **kwargs)
65,134
xvfbwrapper
__enter__
null
def __enter__(self): self.start() return self
(self)
65,135
xvfbwrapper
__exit__
null
def __exit__(self, exc_type, exc_val, exc_tb): self.stop()
(self, exc_type, exc_val, exc_tb)