Snakemake / snakemake / __init__.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# -*- coding: utf-8 -*-

import os
import subprocess
import glob
import argparse
from argparse import ArgumentError
import logging
import multiprocessing
import re
import sys
import inspect
from functools import partial


from snakemake.workflow import Workflow
from snakemake.exceptions import print_exception
from snakemake.logging import logger, init_logger

__author__ = "Johannes Köster"
__version__ = "2.4.9"


def snakemake(snakefile,
    listrules=False,
    cores=1,
    nodes=1,
    resources=None,
    workdir=None,
    targets=None,
    dryrun=False,
    touch=False,
    forcetargets=False,
    forceall=False,
    forcerun=None,
    prioritytargets=None,
    stats=None,
    printreason=False,
    printshellcmds=False,
    printdag=False,
    printrulegraph=False,
    nocolor=False,
    quiet=False,
    keepgoing=False,
    cluster=None,
    jobname="snakejob.{rulename}.{jobid}.sh",
    immediate_submit=False,
    standalone=False,
    ignore_ambiguity=False,
    snakemakepath=None,
    lock=True,
    unlock=False,
    cleanup_metadata=None,
    force_incomplete=False,
    ignore_incomplete=False,
    list_version_changes=False,
    list_code_changes=False,
    list_input_changes=False,
    list_params_changes=False,
    summary=False,
    output_wait=3,
    print_compilation=False,
    debug=False,
    notemp=False,
    nodeps=False,
    jobscript=None,
    timestamp=False):
    """
    Run snakemake on a given snakefile.
    Note: at the moment, this function is not thread-safe!

    Arguments
    snakefile         -- the snakefile.
    list              -- list rules.
    jobs              -- maximum number of parallel jobs (default: 1).
    directory         -- working directory (default: current directory).
    rule              -- execute this rule (default: first rule in snakefile).
    dryrun            -- print the rules that would be executed,
        but do not execute them.
    forcethis         -- force the selected rule to be executed
    forceall          -- force all rules to be executed
    time_measurements -- measure the running times of all rules
    lock              -- lock the working directory
    """

    init_logger(nocolor=nocolor, stdout=dryrun, debug=debug, timestamp=timestamp)

    if not os.path.exists(snakefile):
        logger.error("Error: Snakefile \"{}\" not present.".format(snakefile))
        return False

    if workdir:
        olddir = os.getcwd()
    workflow = Workflow(
        snakefile=snakefile, snakemakepath=snakemakepath,
        jobscript=jobscript)

    if standalone:
        try:
            # set the process group
            os.setpgrp()
        except:
            # ignore: if it does not work we can still work without it
            pass

    success = True
    try:
        workflow.include(snakefile, workdir=workdir,
            overwrite_first_rule=True, print_compilation=print_compilation)
        workflow.check()

        if not print_compilation:
            if listrules:
                workflow.list_rules()
            else:
                    #if not printdag and not printrulegraph:
                    # handle subworkflows
                    subsnakemake = partial(
                        snakemake,
                        cores=cores,
                        nodes=nodes,
                        resources=resources,
                        dryrun=dryrun,
                        touch=touch,
                        printreason=printreason,
                        printshellcmds=printshellcmds,
                        nocolor=nocolor,
                        quiet=quiet,
                        keepgoing=keepgoing,
                        cluster=cluster,
                        jobname=jobname,
                        immediate_submit=immediate_submit,
                        standalone=standalone,
                        ignore_ambiguity=ignore_ambiguity,
                        snakemakepath=snakemakepath,
                        lock=lock,
                        unlock=unlock,
                        cleanup_metadata=cleanup_metadata,
                        force_incomplete=force_incomplete,
                        ignore_incomplete=ignore_incomplete,
                        output_wait=output_wait,
                        debug=debug,
                        notemp=notemp,
                        nodeps=nodeps,
                        jobscript=jobscript,
                        timestamp=timestamp)
                    success = workflow.execute(
                        targets=targets, dryrun=dryrun, touch=touch,
                        cores=cores, nodes=nodes, forcetargets=forcetargets,
                        forceall=forceall, forcerun=forcerun,
                        prioritytargets=prioritytargets, quiet=quiet,
                        keepgoing=keepgoing, printshellcmds=printshellcmds,
                        printreason=printreason, printrulegraph=printrulegraph,
                        printdag=printdag, cluster=cluster, jobname=jobname,
                        immediate_submit=immediate_submit,
                        ignore_ambiguity=ignore_ambiguity,
                        workdir=workdir, stats=stats,
                        force_incomplete=force_incomplete,
                        ignore_incomplete=ignore_incomplete,
                        list_version_changes=list_version_changes,
                        list_code_changes=list_code_changes,
                        list_input_changes=list_input_changes,
                        list_params_changes=list_params_changes,
                        summary=summary,
                        output_wait=output_wait,
                        nolock=not lock,
                        unlock=unlock,
                        resources=resources,
                        notemp=notemp,
                        nodeps=nodeps,
                        cleanup_metadata=cleanup_metadata,
                        subsnakemake=subsnakemake
                        )

    except (Exception, BaseException) as ex:
        print_exception(ex, workflow.linemaps)
        success = False
    if workdir:
        os.chdir(olddir)
    if workflow.persistence:
        workflow.persistence.unlock()
    return success


