Source

Snakemake / snakemake / rules.py

Full commit
  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
# -*- coding: utf-8 -*-

import os
import re
import sys
import inspect
import sre_constants
from collections import defaultdict

from snakemake.io import IOFile, _IOFile, protected, temp, dynamic, Namedlist
from snakemake.io import expand, InputFiles, OutputFiles, Wildcards, Params
from snakemake.io import apply_wildcards
from snakemake.exceptions import RuleException, IOFileException, WildcardError

__author__ = "Johannes Köster"


class Rule:
    def __init__(self, *args, lineno=None, snakefile=None):
        """
        Create a rule

        Arguments
        name -- the name of the rule
        """
        if len(args) == 2:
            name, workflow = args
            self.name = name
            self.workflow = workflow
            self.docstring = None
            self.message = None
            self._input = InputFiles()
            self._output = OutputFiles()
            self._params = Params()
            self.dynamic_output = set()
            self.dynamic_input = set()
            self.temp_output = set()
            self.protected_output = set()
            self.resources = dict(_cores=1)
            self.priority = 1
            self.version = None
            self._log = None
            self.wildcard_names = set()
            self.lineno = lineno
            self.snakefile = snakefile
            self.run_func = None
            self.shellcmd = None
        elif len(args) == 1:
            other = args[0]
            self.name = other.name
            self.workflow = other.workflow
            self.docstring = other.docstring
            self.message = other.message
            self._input = other._input
            self._output = other._output
            self._params = other._params
            self.dynamic_output = other.dynamic_output
            self.dynamic_input = other.dynamic_input
            self.temp_output = other.temp_output
            self.protected_output = other.protected_output
            self.resources = other.resources
            self.priority = other.priority
            self.version = other.version
            self._log = other._log
            self.wildcard_names = other.wildcard_names
            self.lineno = other.lineno
            self.snakefile = other.snakefile
            self.run_func = other.run_func
            self.shellcmd = other.shellcmd

    def dynamic_branch(self, wildcards, input=True):
        def get_io(rule):
            return (self.input, self.dynamic_input) if input else (
                self.output, self.dynamic_output)
        io, dynamic_io = get_io(self)
        expansion = defaultdict(list)
        for i, f in enumerate(io):
            if f in dynamic_io:
                try:
                    for e in reversed(expand(f, zip, **wildcards)):
                        expansion[i].append(IOFile(e, rule=self))
                except KeyError:
                    return None
        branch = Rule(self)
        io_, dynamic_io_ = get_io(branch)

        # replace the dynamic files with the expanded files
        for i, e in reversed(list(expansion.items())):
            dynamic_io_.remove(io[i])
            io_.insert_items(i, e)
        if not input:
            branch.wildcard_names.clear()
            non_dynamic_wildcards = dict(
                (name, values[0])
                for name, values in wildcards.items() if len(set(values)) == 1)
            (
            branch._input,
            branch._output,
            branch._params,
            branch._log,
            _) = branch.expand_wildcards(wildcards=non_dynamic_wildcards)
            return branch, non_dynamic_wildcards
        return branch

    def has_wildcards(self):
        """
        Return True if rule contains wildcards.
        """
        return bool(self.wildcard_names)

    @property
    def log(self):
        return self._log

    @log.setter
    def log(self, log):
        self._log = IOFile(log, rule=self)

    @property
    def input(self):
        return self._input

    def set_input(self, *input, **kwinput):
        """
        Add a list of input files. Recursive lists are flattened.

        Arguments
        input -- the list of input files
        """
        for item in input:
            self._set_inoutput_item(item)
        for name, item in kwinput.items():
            self._set_inoutput_item(item, name=name)

    @property
    def output(self):
        return self._output

    def set_output(self, *output, **kwoutput):
        """
        Add a list of output files. Recursive lists are flattened.

        Arguments
        output -- the list of output files
        """
        for item in output:
            self._set_inoutput_item(item, output=True)
        for name, item in kwoutput.items():
            self._set_inoutput_item(item, output=True, name=name)

        for item in self.output:
            if self.dynamic_output and item not in self.dynamic_output:
                raise SyntaxError(
                    "A rule with dynamic output may not define any "
                    "non-dynamic output files.")
            wildcards = item.get_wildcard_names()
            if self.wildcard_names:
                if self.wildcard_names != wildcards:
                    raise SyntaxError(
                        "Not all output files of rule {} "
                        "contain the same wildcards.".format(self.name))
            else:
                self.wildcard_names = wildcards

    def _set_inoutput_item(self, item, output=False, name=None):
        """
        Set an item to be input or output.

        Arguments
        item     -- the item
        inoutput -- either a Namedlist of input or output items
        name     -- an optional name for the item
        """
        inoutput = self.output if output else self.input
        if isinstance(item, str):
            _item = IOFile(item, rule=self)
            if isinstance(item, temp):
                if not output:
                    raise SyntaxError("Only output files may be temporary")
                self.temp_output.add(_item)
            if isinstance(item, protected):
                if not output:
                    raise SyntaxError("Only output files may be protected")
                self.protected_output.add(_item)
            if isinstance(item, dynamic):
                if output:
                    self.dynamic_output.add(_item)
                else:
                    self.dynamic_input.add(_item)
            inoutput.append(_item)
            if name:
                inoutput.add_name(name)
        elif callable(item):
            if output:
                raise SyntaxError(
                    "Only input files can be specified as functions")
            inoutput.append(item)
            if name:
                inoutput.add_name(name)
        else:
            try:
                start = len(inoutput)
                for i in item:
                    self._set_inoutput_item(i, output=output)
                if name:
                    # if the list was named, make it accessible
                    inoutput.set_name(name, start, end=len(inoutput))
            except TypeError:
                raise SyntaxError(
                    "Input and output files have to be specified as strings.")

    @property
    def params(self):
        return self._params

    def set_params(self, *params, **kwparams):
        for item in params:
            self._set_params_item(item)
        for name, item in kwparams.items():
            self._set_params_item(item, name=name)

    def _set_params_item(self, item, name=None):
        if isinstance(item, str) or callable(item):
            self.params.append(item)
            if name:
                self.params.add_name(name)
        else:
            try:
                start = len(self.params)
                for i in item:
                    self._set_params_item(i)
                if name:
                    self.params.set_name(name, start, end=len(self.params))
            except TypeError:
                raise SyntaxError("Params have to be specified as strings.")

    def expand_wildcards(self, wildcards=None):
        """
        Expand wildcards depending on the requested output
        or given wildcards dict.
        """
        def concretize_iofile(f, wildcards):
            if not isinstance(f, _IOFile):
                return IOFile(f, rule=self)
            else:
                return f.apply_wildcards(
                    wildcards,
                    fill_missing=f in self.dynamic_input,
                    fail_dynamic=self.dynamic_output)

        def _apply_wildcards(
            newitems,
            olditems,
            wildcards,
            wildcards_obj,
            concretize = apply_wildcards,
            ruleio = None):
            for name, item in olditems.allitems():
                start = len(newitems)
                if callable(item):
                    items = item(wildcards_obj)
                    if isinstance(items, str):
                        items = [items]
                    for item_ in items:
                        concrete = concretize(item_, wildcards)
                        newitems.append(concrete)
                        if ruleio is not None:
                            ruleio[concrete] = item_
                else:
                    if isinstance(item, str):
                        item = [item]
                    for item_ in item:
                        concrete = concretize(item_, wildcards)
                        newitems.append(concrete)
                        if ruleio is not None:
                            ruleio[concrete] = item_
                if name:
                    newitems.set_name(name, start, end=len(newitems))

        if wildcards is None:
            wildcards = dict()
        # TODO validate
        missing_wildcards = self.wildcard_names - set(wildcards.keys())

        if missing_wildcards:
            raise RuleException(
                "Could not resolve wildcards in rule {}:\n{}".format(
                    self.name, "\n".join(self.wildcard_names)),
                lineno=self.lineno, snakefile=self.snakefile)

        ruleio = dict()

        try:
            input = InputFiles()
            wildcards_obj = Wildcards(fromdict=wildcards)
            _apply_wildcards(input, self.input, wildcards, wildcards_obj,
                concretize=concretize_iofile, ruleio=ruleio)

            params = Params()
            _apply_wildcards(params, self.params, wildcards, wildcards_obj)

            output = OutputFiles(
                o.apply_wildcards(wildcards) for o in self.output)
            output.take_names(self.output.get_names())

            ruleio.update(dict((f, f_) for f, f_ in zip(output, self.output)))

            log = self.log.apply_wildcards(wildcards) if self.log else None
            return input, output, params, log, ruleio
        except WildcardError as ex:
            # this can only happen if an input contains an unresolved wildcard.
            raise RuleException(
                "Wildcards in input or log file of rule {} cannot be "
                "determined from output files:\n{}".format(self, str(ex)),
                lineno=self.lineno, snakefile=self.snakefile)

    def is_producer(self, requested_output):
        """
        Returns True if this rule is a producer of the requested output.
        """
        try:
            for o in self.output:
                match = o.match(requested_output)
                if match and len(match.group()) == len(requested_output):
                    return True
            return False
        except sre_constants.error as ex:
            raise IOFileException(
                "{} in wildcard statement".format(ex),
                snakefile=self.snakefile, lineno=self.lineno)
        except ValueError as ex:
            raise IOFileException(
                "{}".format(ex), snakefile=self.snakefile, lineno=self.lineno)

    def get_wildcards(self, requested_output):
        """
        Update the given wildcard dictionary by matching regular expression
        output files to the requested concrete ones.

        Arguments
        wildcards -- a dictionary of wildcards
        requested_output -- a concrete filepath
        """
        if requested_output is None:
            return dict()
        bestmatchlen = 0
        bestmatch = None
        bestmatch_output = None
        for i, o in enumerate(self.output):
            match = o.match(requested_output)
            if match:
                l = self.get_wildcard_len(match.groupdict())
                if not bestmatch or bestmatchlen > l:
                    bestmatch = match.groupdict()
                    bestmatchlen = l
                    bestmatch_output = self.output[i]
        return bestmatch

    @staticmethod
    def get_wildcard_len(wildcards):
        """
        Return the length of the given wildcard values.

        Arguments
        wildcards -- a dict of wildcards
        """
        return sum(map(len, wildcards.values()))

    def __lt__(self, rule):
        comp = self.workflow._ruleorder.compare(self.name, rule.name)
        return comp < 0

    def __gt__(self, rule):
        comp = self.workflow._ruleorder.compare(self.name, rule.name)
        return comp > 0

    def __str__(self):
        return self.name


class Ruleorder:
    def __init__(self):
        self.order = list()

    def add(self, *rulenames):
        """
        Records the order of given rules as rule1 > rule2 > rule3, ...
        """
        self.order.append(list(rulenames))

    def compare(self, rule1name, rule2name):
        """
        Return whether rule2 has a higher priority than rule1.
        """
        # try the last clause first,
        # i.e. clauses added later overwrite those before.
        for clause in reversed(self.order):
            try:
                i = clause.index(rule1name)
                j = clause.index(rule2name)
                # rules with higher priority should have a smaller index
                comp = j - i
                if comp < 0:
                    comp = -1
                elif comp > 0:
                    comp = 1
                return comp
            except ValueError:
                pass
        return 0

    def __iter__(self):
        return self.order.__iter__()