docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get the first and second lines Args: f (filelike): File that is opened for ascii. Returns: bytes
def _get_two_lines(f): l0 = f.readline() l1 = f.readline() return l0, l1
712,219
Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class
def classify_format(f): l0, l1 = _get_two_lines(f) if loader.glove.check_valid(l0, l1): return _glove elif loader.word2vec_text.check_valid(l0, l1): return _word2vec_text elif loader.word2vec_bin.check_valid(l0, l1): return _word2vec_bin else: raise OSError(b"Inv...
712,220
Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved
def grid_reload_from_ids(oargrid_jobids): gk = get_api_client() jobs = [] for site, job_id in oargrid_jobids: jobs.append(gk.sites[site].jobs[job_id]) return jobs
712,489
Destroy all the jobs with a given name. Args: job_name (str): the job name
def grid_destroy_from_name(job_name): jobs = grid_reload_from_name(job_name) for job in jobs: job.delete() logger.info("Killing the job (%s, %s)" % (job.site, job.uid))
712,490
Destroy all the jobs with corresponding ids Args: oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple identifying the jobs for each site.
def grid_destroy_from_ids(oargrid_jobids): jobs = grid_reload_from_ids(oargrid_jobids) for job in jobs: job.delete() logger.info("Killing the jobs %s" % oargrid_jobids)
712,491
Submit a job Args: job_spec (dict): The job specifiation (see Grid'5000 API reference)
def submit_jobs(job_specs): gk = get_api_client() jobs = [] try: for site, job_spec in job_specs: logger.info("Submitting %s on %s" % (job_spec, site)) jobs.append(gk.sites[site].jobs.create(job_spec)) except Exception as e: logger.error("An error occured dur...
712,492
Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state.
def wait_for_jobs(jobs): all_running = False while not all_running: all_running = True time.sleep(5) for job in jobs: job.refresh() scheduled = getattr(job, "scheduled_at", None) if scheduled is not None: logger.info("Waiting for ...
712,493
Deploy and wait for the deployment to be finished. Args: site(str): the site nodes(list): list of nodes (str) to depoy options(dict): option of the deployment (refer to the Grid'5000 API Specifications) Returns: tuple of deployed(list), undeployed(list) nodes.
def grid_deploy(site, nodes, options): gk = get_api_client() environment = options.pop("env_name") options.update(environment=environment) options.update(nodes=nodes) key_path = DEFAULT_SSH_KEYFILE options.update(key=key_path.read_text()) logger.info("Deploying %s with options %s" % (no...
712,494
Set the interface of the nodes in a specific vlan. It is assumed that the same interface name is available on the node. Args: site(str): site to consider nodes(list): nodes to consider interface(str): the network interface to put in the vlan vlan_id(str): the id of the vlan
def set_nodes_vlan(site, nodes, interface, vlan_id): def _to_network_address(host): splitted = host.split('.') splitted[0] = splitted[0] + "-" + interface return ".".join(splitted) gk = get_api_client() network_addresses = [_to_network_address(n) for n in nodes] gk...
712,495
Get all the corresponding sites of the passed clusters. Args: clusters(list): list of string uid of sites (e.g 'rennes') Return: dict corresponding to the mapping cluster uid to python-grid5000 site
def clusters_sites_obj(clusters): result = {} all_clusters = get_all_clusters_sites() clusters_sites = {c: s for (c, s) in all_clusters.items() if c in clusters} for cluster, site in clusters_sites.items(): # here we want the site python-grid5000 site object ...
712,496
Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes')
def get_nodes(cluster): gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
712,498
Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are re...
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): nics = get_nics(cluster) # NOTE(msimonin): Since 05/18 nics on g5k nodes have predictable names but # the api description keep the legacy name (device key) and the new # predictable name (key name). The legacy names is still used fo...
712,499
Constructor. Args: excluded_sites(list): sites to forget about when reloading the jobs. The primary use case was to exclude unreachable sites and allow the program to go on.
def __init__(self, excluded_sites=None, **kwargs): super().__init__(**kwargs) self.excluded_site = excluded_sites if excluded_sites is None: self.excluded_site = []
712,503
Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started
def init(self, force_deploy=False): machines = self.provider_conf.machines networks = self.provider_conf.networks _networks = [] for network in networks: ipnet = IPNetwork(network.cidr) _networks.append({ "netpool": list(ipnet)[10:-10], ...
713,010
Saves one environment. Args: env (dict): the env dict to save.
def _save_env(env): env_path = os.path.join(env["resultdir"], "env") if os.path.isdir(env["resultdir"]): with open(env_path, "w") as f: yaml.dump(env, f)
713,372
Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values weight fractions. No wildcard are accepted.
def convert_mass_to_atomic_fractions(mass_fractions): atomic_fractions = {} for z, mass_fraction in mass_fractions.items(): atomic_fractions[z] = mass_fraction / pyxray.element_atomic_weight(z) total_fraction = sum(atomic_fractions.values()) for z, fraction in atomic_fractions.items(): ...
713,915
Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values atomic fractions. No wildcard are accepted.
def convert_atomic_to_mass_fractions(atomic_fractions): # Calculate total atomic mass atomic_masses = {} total_atomic_mass = 0.0 for z, atomic_fraction in atomic_fractions.items(): atomic_mass = pyxray.element_atomic_weight(z) atomic_masses[z] = atomic_mass total_atomic_mass...
713,916
Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted.
def convert_formula_to_atomic_fractions(formula): mole_fractions = {} total_mole_fraction = 0.0 for match in CHEMICAL_FORMULA_PATTERN.finditer(formula): symbol, mole_fraction = match.groups() z = pyxray.element_atomic_number(symbol.strip()) if mole_fraction == '': ...
713,917
Creates a pure composition. Args: z (int): atomic number
def from_pure(cls, z): return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
713,920
Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will get a m...
def from_mass_fractions(cls, mass_fractions, formula=None): mass_fractions = process_wildcard(mass_fractions) atomic_fractions = convert_mass_to_atomic_fractions(mass_fractions) if not formula: formula = generate_name(atomic_fractions) return cls(cls._key, mass_fract...
713,921
Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init`
def _to_enos_roles(roles): def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX for nic, roles in h["nics"]: for role in roles: extra[role] = nic return Host(h["host"], user="root", extra=extra) enos_roles =...
713,955
Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init`
def _to_enos_networks(networks): nets = [] for roles, network in networks: nets.append(network.to_enos(roles)) logger.debug(nets) return nets
713,956
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
def init(self, force_deploy=False, client=None): _force_deploy = self.provider_conf.force_deploy self.provider_conf.force_deploy = _force_deploy or force_deploy self._provider_conf = self.provider_conf.to_dict() r = api.Resources(self._provider_conf, client=client) r.lau...
713,957
Reset the network constraints (latency, bandwidth ...) Remove any filter that have been applied to shape the traffic. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` inventory (str): path to the inventory
def reset_network(roles, extra_vars=None): logger.debug('Reset the constraints') if not extra_vars: extra_vars = {} tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME) _check_tmpdir(tmpdir) utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml') options = {'enos_action': 'tc_reset', ...
714,124
Wait for all the machines to be ssh-reachable Let ansible initiates a communication and retries if needed. Args: inventory (string): path to the inventoy file to test retries (int): Number of time we'll be retrying an SSH connection interval (int): Interval to wait in seconds between t...
def wait_ssh(roles, retries=100, interval=30): utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml') options = {'enos_action': 'ping'} for i in range(0, retries): try: run_ansible([utils_playbook], roles=roles, extra_vars=options, ...
714,125
Expand group names. Args: grp (string): group names to expand Returns: list of groups Examples: * grp[1-3] will be expanded to [grp1, grp2, grp3] * grp1 will be expanded to [grp1]
def expand_groups(grp): p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]") m = p.match(grp) if m is not None: s = int(m.group('start')) e = int(m.group('end')) n = m.group('name') return list(map(lambda x: n + str(x), range(s, e + 1))) else: retur...
714,126
Make a function compatible with xarray.DataArray. This function is intended to be used as a decorator like:: >>> @dc.xarrayfunc >>> def func(array): ... # do something ... return newarray >>> >>> result = func(array) Args: func (function): Funct...
def xarrayfunc(func): @wraps(func) def wrapper(*args, **kwargs): if any(isinstance(arg, xr.DataArray) for arg in args): newargs = [] for arg in args: if isinstance(arg, xr.DataArray): newargs.append(arg.values) else: ...
714,447
Calculate power spectrum density of data. Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). ax (matplotlib.axes): Axis you want to plot on. doplot (bool): Plot ho...
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False): logger = getLogger('decode.utils.ndarray.psd') if overlap_half: step = int(len(data) / (ndivide + 1)) size = step * 2 else: step = int(len(data) / ndivide) size = step if bin(len(data)).count('1') !=...
714,595
Calculate Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. Returns: vk (np.ndarray): Frequency. allanvar (np.ndarray): Allan variance.
def allan_variance(data, dt, tmax=10): allanvar = [] nmax = len(data) if len(data) < tmax / dt else int(tmax / dt) for i in range(1, nmax+1): databis = data[len(data) % i:] y = databis.reshape(len(data)//i, i).mean(axis=1) allanvar.append(((y[1:] - y[:-1])**2).mean() / 2) re...
714,596
Covert a decode cube to a decode array. Args: cube (decode.cube): Decode cube to be cast. template (decode.array): Decode array whose shape the cube is cast on. Returns: decode array (decode.array): Decode array. Notes: This functions is under development.
def fromcube(cube, template): array = dc.zeros_like(template) y, x = array.y.values, array.x.values gy, gx = cube.y.values, cube.x.values iy = interp1d(gy, np.arange(len(gy)))(y) ix = interp1d(gx, np.arange(len(gx)))(x) for ch in range(len(cube.ch)): array[:,ch] = map_coordinates(...
714,652
Make a continuum array. Args: cube (decode.cube): Decode cube which will be averaged over channels. kwargs (optional): Other arguments. inchs (list): Included channel kidids. exchs (list): Excluded channel kidids. Returns: decode cube (decode.cube): Decode cube ...
def makecontinuum(cube, **kwargs): ### pick up kwargs inchs = kwargs.pop('inchs', None) exchs = kwargs.pop('exchs', None) if (inchs is not None) or (exchs is not None): raise KeyError('Inchs and exchs are no longer supported. Use weight instead.') # if inchs is not None: # log...
714,654
u"""Will ask a question and keeps prompting until answered. Args: question (str): Question to ask end user default (str): Default answer if user just press enter at prompt answer (str): Used for testing Returns: (bool) Meaning: True - Answer is yes ...
def ask_yes_no(question, default='no', answer=None): u default = default.lower() yes = [u'yes', u'ye', u'y'] no = [u'no', u'n'] if default in no: help_ = u'[N/y]?' default = False else: default = True help_ = u'[Y/n]?' while 1: display = question + '\n...
714,682
u"""Ask user a question and confirm answer Args: question (str): Question to ask user default (str): Default answer if no input from user required (str): Require user to input answer answer (str): Used for testing is_answer_correct (str): Used for testing
def get_correct_answer(question, default=None, required=False, answer=None, is_answer_correct=None): u while 1: if default is None: msg = u' - No Default Available' else: msg = (u'\n[DEFAULT] -> {}\nPress Enter To ' u'Use Default'...
714,683
Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash
def get_package_hashes(filename): log.debug('Getting package hashes') filename = os.path.abspath(filename) with open(filename, 'rb') as f: data = f.read() _hash = hashlib.sha256(data).hexdigest() log.debug('Hash for file %s: %s', filename, _hash) return _hash
714,931
Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto().
def savefits(cube, fitsname, **kwargs): ### pick up kwargs dropdeg = kwargs.pop('dropdeg', False) ndim = len(cube.dims) ### load yaml FITSINFO = get_data('decode', 'data/fitsinfo.yaml') hdrdata = yaml.load(FITSINFO, dc.utils.OrderedLoader) ### default header if ndim == 2: ...
714,961
Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray.
def loadnetcdf(filename, copy=True): filename = str(Path(filename).expanduser()) if copy: dataarray = xr.open_dataarray(filename).copy() else: dataarray = xr.open_dataarray(filename, chunks={}) if dataarray.name is None: dataarray.name = filename.rstrip('.nc') for key...
714,962
Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used.
def savenetcdf(dataarray, filename=None): if filename is None: if dataarray.name is not None: filename = dataarray.name else: filename = uuid4().hex[:8] else: filename = str(Path(filename).expanduser()) if not filename.endswith('.nc'): filename +...
714,963
Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.ar...
def zeros(shape, dtype=None, **kwargs): data = np.zeros(shape, dtype) return dc.array(data, **kwargs)
714,988
Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.arr...
def ones(shape, dtype=None, **kwargs): data = np.ones(shape, dtype) return dc.array(data, **kwargs)
714,989
Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of th...
def full(shape, fill_value, dtype=None, **kwargs): return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)
714,990
Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array...
def empty(shape, dtype=None, **kwargs): data = np.empty(shape, dtype) return dc.array(data, **kwargs)
714,991
Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. ...
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs): if ax is None: ax = plt.gca() if scantypes is None: ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs) else: for scantype in scantypes: ax.plot(array[coords[0]][array.scantype == sca...
715,097
Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (m...
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs): if ax is None: ax = plt.gca() index = np.where(array.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) if scantypes is None: if xt...
715,098
Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow().
def plot_chmap(cube, kidid, ax=None, **kwargs): if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax...
715,100
Plot PSD (Power Spectral Density). Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). overlap_half (bool): Split data to half-overlapped regions. ax (matplotlib.ax...
def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs): if ax is None: ax = plt.gca() vk, psddata = psd(data, dt, ndivide, window, overlap_half) ax.loglog(vk, psddata, **kwargs) ax.set_xlabel('Frequency [Hz]') ax.set_ylabel('PSD') ax.legend()
715,101
Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot().
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs): if ax is None: ax = plt.gca() tk, allanvar = allan_variance(data, dt, tmax) ax.loglog(tk, allanvar, **kwargs) ax.set_xlabel('Time [s]') ax.set_ylabel('Allan Variance') ax.legend()
715,102
Returns parent directory of mac .app Args: directory (str): Current directory Returns: (str): Parent directory of mac .app
def get_mac_dot_app_dir(directory): return os.path.dirname(os.path.dirname(os.path.dirname(directory)))
715,166
Copy a function object with different name. Args: func (function): Function to be copied. name (string, optional): Name of the new function. If not spacified, the same name of `func` will be used. Returns: newfunc (function): New function with different name.
def copy_function(func, name=None): code = func.__code__ newname = name or func.__name__ newcode = CodeType( code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co...
715,176
Open youtube. Args: keyword (optional): Search word.
def youtube(keyword=None): if keyword is None: web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw') else: web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))
715,268
Parse the output analysis files from MIP for adding info to trend database Args: mip_config_raw (dict): raw YAML input from MIP analysis config file qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample in...
def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict: outdata = _define_output_dict() _config(mip_config_raw, outdata) _qc_metrics(outdata, qcmetrics_raw) _qc_sample_info(outdata, sampleinfo_raw) return outdata
715,598
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data
def parse_config(data: dict) -> dict: return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': sample_id, 'type': analysis_type, } for sample_id, analysis_type in data['analysis_type'].items()], 'config_path': data['co...
716,281
Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data
def parse_sampleinfo(data: dict) -> dict: genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version']}" if 'svdb' in data['program']: svdb_outpath = (f"{data['program']['svdb']['path']}") else: svdb_outpath = '' outdata = { ...
716,282
Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data
def parse_qcmetrics(metrics: dict) -> dict: data = { 'versions': { 'freebayes': metrics['program']['freebayes']['version'], 'gatk': metrics['program']['gatk']['version'], 'manta': metrics['program'].get('manta', {}).get('version'), 'bcftools': metrics['pr...
716,283
Start a task. This function depends on the underlying implementation of _start, which any subclass of ``Task`` should implement. Args: wait (bool): Whether or not to wait on the task to finish before returning from this function. Default `False`. Raises: ...
def start(self, wait=False): if self._status is not TaskStatus.IDLE: raise RuntimeError("Cannot start %s in state %s" % (self, self._status)) self._status = TaskStatus.STARTED STARTED_TASKS.add(self) self._start() if wait: ...
716,502
Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as *...
def send_file(self, file_name, remote_destination=None, **kwargs): if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostname, remote_destination)], **kwargs)
716,688
Get a file from a remote host with rsync. Args: file_name (str): The relative location of the file on the remote host. local_destination (str): The destination for the file on the local host. If `None`, will be assumed to be the same as *...
def get_file(self, file_name, local_destination=None, **kwargs): if not local_destination: local_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', '%s:%s' % (self.hostname, file_name), local_destination], **kwargs)
716,689
Serialize a migration session state to yaml using nicer formatting Args: raw: object to serialize Returns: string (of yaml) Specifically, this forces the "output" member of state step dicts (e.g. state[0]['output']) to use block formatting. For example, rather than this: - migration: [app...
def dump_migration_session_state(raw): class BlockStyle(str): pass class SessionDumper(yaml.SafeDumper): pass def str_block_formatter(dumper, data): return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|') SessionDumper.add_representer(BlockStyle, str_block_formatter) ...
716,977
Add migrations to be applied. Args: migrations: a list of migrations to add of the form [(app, migration_name), ...] Raises: MigrationSessionError if called on a closed MigrationSession
def add_migrations(self, migrations): if self.__closed: raise MigrationSessionError("Can't change applied session") self._to_apply.extend(migrations)
716,979
Create a repr from an instance of a class Args: inst: The class instance we are generating a repr of attrs: The attributes that should appear in the repr
def make_repr(inst, attrs): # type: (object, Sequence[str]) -> str arg_str = ", ".join( "%s=%r" % (a, getattr(inst, a)) for a in attrs if hasattr(inst, a)) repr_str = "%s(%s)" % (inst.__class__.__name__, arg_str) return repr_str
717,445
Annotate a type with run-time accessible metadata Args: description: A one-line description for the argument typ: The type of the Anno, can also be set via context manager name: The name of the Anno, can also be set via context manager
def __init__(self, description, typ=None, name=None, default=NO_DEFAULT): # type: (str, Any, str, Any) -> None self._names_on_enter = None # type: Optional[Set[str]] self.default = default # type: Any self.typ = typ # type: Any self.name = name # type: Optional[str] ...
717,446
Make a call_types dictionary that describes what arguments to pass to f Args: f: The function to inspect for argument names (without self) globals_d: A dictionary of globals to lookup annotation definitions in
def make_call_types(f, globals_d): # type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno] arg_spec = getargspec(f) args = [k for k in arg_spec.args if k != "self"] defaults = {} # type: Dict[str, Any] if arg_spec.defaults: default_args = args[-len(arg_spec.defaults):] for a,...
717,477
Create an annotations dictionary from Python2 type comments http://mypy.readthedocs.io/en/latest/python2.html Args: f: The function to examine for type comments globals_d: The globals dictionary to get type idents from. If not specified then make the annotations dict contain string...
def make_annotations(f, globals_d=None): # type: (Callable, Dict) -> Dict[str, Any] locals_d = {} # type: Dict[str, Any] if globals_d is None: # If not given a globals_d then we should just populate annotations with # the strings in the type comment. globals_d = {} # Th...
717,478
Convert the confusion matrix to the Matthews correlation coefficient Parameters: ----------- cm : ndarray 2x2 confusion matrix with np.array([[tn, fp], [fn, tp]]) tn, fp, fn, tp : float four scalar variables - tn : number of true negatives - fp : number of false positiv...
def confusion_to_mcc(*args): if len(args) is 1: tn, fp, fn, tp = args[0].ravel().astype(float) elif len(args) is 4: tn, fp, fn, tp = [float(a) for a in args] else: raise Exception(( "Input argument is not an 2x2 matrix, " "nor 4 elements tn, fp, fn, tp.")...
717,794
Initialize the service registry. Creates the database table if it does not exist. Args: rr (doublethink.Rethinker): a doublethink.Rethinker, which must have `dbname` set
def __init__(self, rr, table='services'): self.rr = rr self.table = table self._ensure_table()
718,347
Look up healthy services in the registry. A service is considered healthy if its 'last_heartbeat' was less than 'ttl' seconds ago Args: role (str, optional): role name Returns: If `role` is supplied, returns list of healthy services for the given ro...
def healthy_services(self, role=None): try: query = self.rr.table(self.table) if role: query = query.get_all(role, index='role') query = query.filter( lambda svc: r.now().sub(svc["last_heartbeat"]) < svc["ttl"] #.default(20.0) ...
718,352
Get the module specified by the value of option_name. The value of the configuration option will be used to load the module by name from the known module list or treated as a path if not found in known_modules. Args: option_name: name of persistence module known_modules: dictionary of module...
def _get_configured_module(option_name, known_modules=None): from furious.job_utils import path_to_reference config = get_config() option_value = config[option_name] # If no known_modules were give, make it an empty dict. if not known_modules: known_modules = {} module_path = kno...
718,408
Traverse directory trees to find a furious.yaml file Begins with the location of this file then checks the working directory if not found Args: config_file: location of this file, override for testing Returns: the path of furious.yaml or None if not found
def find_furious_yaml(config_file=__file__): checked = set() result = _find_furious_yaml(os.path.dirname(config_file), checked) if not result: result = _find_furious_yaml(os.getcwd(), checked) return result
718,409
Traverse the directory tree identified by start until a directory already in checked is encountered or the path of furious.yaml is found. Checked is present both to make the loop termination easy to reason about and so the same directories do not get rechecked Args: start: the path to ...
def _find_furious_yaml(start, checked): directory = start while directory not in checked: checked.add(directory) for fs_yaml_name in FURIOUS_YAML_NAMES: yaml_path = os.path.join(directory, fs_yaml_name) if os.path.exists(yaml_path): return yaml_path ...
718,410
Creates a segment cost function for a time series with a Normal distribution with changing mean Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, int) -> float where the firs...
def normal_mean(data, variance): if not isinstance(data, np.ndarray): data = np.array(data) i_variance_2 = 1 / (variance ** 2) cmm = [0.0] cmm.extend(np.cumsum(data)) cmm2 = [0.0] cmm2.extend(np.cumsum(np.abs(data))) def cost(start, end): cmm2_diff = cmm2[end...
718,440
Creates a segment cost function for a time series with a Normal distribution with changing variance Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, int) -> float where the ...
def normal_var(data, mean): if not isinstance(data, np.ndarray): data = np.array(data) cumm = [0.0] cumm.extend(np.cumsum(np.power(np.abs(data - mean), 2))) def cost(s, t): dist = float(t - s) diff = cumm[t] - cumm[s] return dist * np.log(diff/dist) r...
718,441
Creates a segment cost function for a time series with a Normal distribution with changing mean and variance Args: data (:obj:`list` of float): 1D time series data Returns: function: Function with signature (int, int) -> float where the first arg is the starting ...
def normal_meanvar(data): data = np.hstack(([0.0], np.array(data))) cumm = np.cumsum(data) cumm_sq = np.cumsum([val**2 for val in data]) def cost(s, t): ts_i = 1.0 / (t-s) mu = (cumm[t] - cumm[s]) * ts_i sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2 sig_i...
718,442
Creates a segment cost function for a time series with a poisson distribution with changing mean Args: data (:obj:`list` of float): 1D time series data Returns: function: Function with signature (int, int) -> float where the first arg is the starting index, and t...
def poisson(data): data = np.hstack(([0.0], np.array(data))) cumm = np.cumsum(data) def cost(s, t): diff = cumm[t]-cumm[s] if diff == 0: return -2 * diff * (- np.log(t-s) - 1) else: return -2 * diff * (np.log(diff) - np.log(t-s) - 1) return...
718,443
Creates a segment cost function for a time series with a exponential distribution with changing mean Args: data (:obj:`list` of float): 1D time series data Returns: function: Function with signature (int, int) -> float where the first arg is the starting index, a...
def exponential(data): data = np.hstack(([0.0], np.array(data))) cumm = np.cumsum(data) def cost(s, t): return -1*(t-s) * (np.log(t-s) - np.log(cumm[t] - cumm[s])) return cost
718,444
Get BEL Specification The json file this depends on is generated by belspec_yaml2json as part of the update_specifications function Args: version: e.g. 2.0.0 where the filename
def get_specification(version: str) -> Mapping[str, Any]: spec_dir = config["bel"]["lang"]["specifications"] spec_dict = {} bel_versions = get_bel_versions() if version not in bel_versions: log.error("Cannot get unknown version BEL specification") return {"error": "unknown version...
721,195
Get belspec files from Github repo Args: spec_dir: directory to store the BEL Specification and derived files force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
def github_belspec_files(spec_dir, force: bool = False): if not force: dtnow = datetime.datetime.utcnow() delta = datetime.timedelta(1) yesterday = dtnow - delta for fn in glob.glob(f"{spec_dir}/bel*yaml"): if datetime.datetime.fromtimestamp(os.path.getmtime(fn)) >...
721,198
Enhance BEL specification and save as JSON file Load all BEL Specification YAML files and convert to JSON files after enhancing them. Also create a bel_versions.json file with all available BEL versions for fast loading. Args: yaml_fn: original YAML version of BEL Spec json_fn: enhanc...
def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str: try: spec_dict = yaml.load(open(yaml_fn, "r").read(), Loader=yaml.SafeLoader) # admin-related keys spec_dict["admin"] = {} spec_dict["admin"]["version_underscored"] = spec_dict["version"].replace(".", "_") spec_...
721,199
Add relation keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added relation keys
def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: # Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances spec_dict["relations"]["list"] = [] spec_dict["relations"]["list_short"] = [] spec_dict["relations"]["list_long"] = [] spe...
721,201
Add function keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added function keys
def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: # Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances spec_dict["functions"]["list"] = [] spec_dict["functions"]["list_long"] = [] spec_dict["functions"]["list_short"] = [] sp...
721,202
Enhance function signatures Add required and optional objects to signatures objects for semantic validation support. Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: return enhanced bel specification dict
def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: for func in spec_dict["functions"]["signatures"]: for i, sig in enumerate(spec_dict["functions"]["signatures"][func]["signatures"]): args = sig["arguments"] req_args = [] pos_args = ...
721,204
Find BEL function or argument at cursor location Args: belstr: BEL String used to create the completion_text ast (Mapping[str, Any]): AST (dict) of BEL String cursor_loc (int): given cursor location from input field cursor_loc starts at 0, think of it like a block cursor coverin...
def cursor( belstr: str, ast: AST, cursor_loc: int, result: Mapping[str, Any] = None ) -> Mapping[str, Any]: log.debug(f"SubAST: {json.dumps(ast, indent=4)}") # Recurse down through subject, object, nested to functions log.debug(f"Cursor keys {ast.keys()}, BELStr: {belstr}") if len(belstr) =...
721,236
Namespace completions Args: completion_text entity_types: used to filter namespace search results bel_spec: used to search default namespaces namespace: used to filter namespace search results species_id: used to filter namespace search results bel_fmt: used to selec...
def nsarg_completions( completion_text: str, entity_types: list, bel_spec: BELSpec, namespace: str, species_id: str, bel_fmt: str, size: int, ): minimal_nsarg_completion_len = 1 species = [species_id] namespaces = [namespace] replace_list = [] if len(completion_te...
721,237
Filter BEL relations by prefix Args: prefix: completion string bel_fmt: short, medium, long BEL formats spec: BEL specification Returns: list: list of BEL relations that match prefix
def relation_completions( completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int ) -> list: if bel_fmt == "short": relation_list = bel_spec["relations"]["list_short"] else: relation_list = bel_spec["relations"]["list_long"] matches = [] for r in relation_list: ...
721,238
Filter BEL functions by prefix Args: prefix: completion string bel_fmt: short, medium, long BEL formats spec: BEL specification Returns: list: list of BEL functions that match prefix
def function_completions( completion_text: str, bel_spec: BELSpec, function_list: list, bel_fmt: str, size: int, ) -> list: # Convert provided function list to correct bel_fmt if isinstance(function_list, list): if bel_fmt in ["short", "medium"]: function_list = [ ...
721,239
Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop of belstr to replace completion_text: text to use for completion - used for creating highlight Returns: [{ ...
def add_completions( replace_list: list, belstr: str, replace_span: Span, completion_text: str ) -> List[Mapping[str, Any]]: completions = [] for r in replace_list: # if '(' not in belstr: # replacement = f'{r["replacement"]}()' # cursor_loc = len(replacement) - 1 # ...
721,241
Get BEL Assertion completions Args: Results:
def get_completions( belstr: str, cursor_loc: int, bel_spec: BELSpec, bel_comp: str, bel_fmt: str, species_id: str, size: int, ): ast, errors = pparse.get_ast_dict(belstr) spans = pparse.collect_spans(ast) completion_text = "" completions = [] function_help = [] ...
721,242
Scan BEL string to map parens, quotes, commas Args: bels: bel string as an array of characters errors: list of error tuples ('<type>', '<msg>') Returns: (char_locs, errors): character locations and errors
def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors]: pstack, qstack, nested_pstack = [], [], [] parens, nested_parens, quotes, commas = {}, {}, {}, {} notquoted_flag = True for i, c in enumerate(bels): prior_char = i - 1 # print('BEL', prior_char, b[prior_char])...
721,247
Parse functions from BEL using paren, comma, quote character locations Args: bels: BEL string as list of chars char_locs: paren, comma, quote character locations errors: Any error messages generated during the parse Returns: (functions, errors): function names and locations and...
def parse_functions( bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: parens = char_locs["parens"] # Handle partial top-level function name if not parens: bels_len = len(bels) - 1 span = (0, bels_len) parsed[span] = { "...
721,248
Parse arguments from functions Args: bels: BEL string as list of chars char_locs: char locations for parens, commas and quotes parsed: function locations errors: error messages Returns: (functions, errors): function and arg locations plus error messages
def parse_args( bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: commas = char_locs["commas"] # Process each span key in parsed from beginning for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: ...
721,249
Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]: func_pattern = re.compile(r"\s*[a-zA-Z]+\(") nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$") for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: continue ...
721,250
Parse relations from BEL string Args: belstr: BEL string as one single string (not list of chars) char_locs: paren, comma and quote char locations parsed: data structure for parsed functions, relations, nested errors: error messages Returns: (parsed, errors):
def parse_relations( belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: quotes = char_locs["quotes"] quoted_range = set([i for start, end in quotes.items() for i in range(start, end)]) for match in relations_pattern_middle.finditer(belstr): (start,...
721,251
Collect flattened list of spans of BEL syntax types Provide simple list of BEL syntax type spans for highlighting. Function names, NSargs, NS prefix, NS value and StrArgs will be tagged. Args: ast: AST of BEL assertion Returns: List[Tuple[str, Tuple[int, int]]]: list of span objec...
def collect_spans(ast: AST) -> List[Tuple[str, Tuple[int, int]]]: spans = [] if ast.get("subject", False): spans.extend(collect_spans(ast["subject"])) if ast.get("object", False): spans.extend(collect_spans(ast["object"])) if ast.get("nested", False): spans.extend(collec...
721,254
Check full parse for errors Args: parsed: errors: component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors: # Error check fn_cnt = 0 rel_cnt = 0 nested_cnt = 0 for key in parsed: if parsed[key]["type"] == "Function": fn_cnt += 1 if parsed[key]["type"] == "Relation": rel_cnt += 1 ...
721,257
Convert parsed data struct to AST dictionary Args: parsed: errors: component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input
def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = ""): ast = {} sorted_keys = sorted(parsed.keys()) # Setup top-level tree for key in sorted_keys: if parsed[key]["type"] == "Nested": nested_component_stack = ["subject", "object"] if component_type: ...
721,258
Convert BEL string to AST dictionary Args: belstr: BEL string component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input
def get_ast_dict(belstr, component_type: str = ""): errors = [] parsed = {} bels = list(belstr) char_locs, errors = parse_chars(bels, errors) parsed, errors = parse_functions(belstr, char_locs, parsed, errors) parsed, errors = parse_args(bels, char_locs, parsed, errors) parsed, errors ...
721,259
Convert dict AST to object AST Function Args: ast_fn: AST object Function d: AST as dictionary spec: BEL Specification Return: ast_fn
def add_ast_fn(d, spec, parent_function=None): if d["type"] == "Function": ast_fn = Function(d["function"]["name"], spec, parent_function=parent_function) for arg in d["args"]: if arg["type"] == "Function": ast_fn.add_argument(add_ast_fn(arg, spec, parent_function=a...
721,261
[De]Canonicalize NSArg Args: nsarg (str): bel statement string or partial string (e.g. subject or object) api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1 namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example canonicalize (bool): u...
def convert_nsarg( nsarg: str, api_url: str = None, namespace_targets: Mapping[str, List[str]] = None, canonicalize: bool = False, decanonicalize: bool = False, ) -> str: if not api_url: api_url = config["bel_api"]["servers"]["api_url"] if not api_url: log.error...
721,263
Recursively convert namespaces of BEL Entities in BEL AST using API endpoint Canonicalization and decanonicalization is determined by endpoint used and namespace_targets. Args: ast (BEL): BEL AST api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicali...
def convert_namespaces_ast( ast, api_url: str = None, namespace_targets: Mapping[str, List[str]] = None, canonicalize: bool = False, decanonicalize: bool = False, ): if isinstance(ast, NSArg): given_term_id = "{}:{}".format(ast.namespace, ast.value) # Get normalized term i...
721,265
Recursively populate NSArg AST entries for default (de)canonical values This was added specifically for the BEL Pipeline. It is designed to run directly against ArangoDB and not through the BELAPI. Args: ast (BEL): BEL AST Returns: BEL: BEL AST
def populate_ast_nsarg_defaults(ast, belast, species_id=None): if isinstance(ast, NSArg): given_term_id = "{}:{}".format(ast.namespace, ast.value) r = bel.terms.terms.get_normalized_terms(given_term_id) ast.canonical = r["canonical"] ast.decanonical = r["decanonical"] ...
721,266
Recursively orthologize BEL Entities in BEL AST using API endpoint NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog) Args: ast (BEL): BEL AST endpoint (str): endpoint url with a placeholder for the term_id Returns: BEL: BEL A...
def orthologize(ast, bo, species_id: str): # if species_id == 'TAX:9606' and str(ast) == 'MGI:Sult2a1': # import pdb; pdb.set_trace() if not species_id: bo.validation_messages.append( ("WARNING", "No species id was provided for orthologization") ) return ast ...
721,267
Recursively collect NSArg orthologs for BEL AST This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available Args: ast: AST at recursive point in belobj species: dictionary of species ids vs labels for or
def populate_ast_nsarg_orthologs(ast, species): ortholog_namespace = "EG" if isinstance(ast, NSArg): if re.match(ortholog_namespace, ast.canonical): orthologs = bel.terms.orthologs.get_orthologs( ast.canonical, list(species.keys()) ) for species...
721,268