Project

General

Profile

Python SDK » History » Version 6

Brett Smith, 08/28/2014 11:21 AM
add another example

1 1 Tom Clegg
h1. Python SDK
2
3
(design draft)
4
5 5 Brett Smith
h1. Hypothetical future Crunch scripts
6 1 Tom Clegg
7 5 Brett Smith
We're writing these out with the goal of designing a new SDK for Crunch script authors.
8
9
{{toc}}
10
11
h2. Example scripts
12
13 6 Brett Smith
h3. Example: "Normalize" files matching a regexp
14 5 Brett Smith
15 1 Tom Clegg
<pre><code class="python">
16
#!/usr/bin/env python
17
18
from arvados import CrunchJob
19
20
import examplelib
21
import re
22
23
class NormalizeMatchingFiles(CrunchJob):
24
    @CrunchJob.task()
25
    def grep_files(self):
26
        # CrunchJob instantiates input parameters based on the
27
        # dataclass attribute.  When we ask for the input parameter,
28
        # CrunchJob sees that it's a Collection, and returns a
29
        # CollectionReader object.
30 3 Brett Smith
        input_coll = self.job_param('input')
31
        for filename in input_coll.filenames():
32
            self.grep_file(self.job_param('pattern'), input_coll, filename)
33 1 Tom Clegg
34
    @CrunchJob.task()
35 3 Brett Smith
    def grep_file(self, pattern, collection, filename):
36
        regexp = re.compile(pattern)
37
        with collection.open(filename) as in_file:
38 1 Tom Clegg
            for line in in_file:
39
                if regexp.search(line):
40 4 Brett Smith
                    self.normalize(in_file)
41 1 Tom Clegg
                    break
42
43
    # examplelib is already multi-threaded and will peg the whole
44
    # compute node.  These tasks should run sequentially.
45 4 Brett Smith
    # When tasks are created, Arvados-specific objects like Collection file
46
    # objects are serialized as task parameters.  CrunchJob instantiates
47
    # these parameters as real objects when it runs the task.
48 1 Tom Clegg
    @CrunchJob.task(parallel_with=[])
49 4 Brett Smith
    def normalize(self, coll_file):
50
        output = examplelib.frob(coll_file.mount_path())
51 1 Tom Clegg
        # self.output is a CollectionWriter.  When this task method finishes,
52
        # CrunchJob checks if we wrote anything to it.  If so, it takes care
53
        # of finishing the upload process, and sets this task's output to the
54
        # Collection UUID.
55
        with self.output.open(filename) as out_file:
56
            out_file.write(output)
57
58
59 2 Tom Clegg
if __name__ == '__main__':
60 1 Tom Clegg
    NormalizeMatchingFiles(task0='grep_files').main()
61 6 Brett Smith
</code></pre>
62
63
h3. Example: Crunch statistics on a Collection of fastj files indicating a tumor
64
65
This demonstrates scheduling tasks in order and explicit job output.
66
67
<pre><code class="python">
68
#!/usr/bin/env python
69
70
import glob
71
import os
72
import pprint
73
74
from arvados import CrunchJob
75
from subprocess import check_call
76
77
class TumorAnalysis(CrunchJob):
78
    OUT_EXT = '.analysis'
79
80
    @CrunchJob.task()
81
    def check_fastjs(self):
82
        in_coll = self.job_param('input')
83
        for name in in_coll.filenames():
84
            if name.endswith('.fastj'):
85
                self.classify(in_coll, name)
86
        # analyze_tumors gets scheduled to run after all the classification,
87
        # since they're not parallel with each other (and it was invoked later).
88
        self.analyze_tumors()
89
90
    @CrunchJob.task()
91
    def classify(self, collection, filename):
92
        # Methods that refer to directories, like mount_path and job_dir,
93
        # work like os.path.join when you pass them arguments.
94
        check_call(['normal_or_tumor', collection.mount_path(filename)])
95
        outpath = filename + self.OUT_EXT
96
        with open(outpath) as result:
97
             is_tumor = 'tumor' in result.read(4096)
98
        if is_tumor:
99
            os.rename(outpath, self.job_dir(outpath))
100
101
    @CrunchJob.task()
102
    def analyze_tumors(self):
103
        compiled = {}
104
        results = glob.glob(self.job_dir('*' + self.OUT_EXT))
105
        for outpath in results:
106
            with open(outpath) as outfile:
107
                compiled[thing] = ...  # Imagine this is a reduce-type step.
108
        # job_output is a CollectionWriter.  Writing to it overrides the
109
        # default behavior where job output is collated task output.
110
        with self.job_output.open('compiled_numbers.log') as resultfile:
111
            pprint.pprint(compiled, resultfile)
112
113
114
if __name__ == '__main__':
115
    TumorAnalysis(task0='check_fastjs').run()
116 1 Tom Clegg
</code></pre>
117
118 5 Brett Smith
h3. Example from #3603
119
120
This is the script that Abram used to illustrate #3603.
121
122
<pre><code class="python">
123
#!/usr/bin/env python
124
125
from arvados import Collection, CrunchJob
126
from subprocess import check_call
127
128
class Example3603(CrunchJob):
129
    @CrunchJob.task()
130
    def parse_human_map(self):
131
        refpath = self.job_param('REFPATH').name
132
        for line in self.job_param('HUMAN_COLLECTION_LIST'):
133
            fastj_id, human_id = line.strip().split(',')
134
            self.run_ruler(refpath, fastj_id, human_id)
135
136
    @CrunchJob.task()
137
    def run_ruler(self, refpath, fastj_id, human_id):
138
        check_call(["tileruler", "--crunch", "--noterm", "abv",
139
                    "-human", human_id,
140
                    "-fastj-path", Collection(fastj_id).mount_path(),
141
                    "-lib-path", refpath])
142
        self.output.add('.')  # Or the path where tileruler writes output.
143
144
145
if __name__ == '__main__':
146
    Example3603(task0='parse_human_map').run()
147
</code></pre>
148
149
h2. Notes/TODO
150
151 2 Tom Clegg
* Important concurrency limits that job scripts must be able to express:
152
** Task Z cannot start until all outputs/side effects of tasks W, X, Y are known/complete (e.g., because Z uses WXY's outputs as its inputs).
153
** Task Y and Z cannot run on the same worker node without interfering with each other (e.g., due to RAM requirements).
154
* In general, the output name is not known until the task is nearly finished. Frequently it is clearer to specify it when the task is queued, though. We should provide a convenient way to do this without any boilerplate in the queued task.
155
* A second example that uses a "case" and "control" input (e.g., "tumor" and "normal") might help reveal features.
156 1 Tom Clegg
* Should get more clear about how the output of the job (as opposed to the output of the last task) is to be set. The obvious way (concatenate all task outputs) should be a one-liner, if not implicit. Either way, it should run in a task rather than being left up to @crunch-job@.