Debian Codegraph @

doc/tutorials/defining_new_commands.rst

raw ◀ ▶
1 Debian patch touch this file
1 .. _defining-new-commands:
2
3 Defining new commands
4 =====================
5
6 A pyqi ``Command`` is a class that accepts inputs, does some work, and produces outputs. A ``Command`` is designed to be interface agnostic, so ideally should not be tied to a filesystem (i.e., it shouldn't do I/O or take filepaths) though there are some exceptions. Your ``Command`` class ultimately defines an API for your ``Command`` that can then easily be wrapped in other interface types (for example, a command line interface and/or a web interface) which handle input and output in an interface-specific way. This strategy also facilitates unit testing of your ``Command`` (by separating core functionality, which is essential to test, from interfaces, which can be very difficult to test in an automated fashion), parallel processing with your ``Command``, and constructing workflows that chain multiple ``Commands`` together. In general, your ``Command`` should take structured input (for example, a list of tuples or a numpy array), not a file that needs to be parsed.
7
8 This document describes how to create your first ``pyqi`` ``Command``.
9
10 Stubbing a new command
11 ----------------------
12
13 After installing pyqi, you can easily stub (i.e., create templates for) new commands using ``pyqi make-command``. You can get usage information by calling::
14
15 pyqi make-command -h
16
17 To create our sequence collection summarizer, we can start by stubbing a ``SequenceCollectionSummarizer`` class::
18
19 pyqi make-command -n SequenceCollectionSummarizer --credits "Greg Caporaso" -o sequence_collection_summarizer.py
20
21 If you run this command locally, substituting your own name where applicable, you'll have a new file called ``sequence_collection_summarizer.py``, which will look roughly like the following::
22
•23 #!/usr/bin/python3
24 from __future__ import division
25
26 __credits__ = ["Greg Caporaso"]
27
28 from pyqi.core.command import (Command, CommandIn, CommandOut,
29 ParameterCollection)
30
31 class SequenceCollectionSummarizer(Command):
32 BriefDescription = "FILL IN A 1 SENTENCE DESCRIPTION"
33 LongDescription = "GO INTO MORE DETAIL"
34 CommandIns = ParameterCollection([
35 CommandIn(Name='foo', DataType=str,
36 Description='some required parameter', Required=True),
37 CommandIn(Name='bar', DataType=int,
38 Description='some optional parameter', Required=False,
39 Default=1)
40 ])
41
42 CommandOuts = ParameterCollection([
43 CommandOut(Name="result_1", DataType=str, Description="xyz"),
44 CommandOut(Name="result_2", DataType=str, Description="123"),
45 ])
46
47 def run(self, **kwargs):
48 # EXAMPLE:
49 # return {'result_1': kwargs['foo'] * kwargs['bar'],
50 # 'result_2': "Some output bits"}
51 raise NotImplementedError("You must define this method")
52
53 CommandConstructor = SequenceCollectionSummarizer
54
55 Defining a command
56 ------------------
57
58 There are several values that you'll need to fill in to define your command based on the stub that is created by ``make-command``. The first, which are the easiest, are ``BriefDescription`` and ``LongDescription``. ``BriefDescription`` should be a one sentence description of your command, and ``LongDescription`` should be a more detailed explanation (usually 2-3 sentences). These are used in auto-generated documentation.
59
60 Next, you'll need to define the parameters that your new command can take as input. Each of these parameters will be an instance of the ``pyqi.core.command.CommandIn`` class.
61
62 Our ``SequenceCollectionSummarizer`` command will take one required parameter and one optional parameter. The required parameter will be called ``seqs``, and will be a list (or some other iterable type) of tuples of (sequence identifier, sequence) pairs. For example::
63
64 [('sequence1','ACCGTGGACCAA'),('sequence2','TGTGGA'), ...]
65
66 We'll also need to provide a description of this parameter (used in documentation), its type, and indicate that it is required. The final ``CommandIn`` definition should look like this::
67
68 CommandIn(Name='seqs', DataType=list,
69 Description='sequences to be summarized', Required=True)
70
71 The optional parameter will be called ``suppress_length_summary``, and if passed will indicate that we don't want information on sequence lengths included in our output summary. The ``Parameter`` definition in this case should look like this::
72
73 CommandIn(Name='suppress_length_summary', DataType=bool,
74 Description='do not generate summary information on the sequence lengths',
75 Required=False, Default=False)
76
77 The only additional parameter that is passed here, relative to our ``seqs`` parameter, is ``Default``. Because this parameter isn't required, it's necessary to give it a default value here. All of the ``CommandIns`` should be included in a ``pyqi.core.command.ParameterCollection`` object (as in the stubbed file).
78
79 .. note:: There are a few restrictions on what ``Name`` can be set to for a ``Parameter`` (e.g., a ``CommandIn`` or a ``CommandOut``). It must be a `valid python identifier <http://docs.python.org/2/reference/lexical_analysis.html#identifiers>`_ (e.g., it cannot contain ``-`` characters or begin with a number) so the ``Command`` can be called with named options instead of passing a dict. ``Parameter`` names also must be unique for a ``Command``.
80
81 Next, you'll need to define the results that the ``Command`` generates as output. In this example, our ``Command`` will generate three results: the number of sequences, the minimum sequence length, and the maximum sequence length. Each of these results will be an instance of the ``pyqi.core.command.CommandOut`` class. We define the name of the result, its type, and a description. The final ``CommandOuts`` should look like this::
82
83 CommandOut(Name='num_seqs', DataType=int, Description='number of sequences'),
84 CommandOut(Name='min_length', DataType=int, Description='minimum sequence length'),
85 CommandOut(Name='max_length', DataType=int, Description='maximum sequence length')
86
87 All of the ``CommandOuts`` should be included in a ``pyqi.core.command.ParameterCollection`` object (as in the stubbed file).
88
89 Next, we'll need to define what our ``Command`` will actually do. This is done in the ``run`` method, and all results are returned in a dictionary. The run method for our ``SequenceCollectionSummarizer`` object would look like the following::
90
91 def run(self, **kwargs):
92 """
93 """
94 num_seqs = 0
95 sequence_lengths = []
96 for seq_id, seq in kwargs['seqs']:
97 num_seqs += 1
98 sequence_lengths.append(len(seq))
99
100 if kwargs['suppress_length_summary']:
101 min_length = None
102 max_length = None
103 else:
104 min_length = min(sequence_lengths)
105 max_length = max(sequence_lengths)
106
107 return {'num_seqs':num_seqs,
108 'min_length':min_length,
109 'max_length':max_length}
110
111 In practice, if your ``Command`` is more complex than our ``SequenceCollectionSummarizer`` (which it probably is), you can define other methods that are called by ``run``. These should likely be private methods.
112
113 .. note:: ``kwargs`` is validated prior to ``run`` being called, so that any required ``kwargs`` that are missing will raise an error, and any optional ``kwargs`` that are missing will have their default values filled in. To customize the validation that is performed on ``kwargs`` for your ``Command`` you should override ``_validate_kwargs`` in your ``Command``.
114
115 A complete example Command
116 --------------------------
117
118 The following illustrates a complete python file defining a new pyqi ``Command``::
119
•120 #!/usr/bin/python3
121 from __future__ import division
122
123 __credits__ = ["Greg Caporaso"]
124
125 from pyqi.core.command import (Command, CommandIn, CommandOut,
126 ParameterCollection)
127
128 class SequenceCollectionSummarizer(Command):
129 BriefDescription = "Generate summary statistics on a collection of sequences."
130 LongDescription = "Provide the number of sequences, the minimum sequence length, and the maximum sequence length given a collection of sequences. Sequences should be provided as a list (or other iterable object) of tuples of (sequence id, sequence) pairs."
131
132 CommandIns = ParameterCollection([
133 CommandIn(Name='seqs', DataType=list,
134 Description='sequences to be summarized', Required=True),
135 CommandIn(Name='suppress_length_summary', DataType=bool,
136 Description='do not generate summary information on the sequence lengths',
137 Required=False, Default=False)
138 ])
139
140 CommandOuts = ParameterCollection([
141 CommandOut(Name='num_seqs', DataType=int, Description='number of sequences'),
142 CommandOut(Name='min_length', DataType=int, Description='minimum sequence length'),
143 CommandOut(Name='max_length', DataType=int, Description='maximum sequence length')
144 ])
145
146 def run(self, **kwargs):
147 """
148 """
149 num_seqs = 0
150 sequence_lengths = []
151 for seq_id, seq in kwargs['seqs']:
152 num_seqs += 1
153 sequence_lengths.append(len(seq))
154
155 if kwargs['suppress_length_summary']:
156 min_length = None
157 max_length = None
158 else:
159 min_length = min(sequence_lengths)
160 max_length = max(sequence_lengths)
161
162 return {'num_seqs':num_seqs,
163 'min_length':min_length,
164 'max_length':max_length}
165
166 CommandConstructor = SequenceCollectionSummarizer
167
168 At this stage you have defined a new command and its API. To access the API in the python terminal, you could do the following::
169
170 # Import your new class
171 >>> from sequence_collection_summarizer import SequenceCollectionSummarizer
172 # Instantiate it
173 >>> s = SequenceCollectionSummarizer()
174 # Call the command, passing a list of (seq id, sequence) tuples as input.
175 # Note that because the parameters are provided as kwargs, you need to
176 # pass the parameter with a keyword.
177 >>> r = s(seqs=[('sequence1','ACCGTGGACCAA'),('sequence2','TGTGGA')])
178 # You can now see the full output of the command by inspecting the
179 # result dictionary.
180 >>> r
181 {'max_length': 12, 'min_length': 6, 'num_seqs': 2}
182 # Alternatively, you can access each value independently, as with any dictionary.
•183 >>> print(r['num_seqs'])
184 2
•185 >>> print(r['min_length'])
186 6
•187 >>> print(r['max_length'])
188 12
189 # You can call this command again with different input.
190 # For example, we can call the command again passing the
191 # suppress_length_summary parameter.
192 >>> r = s(seqs=[('sequence1','ACCGTGGACCAA'),('sequence2','TGTGGA')],suppress_length_summary=True)
193 >>> r
194 {'max_length': None, 'min_length': None, 'num_seqs': 2}
195