sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def action(args):
"""Updates a Refpkg with new files.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and changes (a series of strings
of the form 'key=file' giving the key to update in the refpkg and
the file to store under that key)."
"""
... | Updates a Refpkg with new files.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and changes (a series of strings
of the form 'key=file' giving the key to update in the refpkg and
the file to store under that key)." | entailment |
def import_object(name):
"""
Import module and return object from it. *name* is :class:`str` in
format ``module.path.ObjectClass``.
::
>>> import_command('module.path.ObjectClass')
<class 'module.path.ObjectClass'>
"""
parts = name.split('.')
if len(parts) < 2:
raise... | Import module and return object from it. *name* is :class:`str` in
format ``module.path.ObjectClass``.
::
>>> import_command('module.path.ObjectClass')
<class 'module.path.ObjectClass'> | entailment |
def parse_arguments(argv):
"""Create the argument parser
"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
base_parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-V', '--version', action='version',
version='taxit v' + version,
... | Create the argument parser | entailment |
def execute(self, statements, exc=IntegrityError, rasie_as=ValueError):
"""Execute ``statements`` in a session, and perform a rollback on
error. ``exc`` is a single exception object or a tuple of
objects to be used in the except clause. The error message is
re-raised as the exception spe... | Execute ``statements`` in a session, and perform a rollback on
error. ``exc`` is a single exception object or a tuple of
objects to be used in the except clause. The error message is
re-raised as the exception specified by ``raise_as``. | entailment |
def _node(self, tax_id):
"""
Returns parent_id, rank
FIXME: expand return rank to include custom 'below' ranks built when
get_lineage is caled
"""
s = select([self.nodes.c.parent_id, self.nodes.c.rank],
self.nodes.c.tax_id == tax_id)
res... | Returns parent_id, rank
FIXME: expand return rank to include custom 'below' ranks built when
get_lineage is caled | entailment |
def primary_from_id(self, tax_id):
"""
Returns primary taxonomic name associated with tax_id
"""
s = select([self.names.c.tax_name],
and_(self.names.c.tax_id == tax_id,
self.names.c.is_primary))
res = s.execute()
output = res.fet... | Returns primary taxonomic name associated with tax_id | entailment |
def primary_from_name(self, tax_name):
"""
Return tax_id and primary tax_name corresponding to tax_name.
"""
names = self.names
s1 = select([names.c.tax_id, names.c.is_primary],
names.c.tax_name == tax_name)
log.debug(str(s1))
res = s1.execu... | Return tax_id and primary tax_name corresponding to tax_name. | entailment |
def _get_merged(self, tax_id):
"""Returns tax_id into which `tax_id` has been merged or `tax_id` of
not obsolete.
"""
cmd = """
SELECT COALESCE(
(SELECT new_tax_id FROM {merged}
WHERE old_tax_id = {x}), {x})
""".format(x=self.placeholder, merged=self.me... | Returns tax_id into which `tax_id` has been merged or `tax_id` of
not obsolete. | entailment |
def _get_lineage(self, tax_id, merge_obsolete=True):
"""Return a list of [(rank, tax_id)] describing the lineage of
tax_id. If ``merge_obsolete`` is True and ``tax_id`` has been
replaced, use the corresponding value in table merged.
"""
# Be sure we aren't working with an obsol... | Return a list of [(rank, tax_id)] describing the lineage of
tax_id. If ``merge_obsolete`` is True and ``tax_id`` has been
replaced, use the corresponding value in table merged. | entailment |
def _get_lineage_table(self, tax_ids, merge_obsolete=True):
"""Return a list of [(rank, tax_id, tax_name)] describing the lineage
of tax_id. If ``merge_obsolete`` is True and ``tax_id`` has
been replaced, use the corresponding value in table merged.
"""
try:
with se... | Return a list of [(rank, tax_id, tax_name)] describing the lineage
of tax_id. If ``merge_obsolete`` is True and ``tax_id`` has
been replaced, use the corresponding value in table merged. | entailment |
def lineage(self, tax_id=None, tax_name=None):
"""Public method for returning a lineage; includes tax_name and rank
"""
if not bool(tax_id) ^ bool(tax_name):
msg = 'Exactly one of tax_id and tax_name may be provided.'
raise ValueError(msg)
if tax_name:
... | Public method for returning a lineage; includes tax_name and rank | entailment |
def add_source(self, source_name, description=None):
"""Adds a row to table "source" if "name" does not
exist. Returns (source_id, True) if a new row is created,
(source_id, False) otherwise.
"""
# TODO: shoud be able to do this inside a transaction
if not source_name:... | Adds a row to table "source" if "name" does not
exist. Returns (source_id, True) if a new row is created,
(source_id, False) otherwise. | entailment |
def get_source(self, source_id=None, source_name=None):
"""Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source correspon... | Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source corresponding to
``source_name`` is created if necessary. | entailment |
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
"""Confirm that for each node the parent ranks and children ranks are
coherent
"""
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise... | Confirm that for each node the parent ranks and children ranks are
coherent | entailment |
def add_node(self, tax_id, parent_id, rank, names, source_name, children=None,
is_valid=True, execute=True, **ignored):
"""Add a node to the taxonomy.
``source_name`` is added to table "source" if necessary.
"""
if ignored:
log.info('some arguments were ig... | Add a node to the taxonomy.
``source_name`` is added to table "source" if necessary. | entailment |
def add_name(self, tax_id, tax_name, source_name=None, source_id=None,
name_class='synonym', is_primary=False, is_classified=None,
execute=True, **ignored):
"""Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (str... | Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (string, required)
- tax_name (string, required)
*one* of the following are required:
- source_id (int or string coercable to int)
- source_name (string)
``source_i... | entailment |
def add_names(self, tax_id, names, execute=True):
"""Associate one or more names with ``tax_id``.
``names`` is a list of one or more dicts, with keys
corresponding to the signature of ``self.add_name()``
(excluding ``execute``).
"""
primary_names = [n['tax_name'] for n... | Associate one or more names with ``tax_id``.
``names`` is a list of one or more dicts, with keys
corresponding to the signature of ``self.add_name()``
(excluding ``execute``). | entailment |
def sibling_of(self, tax_id):
"""Return None or a tax_id of a sibling of *tax_id*.
If ``tax_id`` is None, then always returns None. Otherwise,
returns None if there is no sibling.
"""
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
... | Return None or a tax_id of a sibling of *tax_id*.
If ``tax_id`` is None, then always returns None. Otherwise,
returns None if there is no sibling. | entailment |
def tax_ids(self):
'''
Return all tax_ids in node table
'''
fetch = select([self.nodes.c.tax_id]).execute().fetchall()
ids = [t[0] for t in fetch]
return ids | Return all tax_ids in node table | entailment |
def child_of(self, tax_id):
"""Return None or a tax id of a child of *tax_id*.
If *tax_id* is None, then always returns None. Otherwise
returns a child if one exists, else None. The child must have
a proper rank below that of tax_id (i.e., genus, species, but
not no_rank or belo... | Return None or a tax id of a child of *tax_id*.
If *tax_id* is None, then always returns None. Otherwise
returns a child if one exists, else None. The child must have
a proper rank below that of tax_id (i.e., genus, species, but
not no_rank or below_below_kingdom). | entailment |
def nary_subtree(self, tax_id, n=2):
"""Return a list of species tax_ids under *tax_id* such that
node under *tax_id* and above the species has two children.
"""
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
if rank == 'species':
... | Return a list of species tax_ids under *tax_id* such that
node under *tax_id* and above the species has two children. | entailment |
def validate_db(sqlalchemy_bind, is_enabled=ENABLE_DB):
""" Checks if a DB is authorized and responding before executing the function """
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
def is_db_responsive():
try:
sqlalchemy_bind.s... | Checks if a DB is authorized and responding before executing the function | entailment |
def substitute(template, mapping=None):
"""
Render the template *template*. *mapping* is a :class:`dict` with
values to add to the template.
"""
if mapping is None:
mapping = {}
templ = Template(template)
return templ.substitute(mapping) | Render the template *template*. *mapping* is a :class:`dict` with
values to add to the template. | entailment |
def dirtree(path):
"""
Find recursively and return all files and directories from
the path *path*.
"""
results = []
for name in glob.glob(os.path.join(path, '*')):
results.append(name)
if os.path.isdir(name):
results.extend(dirtree(name))
return results | Find recursively and return all files and directories from
the path *path*. | entailment |
def get_tornado_apps(context, debug=False):
"""
Create Tornado's application for all interfaces which are defined
in the configuration. *context* is instance of the
:class:`shelter.core.context.Context`. If *debug* is :const:`True`,
server will be run in **DEBUG** mode. Return :class:`list` of the
... | Create Tornado's application for all interfaces which are defined
in the configuration. *context* is instance of the
:class:`shelter.core.context.Context`. If *debug* is :const:`True`,
server will be run in **DEBUG** mode. Return :class:`list` of the
:class:`tornado.web.Application` instances. | entailment |
def run(self):
"""
Child process. Repeatedly call :meth:`loop` method every
:attribute:`interval` seconds.
"""
setproctitle.setproctitle("{:s}: {:s}".format(
self.context.config.name, self.__class__.__name__))
self.logger.info(
"Worker '%s' has bee... | Child process. Repeatedly call :meth:`loop` method every
:attribute:`interval` seconds. | entailment |
def get_new_nodes(fname):
"""
Return an iterator of dicts given a .csv-format file.
"""
with open(fname, 'rU') as infile:
infile = (line for line in infile if not line.startswith('#'))
reader = list(csv.DictReader(infile))
rows = (d for d in reader if d['tax_id'])
# for now... | Return an iterator of dicts given a .csv-format file. | entailment |
def getlines(fname):
"""
Returns iterator of whitespace-stripped lines in file, omitting
blank lines, lines beginning with '#', and line contents following
the first '#' character.
"""
with open(fname, 'rU') as f:
for line in f:
if line.strip() and not line.startswith('#'):
... | Returns iterator of whitespace-stripped lines in file, omitting
blank lines, lines beginning with '#', and line contents following
the first '#' character. | entailment |
def parse_raxml(handle):
"""Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned.
"""
s = ''.join(handle.readlines())
result = {}
try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s)
try_set... | Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned. | entailment |
def parse_stockholm(fobj):
"""Return a list of names from an Stockholm-format sequence alignment
file. ``fobj`` is an open file or another object representing a
sequence of lines.
"""
names = OrderedDict()
found_eof = False
for line in fobj:
line = line.strip()
if line == ... | Return a list of names from an Stockholm-format sequence alignment
file. ``fobj`` is an open file or another object representing a
sequence of lines. | entailment |
def has_rppr(rppr_name='rppr'):
"""
Check for rppr binary in path
"""
with open(os.devnull) as dn:
try:
subprocess.check_call([rppr_name], stdout=dn, stderr=dn)
except OSError as e:
if e.errno == os.errno.ENOENT:
return False
else:
... | Check for rppr binary in path | entailment |
def add_database_args(parser):
'''
Add a standard set of database arguments for argparse
'''
parser.add_argument(
'url',
nargs='?',
default='sqlite:///ncbi_taxonomy.db',
type=sqlite_default(),
help=('Database string URI or filename. If no database scheme '
... | Add a standard set of database arguments for argparse | entailment |
def sqlite_default():
'''
Prepend default scheme if none is specified. This helps provides backwards
compatibility with old versions of taxtastic where sqlite was the automatic
default database.
'''
def parse_url(url):
# TODO: need separate option for a config file
if url.endswit... | Prepend default scheme if none is specified. This helps provides backwards
compatibility with old versions of taxtastic where sqlite was the automatic
default database. | entailment |
def action(args):
"""Strips non-current files and rollback information from a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on).
"""
log.info('loading reference package')
refpkg.Refpkg(args.refpkg, create=False).strip() | Strips non-current files and rollback information from a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on). | entailment |
def get_conf_d_files(path):
"""
Return alphabetical ordered :class:`list` of the *.conf* files
placed in the path. *path* is a directory path.
::
>>> get_conf_d_files('conf/conf.d/')
['conf/conf.d/10-base.conf', 'conf/conf.d/99-dev.conf']
"""
if not os.path.isdir(path):
... | Return alphabetical ordered :class:`list` of the *.conf* files
placed in the path. *path* is a directory path.
::
>>> get_conf_d_files('conf/conf.d/')
['conf/conf.d/10-base.conf', 'conf/conf.d/99-dev.conf'] | entailment |
def get_conf_files(filename):
"""
Return :class:`list` of the all configuration files. *filename* is a
path of the main configuration file.
::
>>> get_conf_files('exampleapp.conf')
['exampleapp.conf', 'exampleapp.conf.d/10-database.conf']
"""
if not os.path.isfile(filename):
... | Return :class:`list` of the all configuration files. *filename* is a
path of the main configuration file.
::
>>> get_conf_files('exampleapp.conf')
['exampleapp.conf', 'exampleapp.conf.d/10-database.conf'] | entailment |
def get_configparser(filename=''):
"""
Read main configuration file and all files from *conf.d* subdirectory
and return parsed configuration as a **configparser.RawConfigParser**
instance.
"""
filename = filename or os.environ.get('SHELTER_CONFIG_FILENAME', '')
if not filename:
raise... | Read main configuration file and all files from *conf.d* subdirectory
and return parsed configuration as a **configparser.RawConfigParser**
instance. | entailment |
def name(self):
"""
Application name. It's used as a process name.
"""
try:
return self.config_parser.get('application', 'name')
except CONFIGPARSER_EXC:
return super(IniConfig, self).name | Application name. It's used as a process name. | entailment |
def interfaces(self):
"""
Interfaces as a :class:`list`of the
:class:`shelter.core.config.Config.Interface` instances.
"""
if 'interfaces' not in self._cached_values:
self._cached_values['interfaces'] = []
for name, interface in six.iteritems(self.settings... | Interfaces as a :class:`list`of the
:class:`shelter.core.config.Config.Interface` instances. | entailment |
def tz_file(name):
"""
Open a timezone file from the zoneinfo subdir for reading.
:param name: The name of the timezone.
:type name: str
:rtype: file
"""
try:
filepath = tz_path(name)
return open(filepath, 'rb')
except TimezoneNotFound:
# http://bugs.launchpad.... | Open a timezone file from the zoneinfo subdir for reading.
:param name: The name of the timezone.
:type name: str
:rtype: file | entailment |
def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.... | Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str | entailment |
def get_timezones():
"""
Get the supported timezones.
The list will be cached unless you set the "fresh" attribute to True.
:param fresh: Whether to get a fresh list or not
:type fresh: bool
:rtype: tuple
"""
base_dir = _DIRECTORY
zones = ()
for root, dirs, files in os.walk(b... | Get the supported timezones.
The list will be cached unless you set the "fresh" attribute to True.
:param fresh: Whether to get a fresh list or not
:type fresh: bool
:rtype: tuple | entailment |
def award_points(target, key, reason="", source=None):
"""
Awards target the point value for key. If key is an integer then it's a
one off assignment and should be interpreted as the actual point value.
"""
point_value, points = get_points(key)
if not ALLOW_NEGATIVE_TOTALS:
total = poi... | Awards target the point value for key. If key is an integer then it's a
one off assignment and should be interpreted as the actual point value. | entailment |
def points_awarded(target=None, source=None, since=None):
"""
Determine out how many points the given target has received.
"""
lookup_params = {}
if target is not None:
if isinstance(target, get_user_model()):
lookup_params["target_user"] = target
else:
look... | Determine out how many points the given target has received. | entailment |
def __validate_dates(start_date, end_date):
"""Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year.
"""
try:
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.datetime.str... | Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year. | entailment |
def __yahoo_request(query):
"""Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL.
"""
query = quote(query)
url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + \
'&format=json&env=store://datatables.org... | Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL. | entailment |
def request_quotes(tickers_list, selected_columns=['*']):
"""Request Yahoo Finance recent quotes.
Returns quotes information from YQL. The columns to be requested are
listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more
information on YQL.
>>> request_quotes(['AAPL'], ['Name',... | Request Yahoo Finance recent quotes.
Returns quotes information from YQL. The columns to be requested are
listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more
information on YQL.
>>> request_quotes(['AAPL'], ['Name', 'PreviousClose'])
{
'PreviousClose': '95.60',
... | entailment |
def request_historical(ticker, start_date, end_date):
"""Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retr... | Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retrieved. Information provided by YQL platform.
Check `here ... | entailment |
def download_historical(tickers_list, output_folder):
"""Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:p... | Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:param tickers_list: List of tickers that will be returned.
... | entailment |
def setup_logging(default_json_path=None, default_level=None, env_key='LOG_CFG',
custom_log_dir=None):
"""Setup logging configuration
"""
if not default_json_path:
default_json_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "logging.json")
path ... | Setup logging configuration | entailment |
def search_for_files(run_name, raw_extension=None, cellpy_file_extension=None,
raw_file_dir=None, cellpy_file_dir=None, prm_filename=None,
file_name_format=None, cache=None):
"""Searches for files (raw-data files and cellpy-files).
Args:
run_name(str): run-fil... | Searches for files (raw-data files and cellpy-files).
Args:
run_name(str): run-file identification.
raw_extension(str): optional, extension of run-files (without the '.').
cellpy_file_extension(str): optional, extension for cellpy files
(without the '.').
raw_file_dir(p... | entailment |
def squash_xml_to_text(elm, remove_namespaces=False):
"""Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
:para... | Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
:param elm: XML element
:type elm: :class:`xml.etree.ElementTr... | entailment |
def load(self, file_name):
"""Load a raw data-file
Args:
file_name (path)
Returns:
loaded test
"""
new_rundata = self.loader(file_name)
new_rundata = self.inspect(new_rundata)
return new_rundata | Load a raw data-file
Args:
file_name (path)
Returns:
loaded test | entailment |
def datetime2ole(dt):
"""converts from datetime object to ole datetime float"""
delta = dt - OLE_TIME_ZERO
delta_float = delta / datetime.timedelta(days=1) # trick from SO
return delta_float | converts from datetime object to ole datetime float | entailment |
def get_raw_limits():
"""Include the settings for how to decide what kind of
step you are examining here.
The raw limits are 'epsilons' used to check if the current
and/or voltage is stable (for example
for galvanostatic steps, one would expect that the current
is stable... | Include the settings for how to decide what kind of
step you are examining here.
The raw limits are 'epsilons' used to check if the current
and/or voltage is stable (for example
for galvanostatic steps, one would expect that the current
is stable (constant) and non-zero).
... | entailment |
def loader(self, file_name, bad_steps=None, **kwargs):
"""Loads data from biologics .mpr files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s
(in cycle c) to skip loading.
Returns:
new_tests (list... | Loads data from biologics .mpr files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s
(in cycle c) to skip loading.
Returns:
new_tests (list of data objects) | entailment |
def csv_dumper(**kwargs):
"""dump data to csv"""
logging.info("dumping to csv")
barn = kwargs["barn"]
farms = kwargs["farms"]
experiments = kwargs["experiments"]
for experiment, farm in zip(experiments, farms):
name = experiment.journal.name
project = experiment.journal.project
... | dump data to csv | entailment |
def ram_dumper(**kwargs):
"""Dump data to 'memory' for later usage."""
logging.debug("trying to save stuff in memory")
farms = kwargs["farms"]
experiments = kwargs["experiments"]
engine = kwargs["engine"]
try:
engine_name = engine.__name__
except AttributeError:
engine_name ... | Dump data to 'memory' for later usage. | entailment |
def screen_dumper(**kwargs):
"""Dump data to screen."""
farms = kwargs["farms"]
engine = kwargs["engine"]
logging.info("dumping to screen")
print(f"\n[Screen dumper] ({engine})")
try:
if len(farms) == 1:
print(f"You have one farm with little pandas.")
else:
... | Dump data to screen. | entailment |
def create_legend(info, c, option="clean", use_index=False):
"""creating more informative legends"""
logging.debug(" - creating legends")
mass, loading, label = info.loc[c, ["masses", "loadings", "labels"]]
if use_index or not label:
label = c.split("_")
label = "_".join(label[1:])
... | creating more informative legends | entailment |
def create_plot_option_dicts(info, marker_types=None, colors=None,
line_dash=None, size=None):
"""Create two dictionaries with plot-options.
The first iterates colors (based on group-number), the second iterates
through marker types.
Returns: group_styles (dict), sub_group... | Create two dictionaries with plot-options.
The first iterates colors (based on group-number), the second iterates
through marker types.
Returns: group_styles (dict), sub_group_styles (dict) | entailment |
def summary_plotting_engine(**kwargs):
"""creates plots of summary data."""
logging.debug(f"Using {prms.Batch.backend} for plotting")
experiments = kwargs["experiments"]
farms = kwargs["farms"]
barn = None
logging.debug(" - summary_plot_engine")
farms = _preparing_data_and_plotting(
... | creates plots of summary data. | entailment |
def run_dumper(self, dumper):
"""run dumber (once pr. engine)
Args:
dumper: dumper to run (function or method).
The dumper takes the attributes experiments, farms, and barn as input.
It does not return anything. But can, if the dumper designer feels in
a bad and nas... | run dumber (once pr. engine)
Args:
dumper: dumper to run (function or method).
The dumper takes the attributes experiments, farms, and barn as input.
It does not return anything. But can, if the dumper designer feels in
a bad and nasty mood, modify the input objects
... | entailment |
def _comports():
'''
Returns
-------
pandas.DataFrame
Table containing descriptor, and hardware ID of each available COM
port, indexed by port (e.g., "COM4").
'''
return (pd.DataFrame(list(map(list, serial.tools.list_ports.comports())),
columns=['port', '... | Returns
-------
pandas.DataFrame
Table containing descriptor, and hardware ID of each available COM
port, indexed by port (e.g., "COM4"). | entailment |
def comports(vid_pid=None, include_all=False, check_available=True,
only_available=False):
'''
.. versionchanged:: 0.9
Add :data:`check_available` keyword argument to optionally check if
each port is actually available by attempting to open a temporary
connection.
A... | .. versionchanged:: 0.9
Add :data:`check_available` keyword argument to optionally check if
each port is actually available by attempting to open a temporary
connection.
Add :data:`only_available` keyword argument to only include ports that
are actually available for connection.... | entailment |
def _get_serial_ports_windows():
'''
Uses the Win32 registry to return a iterator of serial (COM) ports existing
on this computer.
See http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows
'''
import six.moves.winreg as winreg
reg_path = 'HARDWARE\\DEVICEMAP\\SERIA... | Uses the Win32 registry to return a iterator of serial (COM) ports existing
on this computer.
See http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows | entailment |
def get_port(self, baud_rate):
'''
Using the specified baud-rate, attempt to connect to each available
serial port. If the `test_connection()` method returns `True` for a
port, update the `port` attribute and return the port.
In the case where the `test_connection()` does not r... | Using the specified baud-rate, attempt to connect to each available
serial port. If the `test_connection()` method returns `True` for a
port, update the `port` attribute and return the port.
In the case where the `test_connection()` does not return `True` for
any of the evaluated ports... | entailment |
def _read(name):
"""read the yml file"""
logging.debug("Reading config-file: %s" % name)
try:
with open(name, "r") as config_file:
prm_dict = yaml.load(config_file)
except yaml.YAMLError:
raise yaml.YAMLErrorr
else:
return prm_dict | read the yml file | entailment |
def cycles_engine(**kwargs):
"""engine to extract cycles"""
logging.info("cycles_engine:")
logging.info("Not ready for production")
# raise NotImplementedError
experiments = kwargs["experiments"]
farms = []
barn = "raw_dir" # Its a murder in the red barn - murder in the red barn
for ... | engine to extract cycles | entailment |
def raw_data_engine(**kwargs):
"""engine to extract raw data"""
logger.debug("cycles_engine")
raise NotImplementedError
experiments = kwargs["experiments"]
farms = []
barn = "raw_dir"
for experiment in experiments:
farms.append([])
return farms, barn | engine to extract raw data | entailment |
def summary_engine(**kwargs):
"""engine to extract summary data"""
logger.debug("summary_engine")
# farms = kwargs["farms"]
farms = []
experiments = kwargs["experiments"]
for experiment in experiments:
if experiment.selected_summaries is None:
selected_summaries = [
... | engine to extract summary data | entailment |
def simple_db_engine(reader=None, srnos=None):
"""engine that gets values from the simple excel 'db'"""
if reader is None:
reader = dbreader.Reader()
logger.debug("No reader provided. Creating one myself.")
info_dict = dict()
info_dict["filenames"] = [reader.get_cell_name(srno) for srn... | engine that gets values from the simple excel 'db | entailment |
def orify(event, changed_callback):
'''
Override ``set`` and ``clear`` methods on event to call specified callback
function after performing default behaviour.
Parameters
----------
'''
event.changed = changed_callback
if not hasattr(event, '_set'):
# `set`/`clear` methods have... | Override ``set`` and ``clear`` methods on event to call specified callback
function after performing default behaviour.
Parameters
---------- | entailment |
def OrEvent(*events):
'''
Parameters
----------
events : list(threading.Event)
List of events.
Returns
-------
threading.Event
Event that is set when **at least one** of the events in :data:`events`
is set.
'''
or_event = threading.Event()
def changed():... | Parameters
----------
events : list(threading.Event)
List of events.
Returns
-------
threading.Event
Event that is set when **at least one** of the events in :data:`events`
is set. | entailment |
def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES):
'''
Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or... | Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload to send.
timeout_s : float, optional
Maximum time to wait... | entailment |
def connection_made(self, transport):
"""Called when reader thread is started"""
self.port = transport.serial.port
logger.debug('connection_made: `%s` `%s`', self.port, transport)
self.transport = transport
self.connected.set()
self.disconnected.clear() | Called when reader thread is started | entailment |
def connection_lost(self, exception):
"""\
Called when the serial port is closed or the reader loop terminated
otherwise.
"""
if isinstance(exception, Exception):
logger.debug('Connection to port `%s` lost: %s', self.port,
exception)
e... | \
Called when the serial port is closed or the reader loop terminated
otherwise. | entailment |
def write(self, data, timeout_s=None):
'''
Write to serial port.
Waits for serial connection to be established before writing.
Parameters
----------
data : str or bytes
Data to write to serial port.
timeout_s : float, optional
Maximum num... | Write to serial port.
Waits for serial connection to be established before writing.
Parameters
----------
data : str or bytes
Data to write to serial port.
timeout_s : float, optional
Maximum number of seconds to wait for serial connection to be
... | entailment |
def request(self, response_queue, payload, timeout_s=None,
poll=POLL_QUEUES):
'''
Send
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str ... | Send
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload to send.
timeout_s : float, optional
Maximum time to wait (in sec... | entailment |
def fieldname_to_dtype(fieldname):
"""Converts a column header from the MPT file into a tuple of
canonical name and appropriate numpy dtype"""
if fieldname == 'mode':
return ('mode', np.uint8)
elif fieldname in ("ox/red", "error", "control changes", "Ns changes",
"counter... | Converts a column header from the MPT file into a tuple of
canonical name and appropriate numpy dtype | entailment |
def comma_converter(float_string):
"""Convert numbers to floats whether the decimal point is '.' or ','"""
trans_table = maketrans(b',', b'.')
return float(float_string.translate(trans_table)) | Convert numbers to floats whether the decimal point is '.' or ', | entailment |
def MPTfile(file_or_path):
"""Opens .mpt files as numpy record arrays
Checks for the correct headings, skips any comments and returns a
numpy record array object and a list of comments
"""
if isinstance(file_or_path, str):
mpt_file = open(file_or_path, 'rb')
else:
mpt_file = fi... | Opens .mpt files as numpy record arrays
Checks for the correct headings, skips any comments and returns a
numpy record array object and a list of comments | entailment |
def MPTfileCSV(file_or_path):
"""Simple function to open MPT files as csv.DictReader objects
Checks for the correct headings, skips any comments and returns a
csv.DictReader object and a list of comments
"""
if isinstance(file_or_path, str):
mpt_file = open(file_or_path, 'r')
else:
... | Simple function to open MPT files as csv.DictReader objects
Checks for the correct headings, skips any comments and returns a
csv.DictReader object and a list of comments | entailment |
def read_VMP_modules(fileobj, read_module_data=True):
"""Reads in module headers in the VMPmodule_hdr format. Yields a dict with
the headers and offset for each module.
N.B. the offset yielded is the offset to the start of the data i.e. after
the end of the header. The data runs from (offset) to (offse... | Reads in module headers in the VMPmodule_hdr format. Yields a dict with
the headers and offset for each module.
N.B. the offset yielded is the offset to the start of the data i.e. after
the end of the header. The data runs from (offset) to (offset+length) | entailment |
def get_headers_global():
"""Defines the so-called global column headings for Arbin .res-files"""
headers = dict()
# - global column headings (specific for Arbin)
headers["applications_path_txt"] = 'Applications_Path'
headers["channel_index_txt"] = 'Channel_Index'
headers... | Defines the so-called global column headings for Arbin .res-files | entailment |
def inspect(self, run_data):
"""Inspect the file -> reports to log (debug)"""
# TODO: type checking
if DEBUG_MODE:
checked_rundata = []
for data in run_data:
new_cols = data.dfdata.columns
for col in self.headers_normal:
... | Inspect the file -> reports to log (debug) | entailment |
def _iterdump(self, file_name, headers=None):
"""
Function for dumping values from a file.
Should only be used by developers.
Args:
file_name: name of the file
headers: list of headers to pick
default:
["Discharge_Capacity", "Char... | Function for dumping values from a file.
Should only be used by developers.
Args:
file_name: name of the file
headers: list of headers to pick
default:
["Discharge_Capacity", "Charge_Capacity"]
Returns: pandas.DataFrame | entailment |
def loader(self, file_name, bad_steps=None, **kwargs):
"""Loads data from arbin .res files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s (in cycle c) to skip loading.
Returns:
new_tests (list of data objects)... | Loads data from arbin .res files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s (in cycle c) to skip loading.
Returns:
new_tests (list of data objects) | entailment |
def _save_multi(data, file_name, sep=";"):
"""convenience function for storing data column-wise in a csv-file."""
logger.debug("saving multi")
with open(file_name, "w", newline='') as f:
logger.debug(f"{file_name} opened")
writer = csv.writer(f, delimiter=sep)
try:
writer... | convenience function for storing data column-wise in a csv-file. | entailment |
def _extract_dqdv(cell_data, extract_func, last_cycle):
"""Simple wrapper around the cellpy.utils.ica.dqdv function."""
from cellpy.utils.ica import dqdv
list_of_cycles = cell_data.get_cycle_numbers()
if last_cycle is not None:
list_of_cycles = [c for c in list_of_cycles if c <= int(last_cycle)... | Simple wrapper around the cellpy.utils.ica.dqdv function. | entailment |
def make_df_from_batch(batch_name, batch_col="b01", reader=None, reader_label=None):
"""Create a pandas DataFrame with the info needed for ``cellpy`` to load
the runs.
Args:
batch_name (str): Name of the batch.
batch_col (str): The column where the batch name is in the db.
reader (m... | Create a pandas DataFrame with the info needed for ``cellpy`` to load
the runs.
Args:
batch_name (str): Name of the batch.
batch_col (str): The column where the batch name is in the db.
reader (method): the db-loader method.
reader_label (str): the label for the db-loader (if db... | entailment |
def create_folder_structure(project_name, batch_name):
"""This function creates a folder structure for the batch project.
The folder structure consists of main working folder ``project_name`
located in the ``outdatadir`` (as defined in the cellpy configuration file)
with a sub-folder named ``batch_name... | This function creates a folder structure for the batch project.
The folder structure consists of main working folder ``project_name`
located in the ``outdatadir`` (as defined in the cellpy configuration file)
with a sub-folder named ``batch_name``. It also creates a folder
inside the ``batch_name`` fol... | entailment |
def read_and_save_data(info_df, raw_dir, sep=";", force_raw=False,
force_cellpy=False,
export_cycles=False, shifted_cycles=False,
export_raw=True,
export_ica=False, save=True, use_cellpy_stat_file=False,
p... | Reads and saves cell data defined by the info-DataFrame.
The function iterates through the ``info_df`` and loads data from the runs.
It saves individual data for each run (if selected), as well as returns a
list of ``cellpy`` summary DataFrames, a list of the indexes (one for each
run; same as used as ... | entailment |
def save_summaries(frames, keys, selected_summaries, batch_dir, batch_name):
"""Writes the summaries to csv-files
Args:
frames: list of ``cellpy`` summary DataFrames
keys: list of indexes (typically run-names) for the different runs
selected_summaries: list defining which summary data t... | Writes the summaries to csv-files
Args:
frames: list of ``cellpy`` summary DataFrames
keys: list of indexes (typically run-names) for the different runs
selected_summaries: list defining which summary data to save
batch_dir: directory to save to
batch_name: the batch name (w... | entailment |
def pick_summary_data(key, summary_df, selected_summaries):
"""picks the selected pandas.DataFrame"""
selected_summaries_dict = create_selected_summaries_dict(selected_summaries)
value = selected_summaries_dict[key]
return summary_df.iloc[:, summary_df.columns.get_level_values(1) == value] | picks the selected pandas.DataFrame | entailment |
def plot_summary_data(ax, df, info_df, color_list, symbol_list, is_charge=False,
plot_style=None):
"""creates a plot of the selected df-data in the given axes.
Typical usage:
standard_fig, (ce_ax, cap_ax, ir_ax) = plt.subplots(nrows=3, ncols=1,
... | creates a plot of the selected df-data in the given axes.
Typical usage:
standard_fig, (ce_ax, cap_ax, ir_ax) = plt.subplots(nrows=3, ncols=1,
sharex=True)
list_of_lines, plot_style = plot_summary_data(ce_ax, ce_df,
... | entailment |
def plot_summary_figure(info_df, summary_df, color_list, symbol_list,
selected_summaries,
batch_dir, batch_name, plot_style=None, show=False,
save=True,
figure_type=None):
"""Create a figure with summary graphs.
Args... | Create a figure with summary graphs.
Args:
info_df: the pandas DataFrame with info about the runs.
summary_df: a pandas DataFrame with the summary data.
color_list: a list of colors to use (one pr. group)
symbol_list: a list of symbols to use (one pr. cell in largest group)
s... | entailment |
def export_dqdv(cell_data, savedir, sep, last_cycle=None):
"""Exports dQ/dV data from a CellpyData instance.
Args:
cell_data: CellpyData instance
savedir: path to the folder where the files should be saved
sep: separator for the .csv-files.
last_cycle: only export up to this cyc... | Exports dQ/dV data from a CellpyData instance.
Args:
cell_data: CellpyData instance
savedir: path to the folder where the files should be saved
sep: separator for the .csv-files.
last_cycle: only export up to this cycle (if not None) | entailment |
def init(*args, **kwargs):
"""Returns an initialized instance of the Batch class"""
# set up cellpy logger
default_log_level = kwargs.pop("default_log_level", None)
import cellpy.log as log
log.setup_logging(custom_log_dir=prms.Paths["filelogdir"],
default_level=default_log_lev... | Returns an initialized instance of the Batch class | entailment |
def debugging():
"""This one I use for debugging..."""
print("In debugging")
json_file = r"C:\Scripting\Processing\Cell" \
r"data\outdata\SiBEC\cellpy_batch_bec_exp02.json"
b = init(default_log_level="DEBUG")
b.load_info_df(json_file)
print(b.info_df.head())
# setting some ... | This one I use for debugging... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.