code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
out_data_dir = prms.Paths.outdatadir project_dir = os.path.join(out_data_dir, project) batch_dir = os.path.join(project_dir, name) raw_dir = os.path.join(batch_dir, "raw_data") return out_data_dir, project_dir, batch_dir, raw_dir
def generate_folder_names(name, project)
Creates sensible folder names.
3.128502
2.958607
1.057424
time_00 = time.time() if x is None: x = HEADERS_NORMAL.step_time_txt if y is None: y = HEADERS_NORMAL.voltage_txt if group_by is None: group_by = [HEADERS_NORMAL.cycle_index_txt] if not isinstance(group_by, (list, tuple)): group_by = [group_by] if not gene...
def group_by_interpolate(df, x=None, y=None, group_by=None, number_of_points=100, tidy=False, individual_x_cols=False, header_name="Unit", dx=10.0, generate_new_x=True)
Use this for generating wide format from long (tidy) data
2.503385
2.508615
0.997915
if x is None: x = df.columns[0] if y is None: y = df.columns[1] xs = df[x].values ys = df[y].values if direction > 0: x_min = xs.min() x_max = xs.max() else: x_max = xs.min() x_min = xs.ma...
def _interpolate_df_col(df, x=None, y=None, new_x=None, dx=10.0, number_of_points=None, direction=1, **kwargs)
Interpolate a column based on another column. Args: df: DataFrame with the (cycle) data. x: Column name for the x-value (defaults to the step-time column). y: Column name for the y-value (defaults to the voltage column). new_x (numpy array or None): Interpolate u...
1.709252
1.741789
0.98132
minimum_v_value = np.Inf maximum_v_value = -np.Inf charge_list = [] cycles = data.get_cycle_numbers() for cycle in cycles: try: if direction == "charge": q, v = data.get_ccap(cycle) else: q, v = data.get_dcap(cycle) excep...
def _collect_capacity_curves(data, direction="charge")
Create a list of pandas.DataFrames, one for each charge step. The DataFrames are named by its cycle number. Input: CellpyData Returns: list of pandas.DataFrames minimum voltage value, maximum voltage value
2.723419
2.47154
1.101912
from cellpy import log log.setup_logging(default_level=logging_mode) cellpy_instance = setup_cellpy_instance() if instrument is not None: cellpy_instance.set_instrument(instrument=instrument) if cycle_mode is not None: cellpy_instance.cycle_mode = cycle_mode if filename...
def cell(filename=None, mass=None, instrument=None, logging_mode="INFO", cycle_mode=None, auto_summary=True)
Create a CellpyData object
2.504571
2.384472
1.050367
from cellpy import dbreader, filefinder print("just_load_srno: srno: %i" % srno) # ------------reading parameters-------------------------------------------- # print "just_load_srno: read prms" # prm = prmreader.read(prm_filename) # # print prm print("just_load_srno: making class ...
def just_load_srno(srno, prm_filename=None)
Simply load an dataset based on serial number (srno). This convenience function reads a dataset based on a serial number. This serial number (srno) must then be defined in your database. It is mainly used to check that things are set up correctly. Args: prm_filename: name of parameter file (op...
3.756568
3.951658
0.950631
d = CellpyData() if not outdir: outdir = prms.Paths["cellpydatadir"] if not outfile: outfile = os.path.basename(filename).split(".")[0] + ".h5" outfile = os.path.join(outdir, outfile) print("filename:", filename) print("outfile:", outfile) print("outdir:", outdir)...
def load_and_save_resfile(filename, outfile=None, outdir=None, mass=1.00)
Load a raw data file and save it as cellpy-file. Args: mass (float): active material mass [mg]. outdir (path): optional, path to directory for saving the hdf5-file. outfile (str): optional, name of hdf5-file. filename (str): name of the resfile. Returns: out_file_name (...
3.546351
3.313532
1.070263
# self.test_no = None # self.mass = 1.0 # mass of (active) material (in mg) # self.no_cycles = 0.0 # self.charge_steps = None # not in use at the moment # self.discharge_steps = None # not in use at the moment # self.ir_steps = None # dict # not in use at the moment # self.ocv_step...
def load_and_print_resfile(filename, info_dict=None)
Load a raw data file and print information. Args: filename (str): name of the resfile. info_dict (dict): Returns: info (str): string describing something.
5.863907
5.768832
1.016481
if instrument is None: instrument = self.tester if instrument in ["arbin", "arbin_res"]: self._set_arbin() self.tester = "arbin" elif instrument == "arbin_sql": self._set_arbin_sql() self.tester = "arbin" elif instru...
def set_instrument(self, instrument=None)
Set the instrument (i.e. tell cellpy the file-type you use). Args: instrument: (str) in ["arbin", "bio-logic-csv", "bio-logic-bin",...] Sets the instrument used for obtaining the data (i.e. sets fileformat)
3.111824
2.760567
1.127241
if directory is None: self.logger.info("no directory name given") return if not os.path.isdir(directory): self.logger.info(directory) self.logger.info("directory does not exist") return self.raw_datadir = directory
def set_raw_datadir(self, directory=None)
Set the directory containing .res-files. Used for setting directory for looking for res-files.@ A valid directory name is required. Args: directory (str): path to res-directory Example: >>> d = CellpyData() >>> directory = "MyData/Arbindata" ...
2.682324
3.047851
0.880071
if directory is None: self.logger.info("no directory name given") return if not os.path.isdir(directory): self.logger.info("directory does not exist") return self.cellpy_datadir = directory
def set_cellpy_datadir(self, directory=None)
Set the directory containing .hdf5-files. Used for setting directory for looking for hdf5-files. A valid directory name is required. Args: directory (str): path to hdf5-directory Example: >>> d = CellpyData() >>> directory = "MyData/HDF5" ...
2.79795
3.255547
0.859441
txt = "checking file ids - using '%s'" % self.filestatuschecker self.logger.info(txt) ids_cellpy_file = self._check_cellpy_file(cellpyfile) self.logger.debug(f"cellpyfile ids: {ids_cellpy_file}") if not ids_cellpy_file: # self.logger.debug("hdf5 file does...
def check_file_ids(self, rawfiles, cellpyfile)
Check the stats for the files (raw-data and cellpy hdf5). This function checks if the hdf5 file and the res-files have the same timestamps etc to find out if we need to bother to load .res -files. Args: cellpyfile (str): filename of the cellpy hdf5-file. rawfiles (list ...
3.452243
3.439641
1.003664
strip_file_names = True check_on = self.filestatuschecker if not self._is_listtype(file_names): file_names = [file_names, ] ids = dict() for f in file_names: self.logger.debug(f"checking res file {f}") fid = FileID(f) # s...
def _check_raw(self, file_names, abort_on_missing=False)
Get the file-ids for the res_files.
3.227449
3.00777
1.073037
strip_filenames = True check_on = self.filestatuschecker self.logger.debug("checking cellpy-file") self.logger.debug(filename) if not os.path.isfile(filename): self.logger.debug("cellpy-file does not exist") return None try: s...
def _check_cellpy_file(self, filename)
Get the file-ids for the cellpy_file.
3.318903
3.163015
1.049285
# This is a part of a dramatic API change. It will not be possible to # load more than one set of datasets (i.e. one single cellpy-file or # several raw-files that will be automatically merged) self.logger.info("started loadcell") if cellpy_file is None: si...
def loadcell(self, raw_files, cellpy_file=None, mass=None, summary_on_raw=False, summary_ir=True, summary_ocv=False, summary_end_v=True, only_summary=False, only_first=False, force_raw=False, use_cellpy_stat_file=None)
Loads data for given cells. Args: raw_files (list): name of res-files cellpy_file (path): name of cellpy-file mass (float): mass of electrode or active material summary_on_raw (bool): use raw-file for summary summary_ir (bool): summarize ir ...
4.345361
4.471426
0.971806
# This function only loads one test at a time (but could contain several # files). The function from_res() also implements loading several # datasets (using list of lists as input). if file_names: self.file_names = file_names if not isinstance(file_names, (...
def from_raw(self, file_names=None, **kwargs)
Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together.
4.04487
3.993807
1.012786
if len(self.status_datasets) == 0: return False if all(self.status_datasets): return True return False
def check(self)
Returns False if no datasets exists or if one or more of the datasets are empty
6.929861
3.972368
1.744516
try: self.logger.debug("loading cellpy-file (hdf5):") self.logger.debug(cellpy_file) new_datasets = self._load_hdf5(cellpy_file, parent_level) self.logger.debug("cellpy-file loaded") except AttributeError: new_datasets = [] ...
def load(self, cellpy_file, parent_level="CellpyData")
Loads a cellpy file. Args: cellpy_file (path, str): Full path to the cellpy file. parent_level (str, optional): Parent level
3.834738
3.936867
0.974058
if not os.path.isfile(filename): self.logger.info(f"file does not exist: {filename}") raise IOError store = pd.HDFStore(filename) # required_keys = ['dfdata', 'dfsummary', 'fidtable', 'info'] required_keys = ['dfdata', 'dfsummary', 'info'] requi...
def _load_hdf5(self, filename, parent_level="CellpyData")
Load a cellpy-file. Args: filename (str): Name of the cellpy file. parent_level (str) (optional): name of the parent level (defaults to "CellpyData") Returns: loaded datasets (DataSet-object)
4.308253
4.283025
1.00589
self.logger.info("merging") if separate_datasets: warnings.warn("The option seperate_datasets=True is" "not implemented yet. Performing merging, but" "neglecting the option.") else: if datasets is None: ...
def merge(self, datasets=None, separate_datasets=False)
This function merges datasets into one set.
2.844453
2.770583
1.026662
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return st = self.datasets[dataset_number].step_table print(st)
def print_step_table(self, dataset_number=None)
Print the step table.
3.54861
3.226972
1.099672
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return # if short: # # the table only consists of steps (not cycle,step pairs) assuming # # that the step numbers uniq...
def load_step_specifications(self, file_name, short=False, dataset_number=None)
Load a table that contains step-type definitions. This function loads a file containing a specification for each step or for each (cycle_number, step_number) combinations if short==False. The step_cycle specifications that are allowed are stored in the variable cellreader.list_of_step_t...
4.856728
4.498314
1.079677
if sep is None: sep = self.sep self.logger.debug("saving to csv") dataset_number = -1 for data in self.datasets: dataset_number += 1 if not self._is_not_empty_dataset(data): self.logger.info("to_csv -") self....
def to_csv(self, datadir=None, sep=None, cycles=False, raw=True, summary=True, shifted=False, method=None, shift=0.0, last_cycle=None)
Saves the data as .csv file(s). Args: datadir: folder where to save the data (uses current folder if not given). sep: the separator to use in the csv file (defaults to CellpyData.sep). cycles: (bool) export voltage-capacity curves if True. ...
3.004484
3.032624
0.990721
time_00 = time.time() set_number = self._validate_dataset_number(set_number) if set_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt voltage_header = self.headers_normal.voltage_txt ...
def sget_voltage(self, cycle, step, set_number=None)
Returns voltage for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][voltage_header] Args: cycle: cycle number step: step number set_number: the dataset...
4.201229
3.517105
1.194513
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt voltage_header = self.headers_normal.voltage_txt # step_index_h...
def get_voltage(self, cycle=None, dataset_number=None, full=True)
Returns voltage (in V). Args: cycle: cycle number (all cycles if None) dataset_number: first dataset if None full: valid only for cycle=None (i.e. all cycles), returns the full pandas.Series if True, else a list of pandas.Series Returns: p...
3.330591
3.336166
0.998329
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt current_header = self.headers_normal.current_txt # step_index_h...
def get_current(self, cycle=None, dataset_number=None, full=True)
Returns current (in mA). Args: cycle: cycle number (all cycles if None) dataset_number: first dataset if None full: valid only for cycle=None (i.e. all cycles), returns the full pandas.Series if True, else a list of pandas.Series Returns: ...
3.25312
3.254295
0.999639
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt step_time_header = self.headers_normal.step_time_txt step_index...
def sget_steptime(self, cycle, step, dataset_number=None)
Returns step time for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][step_time_header] Args: cycle: cycle number step: step number dataset_number: the...
3.758993
3.1454
1.195076
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt timestamp_header = self.headers_normal.test_time_txt step_index...
def sget_timestamp(self, cycle, step, dataset_number=None)
Returns timestamp for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][timestamp_header] Args: cycle: cycle number step: step number dataset_number: the...
3.997557
3.438064
1.162735
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt timestamp_header = self.headers_normal.test_time_txt v = pd.Se...
def get_timestamp(self, cycle=None, dataset_number=None, in_minutes=False, full=True)
Returns timestamps (in sec or minutes (if in_minutes==True)). Args: cycle: cycle number (all if None) dataset_number: first dataset if None in_minutes: return values in minutes instead of seconds if True full: valid only for cycle=None (i.e. all cycles), returns ...
3.534724
3.601224
0.981534
# TODO: should return a DataFrame as default # but remark that we then have to update e.g. batch_helpers.py dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return dc, v = s...
def get_dcap(self, cycle=None, dataset_number=None)
Returns discharge_capacity (in mAh/g), and voltage.
9.151556
7.981824
1.146549
# TODO: should return a DataFrame as default # but remark that we then have to update e.g. batch_helpers.py dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cc, v = s...
def get_ccap(self, cycle=None, dataset_number=None)
Returns charge_capacity (in mAh/g), and voltage.
9.285386
7.863528
1.180817
if cycles is None: cycles = self.get_cycle_numbers() else: if not isinstance(cycles, (list, tuple)): cycles = [cycles, ] else: remove_first = False ocv_rlx_id = "ocvrlx" if direction == "up": ocv_...
def get_ocv(self, cycles=None, direction="up", remove_first=False, interpolated=False, dx=None, number_of_points=None)
get the open curcuit voltage relaxation curves. Args: cycles (list of ints or None): the cycles to extract from (selects all if not given). direction ("up", "down", or "both"): extract only relaxations that is performed during discharge for "up" (because ...
2.554695
2.516237
1.015284
# function for getting ocv curves dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return if ocv_type in ['ocvrlx_up', 'ocvrlx_down']: ocv = self._get_ocv(dataset_number=Non...
def get_ocv_old(self, cycle_number=None, ocv_type='ocv', dataset_number=None)
Find ocv data in DataSet (voltage vs time). Args: cycle_number (int): find for all cycles if None. ocv_type ("ocv", "ocvrlx_up", "ocvrlx_down"): ocv - get up and down (default) ocvrlx_up - get up ocvrlx_down - get down ...
2.203769
1.972384
1.117313
if steptable is None: dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return d = self.datasets[dataset_number].dfdata no_cycles = np.amax(d[self.headers...
def get_number_of_cycles(self, dataset_number=None, steptable=None)
Get the number of cycles in the test.
4.42628
4.244077
1.042931
if steptable is None: dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return d = self.datasets[dataset_number].dfdata cycles = np.unique(d[self.headers_...
def get_cycle_numbers(self, dataset_number=None, steptable=None)
Get a list containing all the cycle numbers in the test.
4.382921
4.16296
1.052838
if not dataset: dataset_number = self._validate_dataset_number(None) if dataset_number is None: self._report_empty_dataset() return dataset = self.datasets[dataset_number] if not mass: mass = dataset.mass ...
def get_converter_to_specific(self, dataset=None, mass=None, to_unit=None, from_unit=None)
get the convertion values Args: dataset: DataSet object mass: mass of electrode (for example active material in mg) to_unit: (float) unit of input, f.ex. if unit of charge is mAh and unit of mass is g, then to_unit for charge/mass will be 0.001 / ...
2.775584
2.742007
1.012246
self._set_run_attribute("mass", masses, dataset_number=dataset_number, validated=validated)
def set_mass(self, masses, dataset_number=None, validated=None)
Sets the mass (masses) for the test (datasets).
4.387321
4.119765
1.064944
self._set_run_attribute("tot_mass", masses, dataset_number=dataset_number, validated=validated)
def set_tot_mass(self, masses, dataset_number=None, validated=None)
Sets the mass (masses) for the test (datasets).
3.888971
3.824753
1.01679
self._set_run_attribute("nom_cap", nom_caps, dataset_number=dataset_number, validated=validated)
def set_nom_cap(self, nom_caps, dataset_number=None, validated=None)
Sets the mass (masses) for the test (datasets).
3.811183
3.623394
1.051827
column_headings = df.columns column_headings = column_headings.tolist() try: for col_name in col_names: i = column_headings.index(col_name) column_headings.pop(column_headings.index(col_name)) column_headings.insert(0, col_nam...
def set_col_first(df, col_names)
set selected columns first in a pandas.DataFrame. This function sets cols with names given in col_names (a list) first in the DataFrame. The last col in col_name will come first (processed last)
2.380863
2.373904
1.002932
dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return None test = self.get_dataset(dataset_number) # This is a bit convoluted; in the old days, we used an attribute # called...
def get_summary(self, dataset_number=None, use_dfsummary_made=False)
Retrieve summary returned as a pandas DataFrame.
4.7694
4.624852
1.031255
# first - check if we need some "instrument-specific" prms if self.tester == "arbin": convert_date = True if ensure_step_table is None: ensure_step_table = self.ensure_step_table # Cycle_Index Test_Time(s) Test_Time(h) Date_Time Current(A) # Cur...
def make_summary(self, find_ocv=False, find_ir=False, find_end_voltage=False, use_cellpy_stat_file=None, all_tests=True, dataset_number=0, ensure_step_table=True, convert_date=False)
Convenience function that makes a summary of the cycling data.
2.980392
2.979744
1.000217
epub = cnxepub.EPUB.from_file(epub_file_path) if len(epub) != 1: raise Exception('Expecting an epub with one book') package = epub[0] binder = cnxepub.adapt_package(package) partcount.update({}.fromkeys(parts, 0)) partcount['book'] += 1 html = cnxepub.SingleHTMLFormatter(binde...
def single_html(epub_file_path, html_out=sys.stdout, mathjax_version=None, numchapters=None, includes=None)
Generate complete book HTML.
4.814253
4.923881
0.977736
config_dict = { "Paths": prms.Paths.to_dict(), "FileNames": prms.FileNames.to_dict(), "Db": prms.Db.to_dict(), "DbCols": prms.DbCols.to_dict(), "DataSet": prms.DataSet.to_dict(), "Reader": prms.Reader.to_dict(), "Instruments": prms.Instruments.to_dict(),...
def _pack_prms()
if you introduce new 'save-able' parameter dictionaries, then you have to include them here
2.761233
2.736414
1.00907
logger.debug("Reading config-file: %s" % prm_filename) try: with open(prm_filename, "r") as config_file: prm_dict = yaml.load(config_file) except yaml.YAMLError: raise ConfigFileNotRead else: _update_prms(prm_dict)
def _read_prm_file(prm_filename)
read the prm file
3.209723
3.22324
0.995806
if file_name is not None: if os.path.isfile(file_name): return file_name else: logger.info("Could not find the prm-file") default_name = prms._prm_default_name prm_globtxt = prms._prm_globtxt script_dir = os.path.abspath(os.path.dirname(__file__)) sear...
def _get_prm_file(file_name=None, search_order=None)
returns name of the prm file
2.686847
2.649796
1.013983
print("convenience function for listing prms") print(type(prms)) print(prms.__name__) print(f"prm file: {_get_prm_file()}") for key in prms.__dict__: if isinstance(prms.__dict__[key], box.Box): print() print(80 * "=") print(f"prms.{key}:") ...
def info()
this function will show only the 'box'-type attributes and their content in the cellpy.prms module
3.793133
3.306737
1.147092
math = node.attrib['data-math'] or node.text if math is None: return None eq = {} if mc_client: math_key = hashlib.md5(math.encode('utf-8')).hexdigest() eq = json.loads(mc_client.get(math_key) or '{}') if not eq: res = requests.post(mml_url, {'math': math.enco...
def _replace_tex_math(node, mml_url, mc_client=None, retry=0)
call mml-api service to replace TeX math in body of node with mathml
2.985593
2.963454
1.007471
def _replace_exercises(elem): item_code = elem.get('href')[len(match):] url = url_template.format(itemCode=item_code) exercise = {} if mc_client: mc_key = item_code + (token or '') exercise = json.loads(mc_client.get(mc_key) or '{}') if not exer...
def exercise_callback_factory(match, url_template, mc_client=None, token=None, mml_url=None)
Create a callback function to replace an exercise by fetching from a server.
3.965661
3.932964
1.008314
for node in tree: li_elm = etree.SubElement(root_xl_element, 'li') if node['id'] not in extensions: # no extension, no associated file span_elm = lxml.html.fragment_fromstring( node['title'], create_parent='span') li_elm.append(span_elm) else: ...
def html_listify(tree, root_xl_element, extensions, list_type='ol')
Convert a node tree into an xhtml nested list-of-lists. This will create 'li' elements under the root_xl_element, additional sublists of the type passed as list_type. The contents of each li depends on the extensions dictonary: the keys of this dictionary are the ids of tree elements that a...
2.966494
2.367736
1.252882
existing_ids = content.xpath('//*/@id') elements = [ 'p', 'dl', 'dt', 'dd', 'table', 'div', 'section', 'figure', 'blockquote', 'q', 'code', 'pre', 'object', 'img', 'audio', 'video', ] elements_xpath = '|'.join(['.//{}|.//xhtml:{}'.format(e...
def _generate_ids(self, document, content)
Generate unique ids for html elements in page content so that it's possible to link to them.
2.748579
2.712003
1.013487
if isinstance(node, CompositeDocument): return 'composite-page' elif isinstance(node, (Document, DocumentPointer)): return 'page' elif isinstance(node, Binder) and parent is None: return 'book' for child in node: if isinstance(chil...
def get_node_type(self, node, parent=None)
If node is a document, the type is page. If node is a binder with no parent, the type is book. If node is a translucent binder, the type is either chapters (only contain pages) or unit (contains at least one translucent binder).
8.110513
3.590647
2.258789
with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as zippy: base_path = os.path.abspath(directory) for root, dirs, filenames in os.walk(directory): # Strip the absolute path archive_path = os.path.relpath(root, base_path) for filename in filenames: ...
def pack_epub(directory, file)
Pack the given ``directory`` into an epub (i.e. zip) archive given as ``file``, which can be a file-path or file-like object.
2.034235
2.161
0.941339
if zipfile.is_zipfile(file): # Extract the epub to the current working directory. with zipfile.ZipFile(file, 'r') as zf: zf.extractall(path=directory)
def unpack_epub(file, directory)
Unpack the given ``file`` (a file-path or file-like object) to the given ``directory``.
2.491881
2.838733
0.877814
root = None if zipfile.is_zipfile(file): unpack_dir = tempfile.mkdtemp('-epub') # Extract the epub to the current working directory. with zipfile.ZipFile(file, 'r') as zf: zf.extractall(path=unpack_dir) root = unpack_dir el...
def from_file(cls, file)
Create the object from a *file* or *file-like object*. The file can point to an ``.epub`` file or a directory (the contents of which reflect the internal struture of an ``.epub`` archive). If given an non-archive file, this structure will be used when reading in and parsing the e...
3.768784
3.570724
1.055468
directory = tempfile.mkdtemp('-epub') # Write out the contents to the filesystem. package_filenames = [] for package in epub: opf_filepath = Package.to_file(package, directory) opf_filename = os.path.basename(opf_filepath) package_filenames.ap...
def to_file(epub, file)
Export to ``file``, which is a *file* or *file-like object*.
2.95198
2.970148
0.993883
opf_xml = etree.parse(file) # Check if ``file`` is file-like. if hasattr(file, 'read'): name = os.path.basename(file.name) root = os.path.abspath(os.path.dirname(file.name)) else: # ...a filepath name = os.path.basename(file) root...
def from_file(cls, file)
Create the object from a *file* or *file-like object*.
3.515429
3.420507
1.027751
opf_filepath = os.path.join(directory, package.name) # Create the directory structure for name in ('contents', 'resources',): path = os.path.join(directory, name) if not os.path.exists(path): os.mkdir(path) # Write the items to the files...
def to_file(package, directory)
Write the package to the given ``directory``. Returns the OPF filename.
2.399264
2.266692
1.058487
file_name = self._check_file_name(file_name) with open(file_name, 'r') as infile: top_level_dict = json.load(infile) pages_dict = top_level_dict['info_df'] pages = pd.DataFrame(pages_dict) self.pages = pages self.file_name = file_name self....
def from_file(self, file_name=None)
Loads a DataFrame with all the needed info about the experiment
4.86632
4.690666
1.037447
file_name = self._check_file_name(file_name) pages = self.pages top_level_dict = { 'info_df': pages, 'metadata': self._prm_packer() } jason_string = json.dumps( top_level_dict, default=lambda info_df: json.loads( ...
def to_file(self, file_name=None)
Saves a DataFrame with all the needed info about the experiment
4.867167
4.610046
1.055774
self.project_dir = os.path.join(prms.Paths.outdatadir, self.project) self.batch_dir = os.path.join(self.project_dir, self.name) self.raw_dir = os.path.join(self.batch_dir, "raw_data")
def generate_folder_names(self)
Set appropriate folder names.
3.737854
3.363941
1.111153
project_dir = self.project_dir raw_dir = self.raw_dir batch_dir = self.batch_dir if project_dir is None: raise UnderDefined("no project directory defined") if raw_dir is None: raise UnderDefined("no raw directory defined") if batch_dir i...
def paginate(self)
Make folders where we would like to put results etc.
2.127976
1.975252
1.077319
if not self.project: raise UnderDefined("project name not given") out_data_dir = prms.Paths.outdatadir project_dir = os.path.join(out_data_dir, self.project) file_name = "cellpy_batch_%s.json" % self.name self.file_name = os.path.join(project_dir, file_name)
def generate_file_name(self)
generate a suitable file name for the experiment
5.634378
5.230555
1.077205
print("Sorry, but I don't have much to share.") print("This is me:") print(self) print("And these are the experiments assigned to me:") print(self.experiments)
def info(self)
Delivers some info to you about the class.
13.80759
10.683798
1.292386
self.experiments.append(experiment) self.farms.append(empty_farm)
def assign(self, experiment)
Assign an experiment.
9.938104
9.20518
1.079621
id = model.ident_hash if id is None and isinstance(model, TranslucentBinder): id = lucent_id md = model.metadata shortid = md.get('shortId', md.get('cnx-archive-shortid')) title = title is not None and title or md.get('title') tree = {'id': id, 'title': title, 'shortId': shortid} ...
def model_to_tree(model, title=None, lucent_id=TRANSLUCENT_BINDER_ID)
Given an model, build the tree:: {'id': <id>|'subcol', 'title': <title>, 'contents': [<tree>, ...]}
3.747213
3.765065
0.995258
if 'contents' in item_or_tree: tree = item_or_tree if tree['id'] != lucent_id: yield tree['id'] for i in tree['contents']: # yield from flatten_tree_to_ident_hashs(i, lucent_id) for x in flatten_tree_to_ident_hashes(i, lucent_id): yiel...
def flatten_tree_to_ident_hashes(item_or_tree, lucent_id=TRANSLUCENT_BINDER_ID)
Flatten a tree to id and version values (ident_hash).
2.400734
2.414311
0.994377
yield model if isinstance(model, (TranslucentBinder, Binder,)): for m in model: # yield from flatten_model(m) for x in flatten_model(m): yield x
def flatten_model(model)
Flatten a model to a list of models. This is used to flatten a ``Binder``'ish model down to a list of contained models.
7.049991
5.577969
1.263899
types = [Document] if include_pointers: types.append(DocumentPointer) types = tuple(types) def _filter(m): return isinstance(m, types) return flatten_to(model, _filter)
def flatten_to_documents(model, include_pointers=False)
Flatten the model to a list of documents (aka ``Document`` objects). This is to flatten a ``Binder``'ish model down to a list of documents. If ``include_pointers`` has been set to ``True``, ``DocumentPointers`` will also be included in the results.
4.655803
4.721338
0.986119
parsed_uri = urlparse(uri) if not parsed_uri.netloc: if parsed_uri.scheme == 'data': type_ = INLINE_REFERENCE_TYPE else: type_ = INTERNAL_REFERENCE_TYPE else: type_ = EXTERNAL_REFERENCE_TYPE return type_
def _discover_uri_type(uri)
Given a ``uri``, determine if it is internal or external.
3.040192
2.742891
1.10839
references = [] ref_finder = HTMLReferenceFinder(xml) for elm, uri_attr in ref_finder: type_ = _discover_uri_type(elm.get(uri_attr)) references.append(Reference(elm, type_, uri_attr)) return references
def _parse_references(xml)
Parse the references to ``Reference`` instances.
5.504357
5.288282
1.040859
value = self._uri_template.format(self._bound_model.id) self.elm.set(self._uri_attr, value)
def _set_uri_from_bound_model(self)
Using the bound model, set the uri.
6.4697
4.927146
1.313072
self._bound_model = model self._uri_template = template self._set_uri_from_bound_model()
def bind(self, model, template="{}")
Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed.
6.558189
5.502678
1.191818
if isinstance(x, (pd.DataFrame, pd.Series)): return x.iloc[0], x.iloc[-1] else: return x[0], x[-1]
def index_bounds(x)
returns tuple with first and last item
2.404696
2.348835
1.023782
c_first = cycle.loc[cycle["direction"] == -1] c_last = cycle.loc[cycle["direction"] == 1] converter = Converter(**kwargs) converter.set_data(c_first["capacity"], c_first["voltage"]) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_pro...
def dqdv_cycle(cycle, splitter=True, **kwargs)
Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity', 'direction' (1 or -1)). ...
2.351969
2.039438
1.153244
# TODO: should add option for normalising based on first cycle capacity # this is e.g. done by first finding the first cycle capacity (nom_cap) # (or use nominal capacity given as input) and then propagating this to # Converter using the key-word arguments # normalize=True, normalization_fac...
def dqdv_cycles(cycles, **kwargs)
Convenience functions for creating dq-dv data from given capacity and voltage cycles. Returns a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage', 'capacity', 'direction' (1 or -1)). ...
6.223299
5.427543
1.146614
cycles = cell.get_cap( method="forth-and-forth", categorical_column=True, label_cycle_number=True, ) ica_df = dqdv_cycles(cycles, **kwargs) assert isinstance(ica_df, pd.DataFrame) return ica_df
def _dqdv_combinded_frame(cell, **kwargs)
Returns full cycle dqdv data for all cycles as one pd.DataFrame. Args: cell: CellpyData-object Returns: pandas.DataFrame with the following columns: cycle: cycle number voltage: voltage dq: the incremental capacity
9.467773
9.184346
1.03086
# TODO: should add option for normalising based on first cycle capacity # this is e.g. done by first finding the first cycle capacity (nom_cap) # (or use nominal capacity given as input) and then propagating this to # Converter using the key-word arguments # normalize=True, normalization_fact...
def dqdv_frames(cell, split=False, **kwargs)
Returns dqdv data as pandas.DataFrame(s) for all cycles. Args: cell (CellpyData-object). split (bool): return one frame for charge and one for discharge if True (defaults to False). Returns: pandas.DataFrame(s) with the follow...
13.768374
15.814966
0.870591
charge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves( cell, direction="charge" ) # charge_df = pd.concat( # charge_dfs, axis=1, keys=[k.name for k in charge_dfs]) ica_charge_dfs = _make_ica_charge_curves( charge_dfs, cycles, minimum_v, maximum_v, ...
def _dqdv_split_frames(cell, tidy=False, **kwargs)
Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are ...
2.131069
2.011936
1.059213
logging.debug("setting data (capacity and voltage)") if isinstance(capacity, pd.DataFrame): logging.debug("recieved a pandas.DataFrame") self.capacity = capacity[capacity_label] self.voltage = capacity[voltage_label] else: assert len(cap...
def set_data(self, capacity, voltage=None, capacity_label="q", voltage_label="v" )
Set the data
2.8768
3.055854
0.941406
logging.debug("inspecting the data") if capacity is None: capacity = self.capacity if voltage is None: voltage = self.voltage if capacity is None or voltage is None: raise NullData self.len_capacity = len(capacity) self.len...
def inspect_data(self, capacity=None, voltage=None, err_est=False, diff_est=False)
check and inspect the data
2.536237
2.535849
1.000153
logging.debug("pre-processing the data") capacity = self.capacity voltage = self.voltage # performing an interpolation in v(q) space logging.debug(" - interpolating voltage(capacity)") c1, c2 = index_bounds(capacity) if self.max_points is not None: ...
def pre_process_data(self)
perform some pre-processing of the data (i.e. interpolation)
3.109693
3.02714
1.027271
# NOTE TO ASBJOERN: Probably insert method for "binning" instead of # differentiating here # (use self.increment_method as the variable for selecting method for) logging.debug("incrementing data") # ---- shifting to y-x ---------------------------------------- ...
def increment_data(self)
perform the dq-dv transform
4.376357
4.293853
1.019215
logging.debug("post-processing data") if voltage is None: voltage = self.voltage_processed incremental_capacity = self.incremental_capacity voltage_step = self.voltage_inverted_step if self.post_smoothing: logging.debug(" - post smoothi...
def post_process_data(self, voltage=None, incremental_capacity=None, voltage_step=None)
perform post-processing (smoothing, normalisation, interpolation) of the data
2.893963
2.925988
0.989055
html = etree.parse(in_html) oven = Oven(ruleset) oven.bake(html) out_html.write(etree.tostring(html))
def easybake(ruleset, in_html, out_html)
This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability.
3.489961
3.947585
0.884075
try: htree = etree.parse(html) except etree.XMLSyntaxError: html.seek(0) htree = etree.HTML(html.read()) xhtml = etree.tostring(htree, encoding='utf-8') return adapt_single_html(xhtml)
def reconstitute(html)
Given a file-like object as ``html``, reconstruct it into models.
4.148549
3.839443
1.080508
html_formatter = SingleHTMLFormatter(binder, includes) raw_html = io.BytesIO(bytes(html_formatter)) collated_html = io.BytesIO() if ruleset is None: # No ruleset found, so no cooking necessary. return binder easybake(ruleset, raw_html, collated_html) collated_html.seek(0)...
def collate(binder, ruleset=None, includes=None)
Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder.
5.903528
5.590542
1.055985
navigation_item = package.navigation html = etree.parse(navigation_item.data) tree = parse_navigation_html_to_tree(html, navigation_item.name) return _node_to_model(tree, package)
def adapt_package(package)
Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``.
8.160524
8.829926
0.924189
if item.media_type == 'application/xhtml+xml': try: html = etree.parse(item.data) except Exception as exc: logger.error("failed parsing {}".format(item.name)) raise metadata = DocumentPointerMetadataParser( html, raise_value_error=False)()...
def adapt_item(item, package, filename=None)
Adapts ``.epub.Item`` to a ``DocumentItem``.
4.781865
4.544037
1.052338
if not isinstance(binders, (list, set, tuple,)): binders = [binders] epub = EPUB([_make_package(binder) for binder in binders]) epub.to_file(epub, file)
def make_epub(binders, file)
Creates an EPUB file from a binder(s).
3.97163
3.765705
1.054684
if not isinstance(binders, (list, set, tuple,)): binders = [binders] packages = [] for binder in binders: metadata = binder.metadata binder.metadata = deepcopy(metadata) binder.metadata.update({'publisher': publisher, 'publication_message'...
def make_publication_epub(binders, publisher, publication_message, file)
Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request.
3.123334
3.182936
0.981275
package_id = binder.id if package_id is None: package_id = hash(binder) package_name = "{}.opf".format(package_id) extensions = get_model_extensions(binder) template_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) # Build the package item list. items = [] ...
def _make_package(binder)
Makes an ``.epub.Package`` from a Binder'ish instance.
4.319249
4.249531
1.016406
uri = DataURI(reference.uri) data = io.BytesIO(uri.data) mimetype = uri.mimetype res = Resource('dummy', data, mimetype) res.id = res.filename return res
def _make_resource_from_inline(reference)
Makes an ``models.Resource`` from a ``models.Reference`` of type INLINE. That is, a data: uri
5.195529
5.823752
0.892127
item = Item(model.id, model.content, model.media_type) return item
def _make_item(model)
Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource``
6.79926
6.677016
1.018308
if 'contents' in tree_or_item: # It is a binder. tree = tree_or_item # Grab the package metadata, so we have required license info metadata = package.metadata.copy() if tree['id'] == lucent_id: metadata['title'] = tree['title'] binder = Translucen...
def _node_to_model(tree_or_item, package, parent=None, lucent_id=TRANSLUCENT_BINDER_ID)
Given a tree, parse to a set of models
3.772787
3.791779
0.994991
html_root = etree.fromstring(html) metadata = parse_metadata(html_root.xpath('//*[@data-type="metadata"]')[0]) id_ = metadata['cnx-archive-uri'] or 'book' binder = Binder(id_, metadata=metadata) nav_tree = parse_navigation_html_to_tree(html_root, id_) body = html_root.xpath('//xhtml:body...
def adapt_single_html(html)
Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder``
6.147618
6.01261
1.022454
result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters] for i in range(self.circuits): result_dict['t' + str(i)] = [parameters['t' + str(i)] for parameters ...
def get_best_fit_parameters_grouped(self)
Returns a dictionary of the best fit.
2.640758
2.544394
1.037873
result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters_translated] result_dict['ir'] = [parameters['ir'] for parameters in self.best_fit_parameters_translated] for i in r...
def get_best_fit_parameters_translated_grouped(self)
Returns the parameters as a dictionary of the 'real units' for the best fit.
2.271131
2.24774
1.010407
if cycles is None: cycles = [0] fig1 = plt.figure() ax1 = fig1.add_subplot(221) ax1.set_title('Fit') ax2 = fig1.add_subplot(222) ax2.set_title('OCV') ax3 = fig1.add_subplot(223) ax3.set_title('Tau') ax3.set_yscale("log") ...
def plot_summary(self, cycles=None)
Convenience function for plotting the summary of the fit
2.297072
2.25371
1.01924
fig2 = plt.figure() ax1 = fig2.add_subplot(221) ax1.set_title('OCV (V)') ax2 = fig2.add_subplot(222) ax2.set_title('IR (Ohm)') ax3 = fig2.add_subplot(223) ax3.set_title('Resistances (Ohm)') ax4 = fig2.add_subplot(224) ax4.set_title('Capac...
def plot_summary_translated(self)
Convenience function for plotting the summary of the fit (translated)
2.313043
2.240274
1.032482