def parse_resources(args):
    resources = dict()
    if args.resources is not None:
        valid = re.compile("[a-zA-Z_]\w*$")
        for res in args.resources:
            try:
                res, val = res.split("=")
            except ValueError:
                raise ValueError("Resources have to be defined as name=value pairs.")
            if not valid.match(res):
                raise ValueError("Resource definition must start with a valid identifier.")
            try:
                val = int(val)
            except ValueError:
                raise ValueError("Resource definiton must contain an integer after the identifier.")
            if res == "_cores":
                raise ValueError("Resource _cores is already defined internally. Use a different name.")
            resources[res] = val
    return resources


def get_argument_parser():
    parser = argparse.ArgumentParser(
        description="Snakemake is a Python based language and execution "
            "environment for GNU Make-like workflows.")

    parser.add_argument(
        "target", nargs="*", default=None,
        help="Targets to build. May be rules or files.")
    parser.add_argument(
        "--snakefile", "-s", metavar="FILE",
        default="Snakefile", help="The workflow definition in a snakefile.")
    parser.add_argument(
        "--cores", "--jobs", "-j", action="store", default=1,
        const=multiprocessing.cpu_count(), nargs="?", metavar="N", type=int,
        help=(
            "Use at most N cores in parallel (default: 1). "
            "If N is omitted, the limit is set to the number of "
            "available cores."))
    parser.add_argument(
        "--resources", "--res", nargs="*", metavar="NAME=INT",
        help=(
            "Define additional resources that shall constrain the scheduling "
            "analogously to threads (see above). A resource is defined as "
            "a name and an integer value. E.g. --resources gpu=1. Rules can "
            "use resources by defining the resource keyword, e.g. "
            "resources: gpu=1. If now two rules require 1 of the resource "
            "'gpu' they won't be run in parallel by the scheduler."))
    parser.add_argument(
        "--list", "-l", action="store_true",
        help="Show availiable rules in given snakefile.")
    parser.add_argument(
        "--directory", "-d", metavar="DIR", action="store",
        help=(
            "Specify working directory (relative paths in "
            "the snakefile will use this as their origin)."))
    parser.add_argument(
        "--dryrun", "-n", action="store_true",
        help="Do not execute anything.")
    parser.add_argument(
        "--printshellcmds", "-p", action="store_true",
        help="Print out the shell commands that will be executed.")
    parser.add_argument(
        "--dag", action="store_true",
        help="Do not execute anything and print the directed "
            "acyclic graph of jobs in the dot language. Recommended "
            "use on Unix systems: snakemake --dag | dot | display")
    parser.add_argument(
        "--rulegraph", action="store_true",
        help="Do not execute anything and print the dependency graph "
            "of rules in the dot language. This will be less "
            "crowded than above DAG of jobs, but also show less information. "
            "Note that each rule is displayed once, hence the displayed graph will be "
            "cyclic if a rule appears in several steps of the workflow. "
            "Use this if above option leads to a DAG that is too large. "
            "Recommended use on Unix systems: snakemake --ruledag | dot | display")
    parser.add_argument(
        "--summary", "-S", action="store_true",
        help="Print a summary of all files created by the workflow. The "
        "has the following columns: filename, modification time, "
        "rule version, status, plan.\n"
        "Thereby rule version contains the version"
        "the file was created with (see the version keyword of rules), and "
        "status denotes whether the file is missing, its input files are "
        "newer or if version or implementation of the rule changed since "
        "file creation. Finally the last column denotes whether the file "
        "will be updated or created during the next workflow execution.")
    parser.add_argument(
        "--touch", "-t", action="store_true",
        help=(
            "Touch output files (mark them up to date without really "
            "changing them) instead of running their commands. This is "
            "used to pretend that the rules were executed, in order to "
            "fool future invocations of snakemake. Fails if a file does "
            "not yet exist."))
    parser.add_argument(
        "--keep-going", "-k", action="store_true",
        help="Go on with independent jobs if a job fails.")
    parser.add_argument(
        "--force", "-f", action="store_true",
        help=(
            "Force the execution of the selected target or the first rule "
            "regardless of already created output."))
    parser.add_argument(
        "--forceall", "-F", action="store_true",
        help=(
            "Force the execution of the selected (or the first) rule and "
            "all rules it is dependent on regardless of already created "
            "output."))
    parser.add_argument(
        "--forcerun", "-R", nargs="+", metavar="TARGET",
        help=(
            "Force the re-execution or creation of the given rules or files."
            " Use this option if you changed a rule and want to have all its "
            "output in your workflow updated."))
    parser.add_argument(
        "--prioritize", "-P", nargs="+", metavar="TARGET",
        help=
            ("Tell the scheduler to assign creation of given targets "
            "(and all their dependencies) highest priority. (EXPERIMENTAL)"))
    parser.add_argument(
        "--allow-ambiguity", "-a", action="store_true",
        help=(
            "Don't check for ambiguous rules and simply use the first if "
            "several can produce the same file. This allows the user to "
            "prioritize rules by their order in the snakefile."))
    # TODO extend below description to explain the wildcards that can be used
    parser.add_argument(
        "--cluster", "-c", metavar="CMD",
        help=(
            "Execute snakemake rules with the given submit command, "
            "e.g. qsub. Snakemake compiles jobs into scripts that are "
            "submitted to the cluster with the given command, once all input "
            "files for a particular job are present (also see the argument below).\n"
            "The submit command can be decorated to make it aware of certain job properties (input, output, params, wildcards, log, threads and dependencies (see the argument below)), e.g.:\n"
            "$ snakemake --cluster 'qsub -pe threaded {threads}'."))
    parser.add_argument(
        "--immediate-submit", "--is", action="store_true",
        help=(
            "Immediately submit all jobs to the cluster instead of waiting "
            "for present input files. This will fail, unless you make "
            "the cluster aware of job dependencies, e.g. via:\n"
            "$ snakemake --cluster 'sbatch --dependency {dependencies}.\n"
            "Assuming that your submit script (here sbatch) outputs the generated job id to the first stdout line, {dependencies} will be filled with space separated job ids this job depends on."))
    parser.add_argument(
        "--jobscript", "--js", metavar="SCRIPT",
        help="Provide a custom job script for submission to the cluster. "
            "The default script resides as 'jobscript.sh' in the "
            "installation directory.")
    parser.add_argument(
        "--jobname", "--jn", default="snakejob.{rulename}.{jobid}.sh", metavar="NAME",
        help="Provide a custom name for the jobscript that is submitted to the cluster (see --cluster)."
        "NAME is \"snakejob.{rulename}.{jobid}.sh\" per default. The wildcards {rulename} and {jobid} have to be present in the name.")
    parser.add_argument(
        "--reason", "-r", action = "store_true",
        help="Print the reason for each executed rule.")
    parser.add_argument(
        "--stats", metavar="FILE",
        help="Write stats about Snakefile execution to the given file.")
    parser.add_argument(
        "--nocolor", action = "store_true",
        help="Do not use a colored output.")
    parser.add_argument(
        "--quiet", "-q", action = "store_true",
        help="Do not output any progress or rule information.")
    parser.add_argument(
        "--nolock", action="store_true",
        help="Do not lock the working directory")
    parser.add_argument(
        "--unlock", action="store_true",
        help="Remove a lock on the working directory.")
    parser.add_argument(
        "--cleanup-metadata", "--cm", nargs="*", metavar="FILE",
        help="Cleanup the metadata "
        "of given files. That means that snakemake removes any tracked "
        "version info, and any marks that files are incomplete.")
    parser.add_argument(
        "--rerun-incomplete", "--ri", action="store_true", help="Re-run all "
        "jobs the output of which is recognized as incomplete.")
    parser.add_argument(
        "--ignore-incomplete", "--ii", action="store_true", help="Ignore "
        "any incomplete jobs.")
    parser.add_argument(
        "--list-version-changes", "--lv", action="store_true",
        help="List all output files that have been created with "
        "a different version (as determined by the version keyword).")
    parser.add_argument(
        "--list-code-changes", "--lc", action="store_true",
        help="List all output files for which the rule body (run or shell) have changed "
        "in the Snakefile.")
    parser.add_argument(
        "--list-input-changes", "--li", action="store_true",
        help="List all output files for which the defined input files have changed "
        "in the Snakefile (e.g. new input files were added in the rule definition or files were renamed). For listing input file modification in the filesystem, use --summary.")
    parser.add_argument(
        "--list-params-changes", "--lp", action="store_true",
        help="List all output files for which the defined params have changed "
        "in the Snakefile.")
    parser.add_argument(
        "--output-wait", "-w", type=int, default=3, metavar="SECONDS",
        help="Wait given seconds if an output file of a job is not present after "
        "the job finished. This helps if your filesystem "
        "suffers from latency.")
    parser.add_argument(
        "--notemp", "--nt", action="store_true",
        help="Ignore temp() declarations. This is useful when running only "
        "a part of the workflow, since temp() would lead to deletion of "
        "probably needed files by other parts of the workflow."
        )
    parser.add_argument(
        '--timestamp', '-T', action='store_true',
        help='Add a timestamp to all logging output')
    parser.add_argument(
        "--print-compilation", action="store_true",
        help="Print the python representation of the workflow.")
    parser.add_argument(
        "--debug", action="store_true", help="Print debugging output.")
    parser.add_argument(
            "--bash-completion", action="store_true", help="Output code to register bash completion for snakemake. Put the following in your .bashrc (including the accents): `snakemake --bash-completion`")
    parser.add_argument(
        "--version", "-v", action="version", version=__version__)
    return parser


