code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def report( text, path, stylesheet=None, defaultenc="utf8", template=None, metadata=None, **files, ): """Create an HTML report using python docutils. This is deprecated in favor of the --report flag. Attention: This function needs Python docutils to be installed for the pyt...
Create an HTML report using python docutils. This is deprecated in favor of the --report flag. Attention: This function needs Python docutils to be installed for the python installation you use with Snakemake. All keywords not listed below are interpreted as paths to files that shall be embedded ...
report
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def R(code): """Execute R code. This is deprecated in favor of the ``script`` directive. This function executes the R code given as a string. The function requires rpy2 to be installed. Args: code (str): R code to be executed """ try: import rpy2.robjects as robjects ex...
Execute R code. This is deprecated in favor of the ``script`` directive. This function executes the R code given as a string. The function requires rpy2 to be installed. Args: code (str): R code to be executed
R
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def format(_pattern, *args, stepout=1, _quote_all=False, quote_func=None, **kwargs): """Format a pattern in Snakemake style. This means that keywords embedded in braces are replaced by any variable values that are available in the current namespace. """ frame = inspect.currentframe().f_back wh...
Format a pattern in Snakemake style. This means that keywords embedded in braces are replaced by any variable values that are available in the current namespace.
format
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def read_job_properties( jobscript, prefix="# properties", pattern=re.compile("# properties = (.*)") ): """Read the job properties defined in a snakemake jobscript. This function is a helper for writing custom wrappers for the snakemake --cluster functionality. Applying this function to a jobscript...
Read the job properties defined in a snakemake jobscript. This function is a helper for writing custom wrappers for the snakemake --cluster functionality. Applying this function to a jobscript will return a dict containing information about the job.
read_job_properties
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def min_version(version): """Require minimum snakemake version, raise workflow error if not met.""" from packaging.version import parse from snakemake.common import __version__ if parse(__version__) < parse(version): raise WorkflowError( "Expecting Snakemake version {} or higher (yo...
Require minimum snakemake version, raise workflow error if not met.
min_version
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def update_config(config, overwrite_config): """Recursively update dictionary config with overwrite_config in-place. See https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth for details. Args: config (dict): dictionary to update overwrite_con...
Recursively update dictionary config with overwrite_config in-place. See https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth for details. Args: config (dict): dictionary to update overwrite_config (dict): dictionary whose items will overwrite th...
update_config
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def _update_config(config, overwrite_config): """Necessary as recursive calls require a return value, but `update_config()` has no return value. """ for key, value in overwrite_config.items(): if not isinstance(config, collections.abc.Mapping): # the config ca...
Necessary as recursive calls require a return value, but `update_config()` has no return value.
_update_config
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def available_cpu_count(): """ Return the number of available virtual or physical CPUs on this system. The number of available CPUs can be smaller than the total number of CPUs when the cpuset(7) mechanism is in use, as is the case on some cluster systems. Adapted from https://stackoverflow.com...
Return the number of available virtual or physical CPUs on this system. The number of available CPUs can be smaller than the total number of CPUs when the cpuset(7) mechanism is in use, as is the case on some cluster systems. Adapted from https://stackoverflow.com/a/1006301/715090
available_cpu_count
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def argvquote(arg, force=True): """Returns an argument quoted in such a way that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with a list of arguments. Arguments in a command line should be separated by spaces; this function...
Returns an argument quoted in such a way that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with a list of arguments. Arguments in a command line should be separated by spaces; this function does not add these spaces. This implem...
argvquote
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def cmd_exe_quote(arg): """Quotes an argument in a cmd.exe compliant way.""" arg = argvquote(arg) cmd_exe_metachars = '^()%!"<>&|' for char in cmd_exe_metachars: arg.replace(char, "^" + char) return arg
Quotes an argument in a cmd.exe compliant way.
cmd_exe_quote
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def find_bash_on_windows(): """ Find the path to a usable bash on windows. The first attempt is to look for a bash installed with a git conda package. Alternatively, try bash installed with 'Git for Windows'. """ if not ON_WINDOWS: return None # First look for bash in git's conda pac...
Find the path to a usable bash on windows. The first attempt is to look for a bash installed with a git conda package. Alternatively, try bash installed with 'Git for Windows'.
find_bash_on_windows
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def wildcard_pattern(self): """Wildcard pattern over all columns of the underlying dataframe of the form column1~{column1}/column2~{column2}/*** or of the provided custom pattern. """ if self.single_wildcard: return f"{{{self.single_wildcard}}}" else: retu...
Wildcard pattern over all columns of the underlying dataframe of the form column1~{column1}/column2~{column2}/*** or of the provided custom pattern.
wildcard_pattern
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def instance_patterns(self): """Iterator over all instances of the parameter space (dataframe rows), formatted as file patterns of the form column1~{value1}/column2~{value2}/... or of the provided custom pattern. """ import pandas as pd fmt_value = lambda value: "NA" if ...
Iterator over all instances of the parameter space (dataframe rows), formatted as file patterns of the form column1~{value1}/column2~{value2}/... or of the provided custom pattern.
instance_patterns
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def instance(self, wildcards): """Obtain instance (dataframe row) with the given wildcard values.""" import pandas as pd from snakemake.io import regex_from_filepattern def convert_value_dtype(name, value): if self.dataframe.dtypes[name] == bool and value == "False": ...
Obtain instance (dataframe row) with the given wildcard values.
instance
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def cleanup_source_archive(self): """cleanup source archive form remote storage""" if self._source_archive is not None: obj = self.storage_registry.default_storage_provider.object( self._source_archive.query ) async_run(obj.managed_remove())
cleanup source archive form remote storage
cleanup_source_archive
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def get_rule(self, name): """ Get rule by name. Arguments name -- the name of the rule """ if not self._rules: raise NoRulesException() if name not in self._rules: raise UnknownRuleException(name) return self._rules[name]
Get rule by name. Arguments name -- the name of the rule
get_rule
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def inputfile(self, path): """Mark file as being an input file of the workflow. This also means that eventual --default-remote-provider/prefix settings will be applied to this file. The file is returned as _IOFile object, such that it can e.g. be transparently opened with _IOFile.open()...
Mark file as being an input file of the workflow. This also means that eventual --default-remote-provider/prefix settings will be applied to this file. The file is returned as _IOFile object, such that it can e.g. be transparently opened with _IOFile.open().
inputfile
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def generate_unit_tests(self, path: Path): """Generate unit tests for the workflow. Arguments path -- Path to the directory where the unit tests shall be generated. """ from snakemake import unit_tests assert self.dag_settings is not None self._prepare_dag( ...
Generate unit tests for the workflow. Arguments path -- Path to the directory where the unit tests shall be generated.
generate_unit_tests
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def export_cwl(self, path: Path): """Export the workflow as CWL document. Arguments path -- the path to the CWL document to be created. """ assert self.dag_settings is not None self._prepare_dag( forceall=self.dag_settings.forceall, ignore_incompl...
Export the workflow as CWL document. Arguments path -- the path to the CWL document to be created.
export_cwl
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def source_path(self, rel_path): """Return path to source file from work dir derived from given path relative to snakefile""" # TODO download to disk (use source cache) in case of remote file import inspect frame = inspect.currentframe() assert frame is not None and frame.f_back...
Return path to source file from work dir derived from given path relative to snakefile
source_path
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def register_envvars(self, *envvars): """ Register environment variables that shall be passed to jobs. If used multiple times, union is taken. """ invalid_envvars = [ envvar for envvar in envvars if re.match(r"^\w+$", envvar, flags=re.ASCII) is...
Register environment variables that shall be passed to jobs. If used multiple times, union is taken.
register_envvars
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def configfile(self, fp): """Update the global config with data from the given file.""" from snakemake.common.configfile import load_configfile if not self.modifier.skip_configfile: if os.path.exists(fp): self.configfiles.append(fp) c = load_configfil...
Update the global config with data from the given file.
configfile
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def report(self, path): """Define a global report description in .rst format.""" if not self.modifier.skip_global_report_caption: self.report_text = self.current_basedir.join(path)
Define a global report description in .rst format.
report
python
snakemake/snakemake
src/snakemake/workflow.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/workflow.py
MIT
def wrapper( path, input, output, params, wildcards, threads, resources, log, config, rulename, conda_env, conda_base_path, container_img, singularity_args, env_modules, bench_record, prefix, jobid, bench_iteration, cleanup_scripts, sha...
Load a wrapper from https://github.com/snakemake/snakemake-wrappers under the given path + wrapper.(py|R|Rmd) and execute it.
wrapper
python
snakemake/snakemake
src/snakemake/wrapper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/wrapper.py
MIT
def _get_provenance_hash(self, job: Job, cache_mode: str): """ Recursively calculate hash for the output of the given job and all upstream jobs in a blockchain fashion. This is based on an idea of Sven Nahnsen. Fails if job has more than one output file. The reason is that there...
Recursively calculate hash for the output of the given job and all upstream jobs in a blockchain fashion. This is based on an idea of Sven Nahnsen. Fails if job has more than one output file. The reason is that there is no way to generate a per-output file hash without generati...
_get_provenance_hash
python
snakemake/snakemake
src/snakemake/caching/hash.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/caching/hash.py
MIT
async def store(self, job: Job, cache_mode: str): """ Store generated job output in the cache. """ if not os.access(self.path, os.W_OK): raise WorkflowError( "Cannot access cache location {}. Please ensure that " "it is present and writeable."...
Store generated job output in the cache.
store
python
snakemake/snakemake
src/snakemake/caching/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/caching/local.py
MIT
async def fetch(self, job: Job, cache_mode: str): """ Retrieve cached output file and symlink to the place where the job expects it's output. """ for outputfile, cachefile in self.get_outputfiles_and_cachefiles( job, cache_mode ): if not cachefile.exists()...
Retrieve cached output file and symlink to the place where the job expects it's output.
fetch
python
snakemake/snakemake
src/snakemake/caching/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/caching/local.py
MIT
async def exists(self, job: Job, cache_mode: str): """ Return True if job is already cached """ for outputfile, cachefile in self.get_outputfiles_and_cachefiles( job, cache_mode ): if not cachefile.exists(): return False logger...
Return True if job is already cached
exists
python
snakemake/snakemake
src/snakemake/caching/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/caching/local.py
MIT
def _load_configfile(configpath_or_obj, filetype="Config"): "Tries to load a configfile first as JSON, then as YAML, into a dict." import yaml if isinstance(configpath_or_obj, str) or isinstance(configpath_or_obj, Path): obj = open(configpath_or_obj, encoding="utf-8") else: obj = config...
Tries to load a configfile first as JSON, then as YAML, into a dict.
_load_configfile
python
snakemake/snakemake
src/snakemake/common/configfile.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/configfile.py
MIT
def load_configfile(configpath): "Loads a JSON or YAML configfile as a dict, then checks that it's a dict." config = _load_configfile(configpath) if not isinstance(config, dict): raise WorkflowError( "Config file must be given as JSON or YAML with keys at top level." ) return...
Loads a JSON or YAML configfile as a dict, then checks that it's a dict.
load_configfile
python
snakemake/snakemake
src/snakemake/common/configfile.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/configfile.py
MIT
def get_git_root(path): """ Args: path: (str) Path a to a directory/file that is located inside the repo Returns: path to the root folder for git repo """ import git try: git_repo = git.Repo(path, search_parent_directories=True) return git_repo.git.rev_parse("--s...
Args: path: (str) Path a to a directory/file that is located inside the repo Returns: path to the root folder for git repo
get_git_root
python
snakemake/snakemake
src/snakemake/common/git.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/git.py
MIT
def get_git_root_parent_directory(path, input_path): """ This function will recursively go through parent directories until a git repository is found or until no parent directories are left, in which case an error will be raised. This is needed when providing a path to a file/folder that is located ...
This function will recursively go through parent directories until a git repository is found or until no parent directories are left, in which case an error will be raised. This is needed when providing a path to a file/folder that is located on a branch/tag not currently checked out. Args: ...
get_git_root_parent_directory
python
snakemake/snakemake
src/snakemake/common/git.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/git.py
MIT
def git_content(git_file): """ This function will extract a file from a git repository, one located on the filesystem. The expected format is git+file:///path/to/your/repo/path_to_file@version Args: env_file (str): consist of path to repo, @, version, and file information ...
This function will extract a file from a git repository, one located on the filesystem. The expected format is git+file:///path/to/your/repo/path_to_file@version Args: env_file (str): consist of path to repo, @, version, and file information Ex: git+file:///home/smeds/snake...
git_content
python
snakemake/snakemake
src/snakemake/common/git.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/git.py
MIT
def match_iter(self, query: str) -> Generator[V, None, None]: """Yields all entries which are prefixes of the given key. E.g. if "abc" is the key then "abc", "ab", "a", and "" are considered valid prefixes. Yields entries as (key, value) tuples as supplied to __init__() """ ...
Yields all entries which are prefixes of the given key. E.g. if "abc" is the key then "abc", "ab", "a", and "" are considered valid prefixes. Yields entries as (key, value) tuples as supplied to __init__()
match_iter
python
snakemake/snakemake
src/snakemake/common/prefix_lookup.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/prefix_lookup.py
MIT
def _common_prefix(self, s1: str, s2: str) -> str: """Utility function that gives the common prefix of two strings. Except, if the strings are identical, returns the string minus one letter. Behaviour is undefined if either string is empty. """ for i, (l1, l2) in enumerate(zip(s...
Utility function that gives the common prefix of two strings. Except, if the strings are identical, returns the string minus one letter. Behaviour is undefined if either string is empty.
_common_prefix
python
snakemake/snakemake
src/snakemake/common/prefix_lookup.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/prefix_lookup.py
MIT
def async_run(coroutine): """Attaches to running event loop or creates a new one to execute a coroutine. .. seealso:: https://github.com/snakemake/snakemake/issues/1105 https://stackoverflow.com/a/65696398 """ try: return asyncio.run(coroutine) except RuntimeError as e:...
Attaches to running event loop or creates a new one to execute a coroutine. .. seealso:: https://github.com/snakemake/snakemake/issues/1105 https://stackoverflow.com/a/65696398
async_run
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def num_if_possible(s): """Convert string to number if possible, otherwise return string.""" try: return int(s) except ValueError: try: return float(s) except ValueError: return s
Convert string to number if possible, otherwise return string.
num_if_possible
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def get_file_hash(filename, algorithm="sha256"): """find the SHA256 hash string of a file. We use this so that the user can choose to cache working directories in storage. """ from snakemake.logging import logger # The algorithm must be available try: hasher = hashlib.new(algorithm) ...
find the SHA256 hash string of a file. We use this so that the user can choose to cache working directories in storage.
get_file_hash
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes. bytes to mb: bytesto(bytes, 'm') bytes to gb: bytesto(bytes, 'g' etc. From https://gist.github.com/shawnbutts/3906915 """ levels = {"k": 1, "m": 2, "g": 3, "t": 4, "p": 5, "e": 6} answer = float(bytes) for _ in range(leve...
convert bytes to megabytes. bytes to mb: bytesto(bytes, 'm') bytes to gb: bytesto(bytes, 'g' etc. From https://gist.github.com/shawnbutts/3906915
bytesto
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def group_into_chunks(n, iterable): """Group iterable into chunks of size at most n. See https://stackoverflow.com/a/8998040. """ it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
Group iterable into chunks of size at most n. See https://stackoverflow.com/a/8998040.
group_into_chunks
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def unique_justseen(iterable, key=None): """ List unique elements, preserving order. Remember only the element just seen. From https://docs.python.org/3/library/itertools.html#itertools-recipes """ # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBcCAD', str.lower) --> ...
List unique elements, preserving order. Remember only the element just seen. From https://docs.python.org/3/library/itertools.html#itertools-recipes
unique_justseen
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def set_env(**environ): """ Temporarily set the process environment variables. >>> with set_env(PLUGINS_DIR='test/plugins'): ... "PLUGINS_DIR" in os.environ True >>> "PLUGINS_DIR" in os.environ False :type environ: Dict[str, unicode] :param environ: Environment variables to set ...
Temporarily set the process environment variables. >>> with set_env(PLUGINS_DIR='test/plugins'): ... "PLUGINS_DIR" in os.environ True >>> "PLUGINS_DIR" in os.environ False :type environ: Dict[str, unicode] :param environ: Environment variables to set
set_env
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def copy_permission_safe(src: str, dst: str): """Copy a file to a given destination. If destination exists, it is removed first in order to avoid permission issues when the destination permissions are tried to be applied to an already existing destination. """ if os.path.exists(dst): os...
Copy a file to a given destination. If destination exists, it is removed first in order to avoid permission issues when the destination permissions are tried to be applied to an already existing destination.
copy_permission_safe
python
snakemake/snakemake
src/snakemake/common/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/common/__init__.py
MIT
def address(self): """Path to directory of the conda environment. First tries full hash, if it does not exist, (8-prefix) is used as default. """ if self.name: return self.name elif self.dir: return self.dir else: env_dir = se...
Path to directory of the conda environment. First tries full hash, if it does not exist, (8-prefix) is used as default.
address
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def archive_file(self): """Path to archive of the conda environment, which may or may not exist.""" if self._archive_file is None: self._archive_file = os.path.join(self._env_archive_dir, self.content_hash) return self._archive_file
Path to archive of the conda environment, which may or may not exist.
archive_file
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def create_archive(self): """Create self-contained archive of environment.""" from snakemake.shell import shell # importing requests locally because it interferes with instantiating conda environments import requests self.check_is_file_based() env_archive = self.archiv...
Create self-contained archive of environment.
create_archive
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def execute_deployment_script(self, env_file, deploy_file): """Execute post-deployment script if present""" from snakemake.shell import shell if ON_WINDOWS: raise WorkflowError( "Post deploy script {} provided for conda env {} but unsupported on windows.".format( ...
Execute post-deployment script if present
execute_deployment_script
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def shellcmd_win(self, env_address, cmd): """Prepend the windows activate bat script.""" # get path to activate script activate = os.path.join(self.bin_path(), "activate.bat").replace("\\", "/") env_address = env_address.replace("\\", "/") return f'"{activate}" "{env_address}"&&...
Prepend the windows activate bat script.
shellcmd_win
python
snakemake/snakemake
src/snakemake/deployment/conda.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/conda.py
MIT
def shellcmd(self, cmd): """Return shell command with given modules loaded.""" return "module purge && module load {to_load}; {cmd}".format( to_load=" ".join(self.names), cmd=cmd )
Return shell command with given modules loaded.
shellcmd
python
snakemake/snakemake
src/snakemake/deployment/env_modules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/env_modules.py
MIT
def shellcmd( img_path, cmd, args="", quiet=False, envvars=None, shell_executable=None, container_workdir=None, is_python_script=False, ): """Execute shell command inside singularity container given optional args and environment variables to be passed.""" if envvars: ...
Execute shell command inside singularity container given optional args and environment variables to be passed.
shellcmd
python
snakemake/snakemake
src/snakemake/deployment/singularity.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/deployment/singularity.py
MIT
def save_files(bucket_name, source_path, destination_path): """given a directory path, save all files recursively to storage""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) # destination path should be stripped of path indicators too bucket_name = bucket_name.st...
given a directory path, save all files recursively to storage
save_files
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def get_source_files(source_path): """Given a directory, return a listing of files to upload""" filenames = [] if not os.path.exists(source_path): print("%s does not exist!" % source_path) sys.exit(0) for x in os.walk(source_path): for name in glob(os.path.join(x[0], "*")): ...
Given a directory, return a listing of files to upload
get_source_files
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def add_ending_slash(filename): """Since we want to replace based on having an ending slash, ensure it's there""" if not filename.endswith("/"): filename = "%s/" % filename return filename
Since we want to replace based on having an ending slash, ensure it's there
add_ending_slash
python
snakemake/snakemake
src/snakemake/executors/google_lifesciences_helper.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/google_lifesciences_helper.py
MIT
def run_group_job(self, job: GroupJobExecutorInterface): """Run a pipe or service group job. This lets all items run simultaneously.""" # we only have to consider pipe or service groups because in local running mode, # these are the only groups that will occur service_futures =...
Run a pipe or service group job. This lets all items run simultaneously.
run_group_job
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def cached_or_run(self, job: SingleJobExecutorInterface, run_func, *args): """ Either retrieve result from cache, or run job with given function. """ cache_mode = self.workflow.get_cache_mode(job.rule) try: if cache_mode: async_run(self.workflow.output...
Either retrieve result from cache, or run job with given function.
cached_or_run
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def run_wrapper( job_rule, input, output, params, wildcards, threads, resources, log, benchmark, benchmark_repeats, benchmark_extended, conda_env, container_img, singularity_args, env_modules, use_singularity, linemaps, debug, cleanup_scripts, ...
Wrapper around the run method that handles exceptions and benchmarking. Arguments job_rule -- the ``job.rule`` member input -- a list of input files output -- a list of output files wildcards -- so far processed wildcards threads -- usable threads log -- a list of...
run_wrapper
python
snakemake/snakemake
src/snakemake/executors/local.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/local.py
MIT
def change_working_directory(directory=None): """Change working directory in execution context if provided.""" if directory: try: saved_directory = os.getcwd() logger.info(f"Changing to shadow directory: {directory}") os.chdir(directory) yield fina...
Change working directory in execution context if provided.
change_working_directory
python
snakemake/snakemake
src/snakemake/executors/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/executors/__init__.py
MIT
def _simple_copy(self): """Identical copy except dictionary keys are downcast to str.""" simplified = type(self)(self.max_wait_time) # Copy non-dictionary attributes the same. for name in ["remaining_wait_time", "active"]: old_attr = getattr(self, name) setattr(s...
Identical copy except dictionary keys are downcast to str.
_simple_copy
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def inventory(self): """Starting from the given file, try to cache as much existence and modification date information of this and other files as possible. """ assert self.rule is not None cache: IOCache = self.rule.workflow.iocache if cache.active: task...
Starting from the given file, try to cache as much existence and modification date information of this and other files as possible.
inventory
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def get_inventory_parent(self): """If eligible for inventory, get the parent of a given path. This code does not work on local Windows paths, but inventory is disabled on Windows. """ if self.is_storage: return self.storage_object.get_inventory_parent() else:...
If eligible for inventory, get the parent of a given path. This code does not work on local Windows paths, but inventory is disabled on Windows.
get_inventory_parent
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None): """Open this file. This can (and should) be used in a `with`-statement. If the file is a remote storage file, retrieve it first if necessary. """ if not os.path.exists(self): raise Inpu...
Open this file. This can (and should) be used in a `with`-statement. If the file is a remote storage file, retrieve it first if necessary.
open
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def protected(self): """Returns True if the file is protected. Always False for symlinks.""" # symlinks are never regarded as protected return ( await self.exists_local() and not os.access(self.file, os.W_OK) and not os.path.islink(self.file) )
Returns True if the file is protected. Always False for symlinks.
protected
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def mtime_uncached(self, skip_storage: bool = False): """Obtain mtime. Usually, this will be one stat call only. For symlinks and directories it will be two, for symlinked directories it will be three, for storage files it will additionally query the storage location. ...
Obtain mtime. Usually, this will be one stat call only. For symlinks and directories it will be two, for symlinked directories it will be three, for storage files it will additionally query the storage location.
mtime_uncached
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def check_broken_symlink(self): """Raise WorkflowError if file is a broken symlink.""" if not await self.exists_local(): try: if os.lstat(self.file): raise WorkflowError( f"File {self.file} seems to be a broken symlink." ...
Raise WorkflowError if file is a broken symlink.
check_broken_symlink
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def is_newer(self, time): """Returns true of the file (which is an input file) is newer than time, or if it is a symlink that points to a file newer than time.""" if self.is_ancient: return False return (await self.mtime()).local_or_storage(follow_symlinks=True) > time
Returns true of the file (which is an input file) is newer than time, or if it is a symlink that points to a file newer than time.
is_newer
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def touch(self, times=None): """times must be 2-tuple: (atime, mtime)""" try: if self.is_directory: file = os.path.join(self.file, ".snakemake_timestamp") # Create the flag file if it doesn't exist if not os.path.exists(file): ...
times must be 2-tuple: (atime, mtime)
touch
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
async def wait_for_files( files, latency_wait=3, wait_for_local=False, ignore_pipe_or_service=False, consider_local: Set[_IOFile] = _CONSIDER_LOCAL_DEFAULT, ): """Wait for given files to be present in the filesystem.""" from snakemake.io.fmt import fmt_iofile files = list(files) a...
Wait for given files to be present in the filesystem.
wait_for_files
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def directory(value): """ A flag to specify that output is a directory, rather than a file or named pipe. """ if is_flagged(value, "pipe"): raise SyntaxError("Pipe and directory flags are mutually exclusive.") if is_flagged(value, "storage_object"): raise SyntaxError("Storage and dir...
A flag to specify that output is a directory, rather than a file or named pipe.
directory
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def temp(value, group_jobs=False): """ A flag for an input or output file that shall be removed after usage. When set to true, the extra flag "group_jobs" causes the file to also be flagged as "nodelocal": A flag for an intermediate file that only lives on the compute node executing the group jobs and ...
A flag for an input or output file that shall be removed after usage. When set to true, the extra flag "group_jobs" causes the file to also be flagged as "nodelocal": A flag for an intermediate file that only lives on the compute node executing the group jobs and not accessible from the main snakemake job...
temp
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def protected(value): """A flag for a file that shall be write-protected after creation.""" if is_flagged(value, "temp"): raise SyntaxError("Protected and temporary flags are mutually exclusive.") if is_flagged(value, "storage_object"): raise SyntaxError("Storage and protected flags are mutu...
A flag for a file that shall be write-protected after creation.
protected
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def report( value, caption=None, category=None, subcategory=None, labels=None, patterns=[], htmlindex=None, ): """Flag output file or directory as to be included into reports. In the case of a directory, files to include can be specified via a glob pattern (default: *). Argumen...
Flag output file or directory as to be included into reports. In the case of a directory, files to include can be specified via a glob pattern (default: *). Arguments value -- File or directory. caption -- Path to a .rst file with a textual description of the result. category -- Name of the (optio...
report
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def local(value): """Mark a file as a local file. This disables the application of a default storage provider. """ if is_flagged(value, "storage_object"): raise SyntaxError("Storage and local flags are mutually exclusive.") return flag(value, "local")
Mark a file as a local file. This disables the application of a default storage provider.
local
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def expand(*args, **wildcard_values): """ Expand wildcards in given filepatterns. Arguments *args -- first arg: filepatterns as list or one single filepattern, second arg (optional): a function to combine wildcard values (itertools.product per default) **wildcard_values -- the wildc...
Expand wildcards in given filepatterns. Arguments *args -- first arg: filepatterns as list or one single filepattern, second arg (optional): a function to combine wildcard values (itertools.product per default) **wildcard_values -- the wildcards as keyword arguments with their ...
expand
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def multiext(prefix, *extensions, **named_extensions): """Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).""" if any( (r"/" in ext or r"\\" in ext) for ext in chain(extensions, named_extensions.values()) ): raise WorkflowError( r"Extensio...
Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).
multiext
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def glob_wildcards(pattern, files=None, followlinks=False): """ Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard. """ if is_flagged(pattern, "storage_object"): if files is not None: rai...
Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard.
glob_wildcards
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def update_wildcard_constraints( pattern, wildcard_constraints: Dict[str, str], global_wildcard_constraints: Dict[str, str], ): """Update wildcard constraints Args: pattern (str): pattern on which to update constraints wildcard_constraints (dict): dictionary of wildcard:constraint key-v...
Update wildcard constraints Args: pattern (str): pattern on which to update constraints wildcard_constraints (dict): dictionary of wildcard:constraint key-value pairs global_wildcard_constraints (dict): dictionary of wildcard:constraint key-value pairs
update_wildcard_constraints
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def strip_wildcard_constraints(pattern): """Return a string that does not contain any wildcard constraints.""" if is_callable(pattern): # do not apply on e.g. input functions return pattern def strip_constraint(match): return "{{{}}}".format(match.group("name")) return WILDCARD...
Return a string that does not contain any wildcard constraints.
strip_wildcard_constraints
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __call__(self, *args, **kwargs): """ Generic function that throws an `AttributeError`. Used as replacement for functions such as `index()` and `sort()`, which may be overridden by workflows, to signal to a user that these functions should not be used. """ rai...
Generic function that throws an `AttributeError`. Used as replacement for functions such as `index()` and `sort()`, which may be overridden by workflows, to signal to a user that these functions should not be used.
__call__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __init__( self, toclone=None, fromdict=None, plainstr=False, strip_constraints=False, custom_map=None, ): """ Create the object. Arguments toclone -- another Namedlist that shall be cloned fromdict -- a dict that shall be ...
Create the object. Arguments toclone -- another Namedlist that shall be cloned fromdict -- a dict that shall be converted to a Namedlist (keys become names)
__init__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _set_name(self, name, index, end=None): """ Set the name of an item. Arguments name -- a name index -- the item index """ if name not in self._allowed_overrides and hasattr(self.__class__, name): raise AttributeError( "invalid nam...
Set the name of an item. Arguments name -- a name index -- the item index
_set_name
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _get_names(self): """ Get the defined names as (name, index) pairs. """ for name, index in self._names.items(): yield name, index
Get the defined names as (name, index) pairs.
_get_names
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def _take_names(self, names): """ Take over the given names. Arguments names -- the given names as (name, index) pairs """ for name, (i, j) in names: self._set_name(name, i, end=j)
Take over the given names. Arguments names -- the given names as (name, index) pairs
_take_names
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def __init__(self, min_repeat=20, max_repeat=100): """ Args: max_repeat (int): The maximum length of the periodic substring. min_repeat (int): The minimum length of the periodic substring. """ self.min_repeat = min_repeat self.regex = re.compile( ...
Args: max_repeat (int): The maximum length of the periodic substring. min_repeat (int): The minimum length of the periodic substring.
__init__
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def is_periodic(self, value): """Returns the periodic substring or None if not periodic.""" # short-circuit: need at least min_repeat characters if len(value) < self.min_repeat: return None # short-circuit: need at least min_repeat same characters last_letter = value...
Returns the periodic substring or None if not periodic.
is_periodic
python
snakemake/snakemake
src/snakemake/io/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/io/__init__.py
MIT
def branch( condition: Union[Callable, bool], then: Optional[Union[str, list[str], Callable]] = None, otherwise: Optional[Union[str, list[str], Callable]] = None, cases: Optional[Mapping] = None, ): """Branch based on a condition that is provided as a function pointer (i.e. a Callable) or a valu...
Branch based on a condition that is provided as a function pointer (i.e. a Callable) or a value. If then and optionally otherwise are specified, do the following: If the condition is (or evaluates to) True, return the value of the then parameter. Otherwise, return the value of the otherwise parameter. ...
branch
python
snakemake/snakemake
src/snakemake/ioutils/branch.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/branch.py
MIT
def evaluate(expr: str): """Evaluate a python expression while replacing any wildcards given as {wildcardname} with the wildcard value represented as a string.""" def inner(wildcards): formatted = expr.format(**{w: repr(v) for w, v in wildcards.items()}) try: return eval(formatt...
Evaluate a python expression while replacing any wildcards given as {wildcardname} with the wildcard value represented as a string.
evaluate
python
snakemake/snakemake
src/snakemake/ioutils/evaluate.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/evaluate.py
MIT
def exists(path): """Return True if the given file or directory exists. This function considers any storage arguments given to Snakemake. """ func_context = inspect.currentframe().f_back.f_locals func_context_global = inspect.currentframe().f_back.f_globals workflow = func_context.get("workflo...
Return True if the given file or directory exists. This function considers any storage arguments given to Snakemake.
exists
python
snakemake/snakemake
src/snakemake/ioutils/exists.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/exists.py
MIT
def flatten(list_of_lists: List) -> List: """Flatten an irregular list of lists recursively https://stackoverflow.com/a/53778278 :param list_of_lists: A list of lists :return result: A list that has been flattened from a list of lists """ result = list() for i in list_of_lists: if ...
Flatten an irregular list of lists recursively https://stackoverflow.com/a/53778278 :param list_of_lists: A list of lists :return result: A list that has been flattened from a list of lists
flatten
python
snakemake/snakemake
src/snakemake/ioutils/input.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/input.py
MIT
def lookup( dpath: Optional[str] = None, query: Optional[str] = None, cols: Optional[Union[List[str], str]] = None, is_nrows: Optional[int] = None, within=None, default=NODEFAULT, **namespace, ): """Lookup values in a pandas dataframe, series, or python mapping (e.g. dict). Required...
Lookup values in a pandas dataframe, series, or python mapping (e.g. dict). Required argument ``within`` should be a pandas dataframe or series (in which case use ``query``, and optionally ``cols`` and ``is_nrows``), or a Python mapping like a dict (in which case use the ``dpath`` argument is used). I...
lookup
python
snakemake/snakemake
src/snakemake/ioutils/lookup.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/lookup.py
MIT
def rule_item_factory(name: str): """Allows to access input, output etc. from statements inside a rule but outside of run/shell etc. blocks. Returns an object that defers evaluation to the DAG phase. """ if name == "threads": def inner(_wildcards, threads): return threads ...
Allows to access input, output etc. from statements inside a rule but outside of run/shell etc. blocks. Returns an object that defers evaluation to the DAG phase.
rule_item_factory
python
snakemake/snakemake
src/snakemake/ioutils/rule_items_proxy.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/rule_items_proxy.py
MIT
def subpath( path_or_func: Union[Callable, str, Path], strip_suffix: Optional[str] = None, basename: bool = False, parent: bool = False, ancestor: Optional[int] = None, ): """Return the subpath of a given path. Args: path_or_func: A string, pathlib.Path, or a function returning a st...
Return the subpath of a given path. Args: path_or_func: A string, pathlib.Path, or a function returning a string or pathlib.Path. strip_suffix: If given, strip the suffix from the path. basename: If True, return the basename of the path (cannot be used together with parent or ancestor). ...
subpath
python
snakemake/snakemake
src/snakemake/ioutils/subpath.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ioutils/subpath.py
MIT
def data_uri_from_file(file, defaultenc="utf8"): """Craft a base64 data URI from file with proper encoding and mimetype.""" if isinstance(file, Path): file = str(file) mime, encoding = mime_from_file(file) if encoding is None: encoding = defaultenc with open(file, "rb") as f: ...
Craft a base64 data URI from file with proper encoding and mimetype.
data_uri_from_file
python
snakemake/snakemake
src/snakemake/report/common.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/report/common.py
MIT
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options["uri"] = data_uri_from_file(reference) return result
Image.run() handles most of the
run
python
snakemake/snakemake
src/snakemake/report/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/report/__init__.py
MIT
def log_fmt_shell( self, stdout: bool = True, stderr: bool = True, append: bool = False ) -> str: """ Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers to support optional `log` files specified in the calling rule. If ...
Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers to support optional `log` files specified in the calling rule. If no `log` was specified, then an empty string "" is returned, regardless of the values of `stdout`, `stder...
log_fmt_shell
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def _log_shell_redirect( log: Optional[PathLike], stdout: bool = True, stderr: bool = True, append: bool = False, ) -> str: """ Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers support optional `log` files specified in the calling...
Return a shell redirection string to be used in `shell()` calls This function allows scripts and wrappers support optional `log` files specified in the calling rule. If no `log` was specified, then an empty string "" is returned, regardless of the values of `stdout`, `stderr`, and `append`. ...
_log_shell_redirect
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_list(cls, l): """Encode as vector if the type is homogeneous, otherwise use a list.""" is_homogeneous = False if len(l) == 0: # An empty list is always homogeneous is_homogeneous = True else: # Numbers of different type can be stored in the ...
Encode as vector if the type is homogeneous, otherwise use a list.
encode_list
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def __init__( self, namedlists: List[str] = None, dicts: List[str] = None, prefix: str = "snakemake", ): """namedlists is a list of strings indicating the snakemake object's member variables which are encoded as Namedlist. dicts is a list of strings indicating...
namedlists is a list of strings indicating the snakemake object's member variables which are encoded as Namedlist. dicts is a list of strings indicating the snakemake object's member variables that are encoded as dictionaries. Prefix is the prefix for the bash variable name(s) e.g., snak...
__init__
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_snakemake(self, smk: Snakemake) -> str: """Turn a snakemake object into a collection of bash associative arrays""" arrays = [] main_aa = dict() for var in vars(smk): val = getattr(smk, var) suffix = "params" if var == "_params_store" else var.strip("_")...
Turn a snakemake object into a collection of bash associative arrays
encode_snakemake
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def dict_to_aa(d: dict) -> str: """Converts a dictionary to a Bash associative array This produces the array component of the variable. e.g. ( [var1]=val1 [var2]=val2 ) to make it a correct bash associative array, you need to name it with name=<output of this method> """ ...
Converts a dictionary to a Bash associative array This produces the array component of the variable. e.g. ( [var1]=val1 [var2]=val2 ) to make it a correct bash associative array, you need to name it with name=<output of this method>
dict_to_aa
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT
def encode_namedlist(cls, named_list: io_.Namedlist) -> str: """Convert a namedlist into a Bash associative array See the comments for dict_to_aa() """ nl_dict = dict() # Add the same items keyed by name and also by index for i, (name, val) in enumerate(named_list._allit...
Convert a namedlist into a Bash associative array See the comments for dict_to_aa()
encode_namedlist
python
snakemake/snakemake
src/snakemake/script/__init__.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/script/__init__.py
MIT