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 cwl( path, basedir, input, output, params, wildcards, threads, resources, log, config, rulename, use_singularity, bench_record, jobid, sourcecache_path, runtime_sourcecache_path, ): """ Load cwl from the given basedir + path and execute it. ...
Load cwl from the given basedir + path and execute it.
cwl
python
snakemake/snakemake
src/snakemake/cwl.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cwl.py
MIT
def job_to_cwl(job, dag, outputs, inputs): """Convert a job with its dependencies to a CWL workflow step.""" for f in job.output: if os.path.isabs(f): raise WorkflowError( "All output files have to be relative to the working directory." ) get_output_id = lamb...
Convert a job with its dependencies to a CWL workflow step.
job_to_cwl
python
snakemake/snakemake
src/snakemake/cwl.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cwl.py
MIT
def dag_to_cwl(dag): """Convert a given DAG to a CWL workflow, which is returned as a JSON object.""" snakemake_cwl = { "class": "CommandLineTool", "id": "#snakemake-job", "label": "Snakemake job executor", "hints": [{"dockerPull": get_container_image(), "class": "DockerRequireme...
Convert a given DAG to a CWL workflow, which is returned as a JSON object.
dag_to_cwl
python
snakemake/snakemake
src/snakemake/cwl.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/cwl.py
MIT
def check_directory_outputs(self): """Check that no output file is contained in a directory output of the same or another rule.""" outputs = sorted( {(os.path.abspath(f), job) for job in self.jobs for f in job.output} ) for i in range(len(outputs) - 1): (a, job_a)...
Check that no output file is contained in a directory output of the same or another rule.
check_directory_outputs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def sanitize_local_storage_copies(self): """Remove local copies of storage files that will be recreated in this run.""" async with asyncio.TaskGroup() as tg: for job in self.needrun_jobs(): if not self.finished(job): for f in job.output: ...
Remove local copies of storage files that will be recreated in this run.
sanitize_local_storage_copies
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def check_incomplete(self): """Check if any output files are incomplete. This is done by looking up markers in the persistence module.""" if not self.ignore_incomplete: incomplete_files = await self.incomplete_files() if any(incomplete_files): if sel...
Check if any output files are incomplete. This is done by looking up markers in the persistence module.
check_incomplete
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def incomplete_external_jobid(self, job) -> Optional[str]: """Return the external jobid of the job if it is marked as incomplete. Returns None, if job is not incomplete, or if no external jobid has been registered or if force_incomplete is True. """ if self.workflow.dag_settings...
Return the external jobid of the job if it is marked as incomplete. Returns None, if job is not incomplete, or if no external jobid has been registered or if force_incomplete is True.
incomplete_external_jobid
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def needrun_jobs(self, exclude_finished=True): """Jobs that need to be executed.""" if exclude_finished: return filterfalse(self.finished, self._needrun) else: return iter(self._needrun)
Jobs that need to be executed.
needrun_jobs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def newversion_files(self): """Return list of files where the current version is newer than the recorded version. """ return list( chain( *( job.output for job in filter(self.workflow.persistence.newversion, self.jobs) ...
Return list of files where the current version is newer than the recorded version.
newversion_files
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def check_and_touch_output( self, job: Job, wait: int = 3, ignore_missing_output: Union[List[_IOFile], bool] = False, no_touch: bool = False, wait_for_local: bool = True, check_output_mtime: bool = True, ): """Raise exception if output files of j...
Raise exception if output files of job are missing.
check_and_touch_output
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def correctly_flagged_with_dir(f): """Check that files flagged as directories are in fact directories In ambiguous cases, such as when f is managed by a storage backend, or f doesn't exist and ignore_missing_output is true, always return True """ ...
Check that files flagged as directories are in fact directories In ambiguous cases, such as when f is managed by a storage backend, or f doesn't exist and ignore_missing_output is true, always return True
correctly_flagged_with_dir
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def unshadow_output(self, job, only_log=False, keep_shadow_dir=False): """Move files from shadow directory to real output paths.""" """If shadow directory is kept, returns the path of it.""" if not job.shadow_dir or not job.output: return files = job.log if only_log else cha...
Move files from shadow directory to real output paths.
unshadow_output
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def check_periodic_wildcards(self, job): """Raise an exception if a wildcard of the given job appears to be periodic, indicating a cyclic dependency.""" for wildcard, value in job.wildcards_dict.items(): periodic_substring = self.periodic_wildcard_detector.is_periodic(value) ...
Raise an exception if a wildcard of the given job appears to be periodic, indicating a cyclic dependency.
check_periodic_wildcards
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def handle_protected(self, job): """Write-protect output files that are marked with protected().""" for f in job.output: if f in job.protected_output: logger.info(f"Write-protecting output file {fmt_iofile(f)}.") f.protect()
Write-protect output files that are marked with protected().
handle_protected
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def handle_touch(self, job): """Touches those output files that are marked for touching.""" for f in job.output: if f in job.touch_output: f = job.shadowed_path(f) logger.info(f"Touching output file {fmt_iofile(f)}.") f.touch_or_create() ...
Touches those output files that are marked for touching.
handle_touch
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def temp_size(self, job): """Return the total size of temporary input files of the job. If none, return 0. """ return sum([await f.size() for f in self.temp_input(job)])
Return the total size of temporary input files of the job. If none, return 0.
temp_size
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def handle_temp(self, job): """Remove temp files if they are no longer needed. Update temp_mtimes.""" if self.workflow.storage_settings.notemp: return if job.is_group(): for j in job: await self.handle_temp(j) return is_temp = l...
Remove temp files if they are no longer needed. Update temp_mtimes.
handle_temp
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def handle_storage(self, job, store_in_storage=True, store_only_log=False): """Remove local files if they are no longer needed and upload.""" if store_in_storage and ( self.workflow.remote_exec or self.workflow.is_main_process ): # handle output files fi...
Remove local files if they are no longer needed and upload.
handle_storage
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def jobid(self, job): """Return job id of given job.""" if job.is_group(): return job.jobid else: return self._jobid[job]
Return job id of given job.
jobid
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def update( self, jobs, file=None, visited=None, known_producers=None, progress=False, create_inventory=False, ): """Update the DAG by adding given jobs and their dependencies.""" if visited is None: visited = set() if...
Update the DAG by adding given jobs and their dependencies.
update
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def update_( self, job, visited=None, known_producers=None, progress=False, create_inventory=False, ): """Update the DAG by adding the given job and its dependencies.""" if job in self._dependencies: return if visited is None:...
Update the DAG by adding the given job and its dependencies.
update_
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def update_needrun(self, create_inventory=False): """Update the information whether a job needs to be executed.""" if create_inventory and self.workflow.is_main_process: # Concurrently collect mtimes of all existing files. await self.workflow.iocache.mtime_inventory(self.j...
Update the information whether a job needs to be executed.
update_needrun
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def _check_groups(self): """Check whether all groups are valid.""" # find paths of jobs that leave a group and then enter it again # this is not allowed since then the group depends on itself def dfs(job, group, visited, outside_jobs, outside_jobs_all, skip_this): """Inner f...
Check whether all groups are valid.
_check_groups
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def update_incomplete_input_expand_jobs(self): """Update (re-evaluate) all jobs which have incomplete input file expansions. only filled in the second pass of postprocessing. """ updated = False for job in list(self.jobs): if job.incomplete_input_expand: ...
Update (re-evaluate) all jobs which have incomplete input file expansions. only filled in the second pass of postprocessing.
update_incomplete_input_expand_jobs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def update_ready(self, jobs=None): """Update information whether a job is ready to execute. Given jobs must be needrun jobs! """ if jobs is None: jobs = self.needrun_jobs() potential_new_ready_jobs = False candidate_groups = set() for job in jobs: ...
Update information whether a job is ready to execute. Given jobs must be needrun jobs!
update_ready
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def postprocess( self, update_needrun=True, update_incomplete_input_expand_jobs=True, check_initial=False, ): """Postprocess the DAG. This has to be invoked after any change to the DAG topology.""" self.cleanup() self.update_jobids() if u...
Postprocess the DAG. This has to be invoked after any change to the DAG topology.
postprocess
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def handle_pipes_and_services(self): """Use pipes and services to determine job groups. Check if every pipe has exactly one consumer""" visited = set() for job in self.needrun_jobs(): candidate_groups = set() user_groups = set() if job.pipe_group is n...
Use pipes and services to determine job groups. Check if every pipe has exactly one consumer
handle_pipes_and_services
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def _ready(self, job): """Return whether the given job is ready to execute.""" group = self._group.get(job, None) if group is None: return self._n_until_ready[job] == 0 else: n_internal_deps = lambda job: sum( self._group.get(dep) == group for dep...
Return whether the given job is ready to execute.
_ready
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def finish(self, job, update_checkpoint_dependencies=True): """Finish a given job (e.g. remove from ready jobs, mark depending jobs as ready).""" self._running.remove(job) # turn off this job's Reason if job.is_group(): for j in job: self.reaso...
Finish a given job (e.g. remove from ready jobs, mark depending jobs as ready).
finish
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def new_job( self, rule, targetfile=None, format_wildcards=None, wildcards_dict=None ): """Create new job for given rule and (optional) targetfile. This will reuse existing jobs with the same wildcards.""" product = rule.get_some_product() if targetfile is None and wild...
Create new job for given rule and (optional) targetfile. This will reuse existing jobs with the same wildcards.
new_job
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def replace_job(self, job, newjob, recursive=True): """Replace given job with new job.""" add_to_targetjobs = job in self.targetjobs try: jobid = self.jobid(job) except KeyError: # Job has been added while updating another checkpoint, # jobid is ...
Replace given job with new job.
replace_job
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def collect_potential_dependencies(self, job, known_producers): """Collect all potential dependencies of a job. These might contain ambiguities. The keys of the returned dict represent the files to be considered. """ # use a set to circumvent multiple jobs for the same file ...
Collect all potential dependencies of a job. These might contain ambiguities. The keys of the returned dict represent the files to be considered.
collect_potential_dependencies
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def bfs(self, direction, *jobs, stop=lambda job: False): """Perform a breadth-first traversal of the DAG.""" queue = deque(jobs) visited = set(queue) while queue: job = queue.popleft() if stop(job): # stop criterion reached for this node ...
Perform a breadth-first traversal of the DAG.
bfs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def level_bfs(self, direction, *jobs, stop=lambda job: False): """Perform a breadth-first traversal of the DAG, but also yield the level together with each job.""" queue = [(job, 0) for job in jobs] visited = set(jobs) while queue: job, level = queue.pop(0) ...
Perform a breadth-first traversal of the DAG, but also yield the level together with each job.
level_bfs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def dfs(self, direction, *jobs, stop=lambda job: False, post=True): """Perform depth-first traversal of the DAG.""" visited = set() def _dfs(job): """Inner function for DFS traversal.""" if stop(job): return if not post: yield ...
Perform depth-first traversal of the DAG.
dfs
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def new_wildcards(self, job): """Return wildcards that are newly introduced in this job, compared to its ancestors.""" new_wildcards = set(job.wildcards.items()) for job_ in self._dependencies[job]: if not new_wildcards: return set() for wildcard i...
Return wildcards that are newly introduced in this job, compared to its ancestors.
new_wildcards
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def rule2job(self, targetrule): """Generate a new job from a given rule.""" if targetrule.has_wildcards(): raise WorkflowError( "Target rules may not contain wildcards. " "Please specify concrete files or a rule without wildcards at the command line, " ...
Generate a new job from a given rule.
rule2job
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def hsv_to_htmlhexrgb(h, s, v): """Convert hsv colors to hex-encoded rgb colors usable by html.""" import colorsys hex_r, hex_g, hex_b = (round(255 * x) for x in colorsys.hsv_to_rgb(h, s, v)) return "#{hex_r:0>2X}{hex_g:0>2X}{hex_b:0>2X}".format( hex_r=he...
Convert hsv colors to hex-encoded rgb colors usable by html.
hsv_to_htmlhexrgb
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def resolve_input_functions(input_files): """Iterate over all input files and replace input functions with a fixed string. """ files = [] for f in input_files: if callable(f): files.append("<input function>") ...
Iterate over all input files and replace input functions with a fixed string.
resolve_input_functions
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def html_node(node_id, node, color): """Assemble a html style node for graphviz""" input_files = resolve_input_functions(node._input) output_files = [repr(f).strip("'") for f in node._output] input_header = ( '<b><font point-size="14">&#8618; input</font><...
Assemble a html style node for graphviz
html_node
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def archive(self, path: Path): """Archives workflow such that it can be re-run on a different system. Archiving includes git versioned files (i.e. Snakefiles, config files, ...), ancestral input files and conda environments. """ if path.suffix == ".tar": mode = "x" ...
Archives workflow such that it can be re-run on a different system. Archiving includes git versioned files (i.e. Snakefiles, config files, ...), ancestral input files and conda environments.
archive
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def is_external_input(self, file, job, not_needrun_is_external=False): """Return True if the given file is an external input for the given job.""" consider = lambda job: True if not_needrun_is_external: consider = lambda job: self.needrun(job) return not any( file...
Return True if the given file is an external input for the given job.
is_external_input
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
async def clean(self, only_temp=False, dryrun=False): """Removes files generated by the workflow.""" for job in self.jobs: for f in job.output: if not only_temp or is_flagged(f, "temp"): # The reason for the second check is that dangling ...
Removes files generated by the workflow.
clean
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def list_untracked(self): """List files in the workdir that are not in the dag.""" used_files = set() files_in_cwd = set() for job in self.jobs: used_files.update( os.path.relpath(file) for file in chain(job.local_input, job.local_output, job.l...
List files in the workdir that are not in the dag.
list_untracked
python
snakemake/snakemake
src/snakemake/dag.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/dag.py
MIT
def format_exception_to_string(ex, linemaps=None): """ Returns the error message for a given exception as a string. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile. """ if isinstance(ex,...
Returns the error message for a given exception as a string. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile.
format_exception_to_string
python
snakemake/snakemake
src/snakemake/exceptions.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/exceptions.py
MIT
def print_exception_warning(ex, linemaps=None, footer_message=""): """ Print an error message for a given exception using logger warning. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile. """...
Print an error message for a given exception using logger warning. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile.
print_exception_warning
python
snakemake/snakemake
src/snakemake/exceptions.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/exceptions.py
MIT
def print_exception(ex, linemaps=None): """ Print an error message for a given exception. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile. """ from snakemake.logging import logger l...
Print an error message for a given exception. Arguments ex -- the exception linemaps -- a dict of a dict that maps for each snakefile the compiled lines to source code lines in the snakefile.
print_exception
python
snakemake/snakemake
src/snakemake/exceptions.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/exceptions.py
MIT
def __init__( self, message=None, include=None, lineno=None, snakefile=None, rule=None ): """ Creates a new instance of RuleException. Arguments message -- the exception message include -- iterable of other exceptions to be included lineno -- the line the exc...
Creates a new instance of RuleException. Arguments message -- the exception message include -- iterable of other exceptions to be included lineno -- the line the exception originates snakefile -- the file the exception originates
__init__
python
snakemake/snakemake
src/snakemake/exceptions.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/exceptions.py
MIT
def logfile_suggestion(self, prefix: str) -> str: """Return a suggestion for the log file name given a prefix.""" return ( "/".join( [prefix, self.rule.name] + [ f"{w}_{v}" for w, v in sorted( sel...
Return a suggestion for the log file name given a prefix.
logfile_suggestion
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
async def outputs_older_than_script_or_notebook(self): """return output that's older than script, i.e. script has changed""" path = self.rule.script or self.rule.notebook if not path: return path: SourceFile = self._path_to_source_file(path) if isinstance(path, Loca...
return output that's older than script, i.e. script has changed
outputs_older_than_script_or_notebook
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def _get_resources_to_skip(self): """Return a set of resource names that are callable and depend on input files.""" return { name for name, val in self.rule.resources.items() if is_callable(val) and "input" in get_function_params(val) }
Return a set of resource names that are callable and depend on input files.
_get_resources_to_skip
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def archive_conda_env(self): """Archive a conda environment into a custom local channel.""" if self.conda_env_spec: if self.conda_env.is_externally_managed: raise WorkflowError( "Workflow archives cannot be created for workflows using externally managed co...
Archive a conda environment into a custom local channel.
archive_conda_env
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
async def inputsize(self): """ Return the size of the input files. Input files need to be present. """ if self._inputsize is None: self._inputsize = sum([await f.size() for f in self.input]) return self._inputsize
Return the size of the input files. Input files need to be present.
inputsize
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def message(self): """Return the message for this job.""" try: return ( self.format_wildcards(self.rule.message) if self.rule.message else None ) except AttributeError as ex: raise RuleException(str(ex), rule=self.rule) except KeyError ...
Return the message for this job.
message
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def _path_to_source_file(self, path: Union[str, Path]) -> SourceFile: """Return the path to source file referred by rule, while expanding wildcards and params. """ if isinstance(path, Path): path = str(path) if self.wildcards is not None or self.params is not None: ...
Return the path to source file referred by rule, while expanding wildcards and params.
_path_to_source_file
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def shadowed_path(self, f): """Get the shadowed path of IOFile f.""" if not self.shadow_dir: return f f_ = IOFile(os.path.join(self.shadow_dir, f), self.rule) # The shadowed path does not need the storage object, storage will be handled # after shadowing. f_.c...
Get the shadowed path of IOFile f.
shadowed_path
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
async def remove_existing_output(self): """Clean up output before rules actually run""" for f, f_ in zip(self.output, self.rule.output): if is_flagged(f, "update"): # output files marked as to be updated are not removed continue try: ...
Clean up output before rules actually run
remove_existing_output
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
async def prepare(self): """ Prepare execution of job. This includes creation of directories and deletion of previously created files. Creates a shadow directory for the job if specified. """ await self.check_protected_output() unexpected_output = self.d...
Prepare execution of job. This includes creation of directories and deletion of previously created files. Creates a shadow directory for the job if specified.
prepare
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def format_wildcards(self, string, **variables): """Format a string with variables from the job.""" _variables = dict() _variables.update(self.rule.workflow.globals) _variables.update( dict( input=self.input, output=self.output, ...
Format a string with variables from the job.
format_wildcards
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def format_wildcards(self, string, **variables): """Format a string with variables from the job.""" _variables = dict() _variables.update(self.dag.workflow.globals) _variables.update( dict( input=self.input, output=self.output, ...
Format a string with variables from the job.
format_wildcards
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def expanded_output(self): """Yields the entire expanded output of all jobs""" for job in self.jobs: yield from job.output
Yields the entire expanded output of all jobs
expanded_output
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def is_provenance_triggered(self): """Return True if reason is triggered by provenance information.""" return ( self.params_changed or self.code_changed or self.software_stack_changed or self.input_changed )
Return True if reason is triggered by provenance information.
is_provenance_triggered
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def mark_finished(self): "called if the job has been run" self.finished = True
called if the job has been run
mark_finished
python
snakemake/snakemake
src/snakemake/jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/jobs.py
MIT
def format_percentage(done, total): """Format percentage from given fraction while avoiding superfluous precision.""" if done == total: return "100%" if done == 0: return "0%" precision = 0 fraction = done / total fmt_precision = "{{:.{}%}}".format def fmt(fraction): ...
Format percentage from given fraction while avoiding superfluous precision.
format_percentage
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def get_event_level(record: logging.LogRecord) -> tuple[LogEvent, str]: """ Gets snakemake log level from a log record. If there is no snakemake log level, returns the log record's level name. Args: record (logging.LogRecord) Returns: tuple[LogEvent, str] """ event = record...
Gets snakemake log level from a log record. If there is no snakemake log level, returns the log record's level name. Args: record (logging.LogRecord) Returns: tuple[LogEvent, str]
get_event_level
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def format(self, record): """ Override format method to format Snakemake-specific log messages. """ event, level = get_event_level(record) record_dict = record.__dict__.copy() def default_formatter(rd): return rd["msg"] formatters = { Non...
Override format method to format Snakemake-specific log messages.
format
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def _format_job_info(self, msg): """Helper method to format job info details.""" def format_item(item, omit=None, valueformat=str): value = msg[item] if value != omit: return f" {item}: {valueformat(value)}" output = [ f"{'local' if msg['l...
Helper method to format job info details.
_format_job_info
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def _format_job_error(self, msg): """Helper method to format job error details.""" output = [f"Error in rule {msg['rule_name']}:"] if msg["msg"]: output.append(f" message: {msg['rule_msg']}") output.append(f" jobid: {msg['jobid']}") if msg["input"]: ...
Helper method to format job error details.
_format_job_error
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def _format_group_error(self, msg): """Helper method to format group error details.""" output = [] if msg["msg"]: output.append(f" message: {msg['msg']}") if msg["aux_logs"]: output.append( f" log: {', '.join(msg['aux_logs'])} (check log fil...
Helper method to format group error details.
_format_group_error
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def can_color_tty(self, mode): """ Colors are supported when: 1. Terminal is not "dumb" 2. Running in subprocess mode 3. Using a TTY on non-Windows systems """ from snakemake_interface_executor_plugins.settings import ExecMode # Case 1: Check if terminal ...
Colors are supported when: 1. Terminal is not "dumb" 2. Running in subprocess mode 3. Using a TTY on non-Windows systems
can_color_tty
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def decorate(self, record, message): """ Add color to the log message based on its level. """ message = [message] event, level = get_event_level(record) if not self.nocolor and record.levelname in self.colors: if level == "INFO" and event in self.yellow_info...
Add color to the log message based on its level.
decorate
python
snakemake/snakemake
src/snakemake/logging.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/logging.py
MIT
def notebook( path, basedir, input, output, params, wildcards, threads, resources, log, config, rulename, conda_env, conda_base_path, container_img, singularity_args, env_modules, bench_record, jobid, bench_iteration, cleanup_scripts, s...
Load a script from the given basedir + path and execute it.
notebook
python
snakemake/snakemake
src/snakemake/notebook.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/notebook.py
MIT
def match(self, targetfile: str) -> set[Rule]: """Returns all rules that match the given target file, considering only the prefix and suffix up to the first wildcard. To further verify the match, the returned rules should be checked with ``Rule.is_producer(targetfile)``. """ ret...
Returns all rules that match the given target file, considering only the prefix and suffix up to the first wildcard. To further verify the match, the returned rules should be checked with ``Rule.is_producer(targetfile)``.
match
python
snakemake/snakemake
src/snakemake/output_index.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/output_index.py
MIT
def parse_fstring(self, token: tokenize.TokenInfo): """ only for python >= 3.12, since then python changed the parsing manner of f-string, see [pep-0701](https://peps.python.org/pep-0701) Here, we just read where the f-string start and end from tokens. Luckily, each toke...
only for python >= 3.12, since then python changed the parsing manner of f-string, see [pep-0701](https://peps.python.org/pep-0701) Here, we just read where the f-string start and end from tokens. Luckily, each token records the content of the line, and we can just take...
parse_fstring
python
snakemake/snakemake
src/snakemake/parser.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/parser.py
MIT
def apply_default_storage(self, path): """Apply the defined default remote provider to the given path and return the updated _IOFile. Asserts that default remote provider is defined. """ from snakemake.storage import flag_with_storage_object def is_annotated_callable(value): ...
Apply the defined default remote provider to the given path and return the updated _IOFile. Asserts that default remote provider is defined.
apply_default_storage
python
snakemake/snakemake
src/snakemake/path_modifier.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/path_modifier.py
MIT
def input_checksums(self, job, input_path): """Return all checksums of the given input file recorded for the output of the given job. """ return set( self.metadata(output_path).get("input_checksums", {}).get(input_path) for output_path in job.output )
Return all checksums of the given input file recorded for the output of the given job.
input_checksums
python
snakemake/snakemake
src/snakemake/persistence.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/persistence.py
MIT
def params_changed(self, job, file=None): """Yields output files with changed params or bool if file given.""" files = [file] if file is not None else job.output changes = NO_PARAMS_CHANGE new = set(self._params(job)) for outfile in files: fmt_version = self.record...
Yields output files with changed params or bool if file given.
params_changed
python
snakemake/snakemake
src/snakemake/persistence.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/persistence.py
MIT
def _get_layers(cls, resources, constraints, sortby=None): """Calculate required consecutive job layers. Layers are used to keep resource requirements within given constraint. For instance, if the jobs together require 50 threads, but only 12 are available, we will use 5 layers. If mult...
Calculate required consecutive job layers. Layers are used to keep resource requirements within given constraint. For instance, if the jobs together require 50 threads, but only 12 are available, we will use 5 layers. If multiple constraints are used, all will be considered and met. Any...
_get_layers
python
snakemake/snakemake
src/snakemake/resources.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/resources.py
MIT
def infer_resources(name, value, resources: dict): """Infer resources from a given one, if possible.""" from humanfriendly import parse_size, parse_timespan, InvalidTimespan, InvalidSize if isinstance(value, str): value = value.strip("'\"") if ( (name == "mem" or name == "disk") ...
Infer resources from a given one, if possible.
infer_resources
python
snakemake/snakemake
src/snakemake/resources.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/resources.py
MIT
def apply_modifier( self, modifier, rulename, prefix_replacables={"input", "output", "log", "benchmark"}, ): """Update this ruleinfo with the given one (used for 'use rule' overrides).""" path_modifier = modifier.path_modifier skips = set() if modifie...
Update this ruleinfo with the given one (used for 'use rule' overrides).
apply_modifier
python
snakemake/snakemake
src/snakemake/ruleinfo.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/ruleinfo.py
MIT
def __init__(self, name, workflow, lineno=None, snakefile=None): """ Create a rule Arguments name -- the name of the rule """ self._name = name self.workflow = workflow self.docstring = None self.message = None self._input = InputFiles() ...
Create a rule Arguments name -- the name of the rule
__init__
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def set_input(self, *input, **kwinput): """ Add a list of input files. Recursive lists are flattened. Arguments input -- the list of input files """ consider_ancient = self.workflow.workflow_settings.consider_ancient.get( self.name, frozenset() ) ...
Add a list of input files. Recursive lists are flattened. Arguments input -- the list of input files
set_input
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def set_output(self, *output, **kwoutput): """ Add a list of output files. Recursive lists are flattened. After creating the output files, they are checked for duplicates. Arguments output -- the list of output files """ for item in output: # Named m...
Add a list of output files. Recursive lists are flattened. After creating the output files, they are checked for duplicates. Arguments output -- the list of output files
set_output
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def check_output_duplicates(self): """Check ``Namedlist`` for duplicate entries and raise a ``WorkflowError`` on problems. Does not raise if the entry is empty. """ seen = dict() idx = None for name, value in self.output._allitems(): if name is None: ...
Check ``Namedlist`` for duplicate entries and raise a ``WorkflowError`` on problems. Does not raise if the entry is empty.
check_output_duplicates
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def _set_inoutput_item(self, item, output=False, name=None, mark_ancient=False): """ Set an item to be input or output. Arguments item -- the item inoutput -- a Namedlist of either input or output items name -- an optional name for the item """ i...
Set an item to be input or output. Arguments item -- the item inoutput -- a Namedlist of either input or output items name -- an optional name for the item
_set_inoutput_item
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def handle_incomplete_checkpoint(exception): """If checkpoint is incomplete, target it such that it is completed before this rule gets executed.""" if exception.targetfile in input: return TBDString() else: raise WorkflowError( ...
If checkpoint is incomplete, target it such that it is completed before this rule gets executed.
handle_incomplete_checkpoint
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def is_producer(self, requested_output): """ Returns True if this rule is a producer of the requested output. """ try: for o in self.products(): if o.match(requested_output): return True return False except sre_constants...
Returns True if this rule is a producer of the requested output.
is_producer
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def get_wildcards(self, requested_output, wildcards_dict=None): """ Return wildcard dictionary by 1. trying to format the output with the given wildcards and comparing with the requested output 2. matching regular expression output files to the requested concrete ones. Arguments...
Return wildcard dictionary by 1. trying to format the output with the given wildcards and comparing with the requested output 2. matching regular expression output files to the requested concrete ones. Arguments requested_output -- a concrete filepath
get_wildcards
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def compare(self, rule1, rule2): """ Return whether rule2 has a higher priority than rule1. """ if rule1.name != rule2.name: # try the last clause first, # i.e. clauses added later overwrite those before. for clause in reversed(self.order): ...
Return whether rule2 has a higher priority than rule1.
compare
python
snakemake/snakemake
src/snakemake/rules.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/rules.py
MIT
def remaining_jobs(self): """Return jobs to be scheduled including not yet ready ones.""" return [ job for job in self.workflow.dag.needrun_jobs() if job not in self.running and not self.workflow.dag.finished(job) and job not in self.failed ...
Return jobs to be scheduled including not yet ready ones.
remaining_jobs
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def schedule(self): """Schedule jobs that are ready, maximizing cpu usage.""" try: while True: if self.workflow.dag.queue_input_jobs: self.update_queue_input_jobs() # work around so that the wait does not prevent keyboard interrupts ...
Schedule jobs that are ready, maximizing cpu usage.
schedule
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def _proceed(self, job): """Do stuff after job is finished.""" with self._lock: self._tofinish.append(job) if self.dryrun: if len(self.running) - len(self._tofinish) - len(self._toerror) <= 0: # During dryrun, only release when all running job...
Do stuff after job is finished.
_proceed
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def _handle_error(self, job, postprocess_job: bool = True): """Clear jobs and stop the workflow. If Snakemake is configured to restart jobs then the job might have "restart_times" left and we just decrement and let the scheduler try to run the job again. """ # must be ca...
Clear jobs and stop the workflow. If Snakemake is configured to restart jobs then the job might have "restart_times" left and we just decrement and let the scheduler try to run the job again.
_handle_error
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def job_selector_ilp(self, jobs): """ Job scheduling by optimization of resource usage by solving ILP using pulp """ import pulp from pulp import lpSum if len(jobs) == 1: return self.job_selector_greedy(jobs) with self._lock: if not self....
Job scheduling by optimization of resource usage by solving ILP using pulp
job_selector_ilp
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def job_selector_greedy(self, jobs): """ Using the greedy heuristic from "A Greedy Algorithm for the General Multidimensional Knapsack Problem", Akcay, Li, Xu, Annals of Operations Research, 2012 Args: jobs (list): list of jobs """ logger.debug("Se...
Using the greedy heuristic from "A Greedy Algorithm for the General Multidimensional Knapsack Problem", Akcay, Li, Xu, Annals of Operations Research, 2012 Args: jobs (list): list of jobs
job_selector_greedy
python
snakemake/snakemake
src/snakemake/scheduler.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/scheduler.py
MIT
def general_args( self, executor_common_settings: CommonSettings, ) -> str: """Return a string to add to self.exec_job that includes additional arguments from the command line. This is currently used in the ClusterExecutor and CPUExecutor, as both were using the same ...
Return a string to add to self.exec_job that includes additional arguments from the command line. This is currently used in the ClusterExecutor and CPUExecutor, as both were using the same code. Both have base class of the RealExecutor.
general_args
python
snakemake/snakemake
src/snakemake/spawn_jobs.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/spawn_jobs.py
MIT
def validate(data, schema, set_default=True): """Validate data with JSON schema at given path. Args: data (object): data to validate. Can be a config dict or a pandas data frame. schema (str): Path to JSON schema used for validation. The schema can also be in YAML format. If validat...
Validate data with JSON schema at given path. Args: data (object): data to validate. Can be a config dict or a pandas data frame. schema (str): Path to JSON schema used for validation. The schema can also be in YAML format. If validating a pandas data frame, the schema has to ...
validate
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def simplify_path(path): """Return a simplified version of the given path.""" relpath = os.path.relpath(path) if relpath.startswith("../../"): return path else: return relpath
Return a simplified version of the given path.
simplify_path
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def linecount(filename): """Return the number of lines of the given file. Args: filename (str): the path to the file """ with open(filename) as f: return sum(1 for l in f)
Return the number of lines of the given file. Args: filename (str): the path to the file
linecount
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT
def makedirs(dirnames): """Recursively create the given directory or directories without reporting errors if they are present. """ if isinstance(dirnames, str): dirnames = [dirnames] for dirname in dirnames: os.makedirs(dirname, exist_ok=True)
Recursively create the given directory or directories without reporting errors if they are present.
makedirs
python
snakemake/snakemake
src/snakemake/utils.py
https://github.com/snakemake/snakemake/blob/master/src/snakemake/utils.py
MIT