def main():
    parser = get_argument_parser()
    args = parser.parse_args()
    
    if args.bash_completion:
        print("complete -C snakemake-bash-completion snakemake")
        sys.exit(0)

    snakemakepath = sys.argv[0]

    try:
        resources = parse_resources(args)
    except ValueError as e:
        print(e, file=sys.stderr)
        print("", file=sys.stderr)
        parser.print_help()
        sys.exit(1)

    cores, nodes = args.cores, sys.maxsize
    if args.cluster:
        cores, nodes = nodes, cores

    success = snakemake(
            args.snakefile,
            listrules=args.list,
            cores=cores,
            nodes=nodes,
            resources=resources,
            workdir=args.directory,
            targets=args.target,
            dryrun=args.dryrun,
            printshellcmds=args.printshellcmds,
            printreason=args.reason,
            printdag=args.dag,
            printrulegraph=args.rulegraph,
            touch=args.touch,
            forcetargets=args.force,
            forceall=args.forceall,
            forcerun=args.forcerun,
            prioritytargets=args.prioritize,
            stats=args.stats,
            nocolor=args.nocolor,
            quiet=args.quiet,
            keepgoing=args.keep_going,
            cluster=args.cluster,
            jobname=args.jobname,
            immediate_submit=args.immediate_submit,
            standalone=True,
            ignore_ambiguity=args.allow_ambiguity,
            snakemakepath=snakemakepath,
            lock=not args.nolock,
            unlock=args.unlock,
            cleanup_metadata=args.cleanup_metadata,
            force_incomplete=args.rerun_incomplete,
            ignore_incomplete=args.ignore_incomplete,
            list_version_changes=args.list_version_changes,
            list_code_changes=args.list_code_changes,
            list_input_changes=args.list_input_changes,
            list_params_changes=args.list_params_changes,
            summary=args.summary,
            print_compilation=args.print_compilation,
            debug=args.debug,
            jobscript=args.jobscript,
            notemp=args.notemp,
            timestamp=args.timestamp)
    sys.exit(0 if success else 1)


def bash_completion(snakefile="Snakefile"):
    if not len(sys.argv) >= 2:
        print("Calculate bash completion for snakemake. This tool shall not be invoked by hand.")
        sys.exit(1)

    prefix = sys.argv[2]

    if prefix.startswith("-"):
        opts = [
            action.option_strings[0] for action in get_argument_parser()._actions
            if action.option_strings and action.option_strings[0].startswith(prefix)]
        print(*opts, sep="\n")

    else:
        files = glob.glob("{}*".format(prefix))
        if files:
            print(*files, sep="\n")
        elif os.path.exists(snakefile):
            workflow = Workflow(snakefile=snakefile, snakemakepath=get_snakemake_path())
            workflow.include(snakefile)

            workflow_files = sorted(set(
                file for file in workflow.concrete_files
                if file.startswith(prefix)))
            if workflow_files:
                print(*workflow_files, sep="\n")
            
            rules = [
                rule.name for rule in workflow.rules
                if rule.name.startswith(prefix)]
            if rules:
                print(*rules, sep="\n")
    sys.exit(0)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.