sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def create_info_df(self): """Creates a DataFrame with info about the runs (loaded from the DB)""" logger.debug("running create_info_df") # initializing the reader reader = self.reader() self.info_df = make_df_from_batch(self.name, batch_col=self.batch_col, ...
Creates a DataFrame with info about the runs (loaded from the DB)
entailment
def save_info_df(self): """Saves the DataFrame with info about the runs to a JSON file""" logger.debug("running save_info_df") info_df = self.info_df top_level_dict = {'info_df': info_df, 'metadata': self._prm_packer()} # packing prms jason_string = json.dumps(top_leve...
Saves the DataFrame with info about the runs to a JSON file
entailment
def load_info_df(self, file_name=None): """Loads a DataFrame with all the needed info about the run (JSON file)""" if file_name is None: file_name = self.info_file with open(file_name, 'r') as infile: top_level_dict = json.load(infile) new_info_df_dict ...
Loads a DataFrame with all the needed info about the run (JSON file)
entailment
def create_folder_structure(self): """Creates a folder structure based on the project and batch name. Project - Batch-name - Raw-data-dir The info_df JSON-file will be stored in the Project folder. The summary-files will be saved in the Batch-name folder. The raw data (includin...
Creates a folder structure based on the project and batch name. Project - Batch-name - Raw-data-dir The info_df JSON-file will be stored in the Project folder. The summary-files will be saved in the Batch-name folder. The raw data (including exported cycles and ica-data) will be saved ...
entailment
def load_and_save_raw(self, parent_level="CellpyData"): """Loads the cellpy or raw-data file(s) and saves to csv""" sep = prms.Reader["sep"] if self.use_cellpy_stat_file is None: use_cellpy_stat_file = prms.Reader.use_cellpy_stat_file else: use_cellpy_stat_file = ...
Loads the cellpy or raw-data file(s) and saves to csv
entailment
def make_summaries(self): """Make and save summary csv files, each containing values from all cells""" self.summary_df = save_summaries(self.frames, self.keys, self.selected_summaries, self.batch_dir, self.name) ...
Make and save summary csv files, each containing values from all cells
entailment
def plot_summaries(self, show=False, save=True, figure_type=None): """Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create. """ if not figure_type: figure_...
Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create.
entailment
def update(self, all_in_memory=None): """Updates the selected datasets. Args: all_in_memory (bool): store the cellpydata in memory (default False) """ logging.info("[update experiment]") if all_in_memory is not None: self.all_in_memory = all_...
Updates the selected datasets. Args: all_in_memory (bool): store the cellpydata in memory (default False)
entailment
def link(self): """Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark that running update persists the summary f...
Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark that running update persists the summary frames instead (or e...
entailment
def get_default_config_file_path(init_filename=None): """gets the path to the default config-file""" prm_dir = get_package_prm_dir() if not init_filename: init_filename = DEFAULT_FILENAME src = os.path.join(prm_dir, init_filename) return src
gets the path to the default config-file
entailment
def get_user_dir_and_dst(init_filename): """gets the name of the user directory and full prm filepath""" user_dir = get_user_dir() dst_file = os.path.join(user_dir, init_filename) return user_dir, dst_file
gets the name of the user directory and full prm filepath
entailment
def setup(interactive, not_relative, dry_run, reset, root_dir, testuser): """This will help you to setup cellpy.""" click.echo("[cellpy] (setup)") # generate variables init_filename = create_custom_init_filename() userdir, dst_file = get_user_dir_and_dst(init_filename) if testuser: if...
This will help you to setup cellpy.
entailment
def _parse_g_dir(repo, gdirpath): """parses a repo directory two-levels deep""" for f in repo.get_contents(gdirpath): if f.type == "dir": for sf in repo.get_contents(f.path): yield sf else: yield f
parses a repo directory two-levels deep
entailment
def look_up_and_get(cellpy_file_name, table_name): """Extracts table from cellpy hdf5-file.""" # infoname = '/CellpyData/info' # dataname = '/CellpyData/dfdata' # summaryname = '/CellpyData/dfsummary' # fidname = '/CellpyData/fidtable' # stepname = '/CellpyData/step_table' root = '/CellpyD...
Extracts table from cellpy hdf5-file.
entailment
def fix_groups(groups): """Takes care of strange group numbers.""" _groups = [] for g in groups: try: if not float(g) > 0: _groups.append(1000) else: _groups.append(int(g)) except TypeError as e: logging.info("Error in readi...
Takes care of strange group numbers.
entailment
def create_selected_summaries_dict(summaries_list): """Creates a dictionary with summary column headers. Examples: >>> summaries_to_output = ["discharge_capacity", "charge_capacity"] >>> summaries_to_output_dict = create_selected_summaries_dict( >>> summaries_to_output >>> ) ...
Creates a dictionary with summary column headers. Examples: >>> summaries_to_output = ["discharge_capacity", "charge_capacity"] >>> summaries_to_output_dict = create_selected_summaries_dict( >>> summaries_to_output >>> ) >>> print(summaries_to_output_dict) {'disch...
entailment
def join_summaries(summary_frames, selected_summaries, keep_old_header=False): """parse the summaries and combine based on column (selected_summaries)""" selected_summaries_dict = create_selected_summaries_dict(selected_summaries) frames = [] keys = [] for key in summary_frames: keys.append...
parse the summaries and combine based on column (selected_summaries)
entailment
def generate_folder_names(name, project): """Creates sensible folder names.""" 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...
Creates sensible folder names.
entailment
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""" ti...
Use this for generating wide format from long (tidy) data
entailment
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 ste...
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...
entailment
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""" minimum_v_val...
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
entailment
def cell(filename=None, mass=None, instrument=None, logging_mode="INFO", cycle_mode=None, auto_summary=True): """Create a CellpyData object""" from cellpy import log log.setup_logging(default_level=logging_mode) cellpy_instance = setup_cellpy_instance() if instrument is not None: ...
Create a CellpyData object
entailment
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. Ar...
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...
entailment
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. ...
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 (...
entailment
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. """ # self.test_no = None # self.mass = 1.0 # mass of (a...
Load a raw data file and print information. Args: filename (str): name of the resfile. info_dict (dict): Returns: info (str): string describing something.
entailment
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) """ if instr...
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)
entailment
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() ...
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" ...
entailment
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 = CellpyDa...
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" ...
entailment
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): fi...
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 ...
entailment
def _check_raw(self, file_names, abort_on_missing=False): """Get the file-ids for the res_files.""" 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: ...
Get the file-ids for the res_files.
entailment
def _check_cellpy_file(self, filename): """Get the file-ids for the cellpy_file.""" 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.deb...
Get the file-ids for the cellpy_file.
entailment
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...
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 ...
entailment
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. """ # T...
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.
entailment
def check(self): """Returns False if no datasets exists or if one or more of the datasets are empty""" if len(self.status_datasets) == 0: return False if all(self.status_datasets): return True return False
Returns False if no datasets exists or if one or more of the datasets are empty
entailment
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 """ try: self.logger.debug("loading cellpy-file (hdf5):") ...
Loads a cellpy file. Args: cellpy_file (path, str): Full path to the cellpy file. parent_level (str, optional): Parent level
entailment
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 (Data...
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)
entailment
def merge(self, datasets=None, separate_datasets=False): """This function merges datasets into one set.""" self.logger.info("merging") if separate_datasets: warnings.warn("The option seperate_datasets=True is" "not implemented yet. Performing merging, but" ...
This function merges datasets into one set.
entailment
def print_step_table(self, dataset_number=None): """Print the step table.""" 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(s...
Print the step table.
entailment
def get_step_numbers(self, steptype='charge', allctypes=True, pdtype=False, cycle_number=None, dataset_number=None, steptable=None): # TODO: @jepe - include sub_steps here """Get the step numbers of selected type. Returns the selected step_numbe...
Get the step numbers of selected type. Returns the selected step_numbers for the elected type of step(s). Args: steptype (string): string identifying type of step. allctypes (bool): get all types of charge (or discharge). pdtype (bool): return results as pandas.Dat...
entailment
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 sho...
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...
entailment
def make_step_table(self, custom_step_definition=False, step_specifications=None, short=False, dataset_number=None): """ Create a table (v.4) that contains summary information for each step. This function creates a table containin...
Create a table (v.4) that contains summary information for each step. This function creates a table containing information about the different steps for each cycle and, based on that, decides what type of step it is (e.g. charge) for each cycle. The format of the step_table is: ...
entailment
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 ...
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. ...
entailment
def save(self, filename, dataset_number=None, force=False, overwrite=True, extension="h5", ensure_step_table=None): """Save the data structure to cellpy-format. Args: filename: (str) the name you want to give the file dataset_number: (int) if you have several datase...
Save the data structure to cellpy-format. Args: filename: (str) the name you want to give the file dataset_number: (int) if you have several datasets, chose the one you want (probably leave this untouched) force: (bool) save a file even if the summary is not ...
entailment
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 ...
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...
entailment
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 panda...
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...
entailment
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 pand...
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: ...
entailment
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: cycl...
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...
entailment
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: cyc...
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...
entailment
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: ret...
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 ...
entailment
def get_dcap(self, cycle=None, dataset_number=None): """Returns discharge_capacity (in mAh/g), and voltage.""" # 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) ...
Returns discharge_capacity (in mAh/g), and voltage.
entailment
def get_ccap(self, cycle=None, dataset_number=None): """Returns charge_capacity (in mAh/g), and voltage.""" # 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) ...
Returns charge_capacity (in mAh/g), and voltage.
entailment
def get_cap(self, cycle=None, dataset_number=None, method="back-and-forth", shift=0.0, categorical_column=False, label_cycle_number=False, split=False, interpolated=False, dx=0.1, number_of_po...
Gets the capacity for the run. For cycle=None: not implemented yet, cycle set to 1. Args: cycle (int): cycle number. method (string): how the curves are given "back-and-forth" - standard back and forth; discharge (or charge) reversed from wher...
entailment
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 extr...
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 ...
entailment
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)...
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 ...
entailment
def get_number_of_cycles(self, dataset_number=None, steptable=None): """Get the number of cycles in the test.""" if steptable is None: dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() ...
Get the number of cycles in the test.
entailment
def get_cycle_numbers(self, dataset_number=None, steptable=None): """Get a list containing all the cycle numbers in the test.""" if steptable is None: dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_data...
Get a list containing all the cycle numbers in the test.
entailment
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 ...
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 / ...
entailment
def set_mass(self, masses, dataset_number=None, validated=None): """Sets the mass (masses) for the test (datasets). """ self._set_run_attribute("mass", masses, dataset_number=dataset_number, validated=validated)
Sets the mass (masses) for the test (datasets).
entailment
def set_tot_mass(self, masses, dataset_number=None, validated=None): """Sets the mass (masses) for the test (datasets). """ self._set_run_attribute("tot_mass", masses, dataset_number=dataset_number, validated=validated)
Sets the mass (masses) for the test (datasets).
entailment
def set_nom_cap(self, nom_caps, dataset_number=None, validated=None): """Sets the mass (masses) for the test (datasets). """ self._set_run_attribute("nom_cap", nom_caps, dataset_number=dataset_number, validated=validated)
Sets the mass (masses) for the test (datasets).
entailment
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) """ column_headings = df.columns colu...
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)
entailment
def get_summary(self, dataset_number=None, use_dfsummary_made=False): """Retrieve summary returned as a pandas DataFrame.""" dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return None test = ...
Retrieve summary returned as a pandas DataFrame.
entailment
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...
Convenience function that makes a summary of the cycling data.
entailment
def single_html(epub_file_path, html_out=sys.stdout, mathjax_version=None, numchapters=None, includes=None): """Generate complete book HTML.""" epub = cnxepub.EPUB.from_file(epub_file_path) if len(epub) != 1: raise Exception('Expecting an epub with one book') package = epub[0] ...
Generate complete book HTML.
entailment
def _pack_prms(): """if you introduce new 'save-able' parameter dictionaries, then you have to include them here""" config_dict = { "Paths": prms.Paths.to_dict(), "FileNames": prms.FileNames.to_dict(), "Db": prms.Db.to_dict(), "DbCols": prms.DbCols.to_dict(), "DataSe...
if you introduce new 'save-able' parameter dictionaries, then you have to include them here
entailment
def _read_prm_file(prm_filename): """read the prm file""" 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(p...
read the prm file
entailment
def _get_prm_file(file_name=None, search_order=None): """returns name of the prm file""" 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 = ...
returns name of the prm file
entailment
def info(): """this function will show only the 'box'-type attributes and their content in the cellpy.prms module""" 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(pr...
this function will show only the 'box'-type attributes and their content in the cellpy.prms module
entailment
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""" 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')).hex...
call mml-api service to replace TeX math in body of node with mathml
entailment
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.""" def _replace_exercises(elem): item_code = elem.get('href')[len(match):] url = url_te...
Create a callback function to replace an exercise by fetching from a server.
entailment
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 dicto...
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...
entailment
def _generate_ids(self, document, content): """Generate unique ids for html elements in page content so that it's possible to link to them. """ existing_ids = content.xpath('//*/@id') elements = [ 'p', 'dl', 'dt', 'dd', 'table', 'div', 'section', 'figure', ...
Generate unique ids for html elements in page content so that it's possible to link to them.
entailment
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). """ ...
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).
entailment
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. """ with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as zippy: base_path = os.path.abspath(directory) for root, dirs, 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.
entailment
def unpack_epub(file, directory): """Unpack the given ``file`` (a file-path or file-like object) to the given ``directory``. """ if zipfile.is_zipfile(file): # Extract the epub to the current working directory. with zipfile.ZipFile(file, 'r') as zf: zf.extractall(path=directo...
Unpack the given ``file`` (a file-path or file-like object) to the given ``directory``.
entailment
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 u...
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...
entailment
def to_file(epub, file): """Export to ``file``, which is a *file* or *file-like object*.""" directory = tempfile.mkdtemp('-epub') # Write out the contents to the filesystem. package_filenames = [] for package in epub: opf_filepath = Package.to_file(package, directory)...
Export to ``file``, which is a *file* or *file-like object*.
entailment
def from_file(cls, file): """Create the object from a *file* or *file-like object*.""" 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)) ...
Create the object from a *file* or *file-like object*.
entailment
def to_file(package, directory): """Write the package to the given ``directory``. Returns the OPF filename. """ opf_filepath = os.path.join(directory, package.name) # Create the directory structure for name in ('contents', 'resources',): path = os.path.join(d...
Write the package to the given ``directory``. Returns the OPF filename.
entailment
def from_file(self, file_name=None): """Loads a DataFrame with all the needed info about the experiment""" 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'] pa...
Loads a DataFrame with all the needed info about the experiment
entailment
def to_file(self, file_name=None): """Saves a DataFrame with all the needed info about the experiment""" file_name = self._check_file_name(file_name) pages = self.pages top_level_dict = { 'info_df': pages, 'metadata': self._prm_packer() } jason_...
Saves a DataFrame with all the needed info about the experiment
entailment
def generate_folder_names(self): """Set appropriate folder names.""" 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")
Set appropriate folder names.
entailment
def paginate(self): """Make folders where we would like to put results etc.""" 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: ...
Make folders where we would like to put results etc.
entailment
def generate_file_name(self): """generate a suitable file name for the experiment""" 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_batc...
generate a suitable file name for the experiment
entailment
def info(self): """Delivers some info to you about the class.""" 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)
Delivers some info to you about the class.
entailment
def assign(self, experiment): """Assign an experiment.""" self.experiments.append(experiment) self.farms.append(empty_farm)
Assign an experiment.
entailment
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>, ...]} """ id = model.ident_hash if id is None and isinstance(model, TranslucentBinder): id = lucent_id md = model....
Given an model, build the tree:: {'id': <id>|'subcol', 'title': <title>, 'contents': [<tree>, ...]}
entailment
def flatten_tree_to_ident_hashes(item_or_tree, lucent_id=TRANSLUCENT_BINDER_ID): """Flatten a tree to id and version values (ident_hash).""" if 'contents' in item_or_tree: tree = item_or_tree if tree['id'] != lucent_id: yield tree['id'] for i ...
Flatten a tree to id and version values (ident_hash).
entailment
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. """ yield model if isinstance(model, (TranslucentBinder, Binder,)): for m in model: # yield from flatten_model(m) f...
Flatten a model to a list of models. This is used to flatten a ``Binder``'ish model down to a list of contained models.
entailment
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 resu...
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.
entailment
def _discover_uri_type(uri): """Given a ``uri``, determine if it is internal or external.""" 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...
Given a ``uri``, determine if it is internal or external.
entailment
def _parse_references(xml): """Parse the references to ``Reference`` instances.""" 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
Parse the references to ``Reference`` instances.
entailment
def _set_uri_from_bound_model(self): """Using the bound model, set the uri.""" value = self._uri_template.format(self._bound_model.id) self.elm.set(self._uri_attr, value)
Using the bound model, set the uri.
entailment
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. """ self._bound_model = model self._uri_template = template self._set_uri_fr...
Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed.
entailment
def index_bounds(x): """returns tuple with first and last item""" if isinstance(x, (pd.DataFrame, pd.Series)): return x.iloc[0], x.iloc[-1] else: return x[0], x[-1]
returns tuple with first and last item
entailment
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...
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)). ...
entailment
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', ...
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)). ...
entailment
def dqdv(voltage, capacity, voltage_resolution=None, capacity_resolution=None, voltage_fwhm=0.01, pre_smoothing=True, diff_smoothing=False, post_smoothing=True, post_normalization=True, interpolation_method=None, gaussian_order=None, gaussian_mode=None, gaussian_cval=None, gaussian_t...
Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.005) capacity_resolution: used for interpolating capacity data...
entailment
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 ...
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
entailment
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...
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...
entailment