File: combinatorics.rst

package info (click to toggle)
python-ruffus 2.6.3%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 20,828 kB
  • ctags: 2,843
  • sloc: python: 15,745; makefile: 180; sh: 14
file content (442 lines) | stat: -rw-r--r-- 19,153 bytes parent folder | download | duplicates (6)
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
.. include:: ../../global.inc
.. include:: manual_chapter_numbers.inc

.. index::
    pair: combinatorics; Tutorial

.. _new_manual.combinatorics:

##################################################################################################################################################################################################################################################
|new_manual.combinatorics.chapter_num|: :ref:`@combinations<decorators.combinations>`, :ref:`@permutations<decorators.permutations>` and all versus all :ref:`@product<decorators.product>`
##################################################################################################################################################################################################################################################

.. seealso::

   * :ref:`Manual Table of Contents <new_manual.table_of_contents>`
   * :ref:`@combinations_with_replacement <decorators.combinations_with_replacement>`
   * :ref:`@combinations <decorators.combinations>`
   * :ref:`@permutations <decorators.permutations>`
   * :ref:`@product <decorators.product>`
   * :ref:`formatter() <decorators.formatter>`

.. note::

    Remember to look at the example code:

        * :ref:`new_manual.combinatorics.code`


**************************************
Overview
**************************************

    A surprising number of computational problems involve some sort of all versus all calculations.
    Previously, this would have required all the parameters to be supplied using a custom function
    on the fly with :ref:`@files<decorators.files_on_the_fly>`.

    From version 2.4, *Ruffus* supports  :ref:`@combinations_with_replacement <decorators.combinations_with_replacement>`,
    :ref:`@combinations <decorators.combinations>`, :ref:`@permutations <decorators.permutations>`,
    :ref:`@product <decorators.product>`.

    These provide as far as possible all the functionality of the four combinatorics iterators
    from the standard python `itertools  <http://docs.python.org/2/library/itertools.html>`__
    functions of the same name.

***************************************************************************
Generating output with :ref:`formatter()<decorators.formatter>`
***************************************************************************

    String replacement always takes place via :ref:`formatter()<decorators.formatter>`. Unfortunately,
    the other *Ruffus* workhorses of  :ref:`regex()<decorators.regex>` and  :ref:`suffix()<decorators.suffix>`
    do not have sufficient syntactic flexibility.

    Each combinatorics decorator deals with multiple sets of inputs whether this might be:

        * a self-self comparison (such as :ref:`@combinations_with_replacement <decorators.combinations_with_replacement>`,
          :ref:`@combinations <decorators.combinations>`, :ref:`@permutations <decorators.permutations>`) or,
        * a self-other comparison (:ref:`@product <decorators.product>`)

    The replacement strings thus require an extra level of indirection to refer to
    parsed components.

        #. The first level refers to which *set* of inputs.
        #. The second level refers to which input file in any particular *set* of inputs.


    For example, if the *inputs* are  **[A1,A2],[B1,B2],[C1,C2] vs [P1,P2],[Q1,Q2],[R1,R2] vs [X1,X2],[Y1,Y2],[Z1,Z2]**,
    then ``'{basename[2][0]}'`` is the `basename  <http://docs.python.org/2/library/os.path.html#os.path.basename>`__ for

        * the third set of inputs (**X,Y,Z**) and
        * the first file name string in each **Input** of that set (**X1, Y1, Z1**)



.. _new_manual.product:

***************************************************************************
All vs all comparisons with :ref:`@product <decorators.product>`
***************************************************************************

    :ref:`@product <decorators.product>` generates the Cartesian **product** between sets of input files,
    i.e. all vs all comparisons.

    The effect is analogous to a nested for loop.

    :ref:`@product <decorators.product>` can be useful, for example, in bioinformatics for finding
    the corresponding genes (orthologues) for a set of proteins in multiple species.

    .. code-block:: pycon
        :emphasize-lines: 2

        >>> from itertools import product
        >>> # product('ABC', 'XYZ') --> AX AY AZ BX BY BZ CX CY CZ
        >>> [ "".join(a) for a in product('ABC', 'XYZ')]
        ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']



    This example Calculates the **@product** of **A,B** and **P,Q** and **X,Y** files

        .. code-block:: python
            :emphasize-lines: 4,17,19,22,25,27,28,29,30,32,34,35,36

            from ruffus import *
            from ruffus.combinatorics import *

            #   Three sets of initial files
            @originate([ 'a.start', 'b.start'])
            def create_initial_files_ab(output_file):
                with open(output_file, "w") as oo: pass

            @originate([ 'p.start', 'q.start'])
            def create_initial_files_pq(output_file):
                with open(output_file, "w") as oo: pass

            @originate([ ['x.1_start', 'x.2_start'],
                         ['y.1_start', 'y.2_start'] ])
            def create_initial_files_xy(output_file):
                with open(output_file, "w") as oo: pass

            #   @product
            @product(   create_initial_files_ab,        # Input
                        formatter("(.start)$"),         # match input file set # 1

                        create_initial_files_pq,        # Input
                        formatter("(.start)$"),         # match input file set # 2

                        create_initial_files_xy,        # Input
                        formatter("(.start)$"),         # match input file set # 3

                        "{path[0][0]}/"                 # Output Replacement string
                        "{basename[0][0]}_vs_"          #
                        "{basename[1][0]}_vs_"          #
                        "{basename[2][0]}.product",     #

                        "{path[0][0]}",                 # Extra parameter: path for 1st set of files, 1st file name

                        ["{basename[0][0]}",            # Extra parameter: basename for 1st set of files, 1st file name
                         "{basename[1][0]}",            #                               2nd
                         "{basename[2][0]}",            #                               3rd
                         ])
            def product_task(input_file, output_parameter, shared_path, basenames):
                print "# basenames      = ", " ".join(basenames)
                print "input_parameter  = ", input_file
                print "output_parameter = ", output_parameter, "\n"


            #
            #       Run
            #
            pipeline_run(verbose=0)


    This results in:

        .. code-block:: pycon
            :emphasize-lines: 2,6,10,14,18,22,26,30

            >>> pipeline_run(verbose=0)

            # basenames      =  a p x
            input_parameter  =  ('a.start', 'p.start', 'x.start')
            output_parameter =  /home/lg/temp/a_vs_p_vs_x.product

            # basenames      =  a p y
            input_parameter  =  ('a.start', 'p.start', 'y.start')
            output_parameter =  /home/lg/temp/a_vs_p_vs_y.product

            # basenames      =  a q x
            input_parameter  =  ('a.start', 'q.start', 'x.start')
            output_parameter =  /home/lg/temp/a_vs_q_vs_x.product

            # basenames      =  a q y
            input_parameter  =  ('a.start', 'q.start', 'y.start')
            output_parameter =  /home/lg/temp/a_vs_q_vs_y.product

            # basenames      =  b p x
            input_parameter  =  ('b.start', 'p.start', 'x.start')
            output_parameter =  /home/lg/temp/b_vs_p_vs_x.product

            # basenames      =  b p y
            input_parameter  =  ('b.start', 'p.start', 'y.start')
            output_parameter =  /home/lg/temp/b_vs_p_vs_y.product

            # basenames      =  b q x
            input_parameter  =  ('b.start', 'q.start', 'x.start')
            output_parameter =  /home/lg/temp/b_vs_q_vs_x.product

            # basenames      =  b q y
            input_parameter  =  ('b.start', 'q.start', 'y.start')
            output_parameter =  /home/lg/temp/b_vs_q_vs_y.product


.. _new_manual.permutations:

******************************************************************************************************************************************************
Permute all k-tuple orderings of inputs without repeats using :ref:`@permutations <decorators.permutations>`
******************************************************************************************************************************************************

    Generates the **permutations** for all the elements of a set of **Input** (e.g. **A B C D**),
        * r-length tuples of *input* elements
        * excluding repeated elements (**A A**)
        * and order of the tuples is significant (both **A B** and  **B A**).

    .. code-block:: pycon
        :emphasize-lines: 2

        >>> from itertools import permutations
        >>> # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
        >>> [ "".join(a) for a in permutations("ABCD", 2)]
        ['AB', 'AC', 'AD', 'BA', 'BC', 'BD', 'CA', 'CB', 'CD', 'DA', 'DB', 'DC']

    This following example calculates the **@permutations** of **A,B,C,D** files

        .. code-block:: python
            :emphasize-lines: 13,17,20,25,28-30

            from ruffus import *
            from ruffus.combinatorics import *

            #   initial file pairs
            @originate([ ['A.1_start', 'A.2_start'],
                         ['B.1_start', 'B.2_start'],
                         ['C.1_start', 'C.2_start'],
                         ['D.1_start', 'D.2_start']])
            def create_initial_files_ABCD(output_files):
                for output_file in output_files:
                    with open(output_file, "w") as oo: pass

            #   @permutations
            @permutations(create_initial_files_ABCD,      # Input
                          formatter(),                    # match input files

                          # tuple of 2 at a time
                          2,

                          # Output Replacement string
                          "{path[0][0]}/"
                          "{basename[0][1]}_vs_"
                          "{basename[1][1]}.permutations",

                          # Extra parameter: path for 1st set of files, 1st file name
                          "{path[0][0]}",

                          # Extra parameter
                          ["{basename[0][0]}",  # basename for 1st set of files, 1st file name
                           "{basename[1][0]}",  #                                2nd
                           ])
            def permutations_task(input_file, output_parameter, shared_path, basenames):
                print " - ".join(basenames)


            #
            #       Run
            #
            pipeline_run(verbose=0)


    This results in:

        .. code-block:: pycon

            >>> pipeline_run(verbose=0)

            A - B
            A - C
            A - D
            B - A
            B - C
            B - D
            C - A
            C - B
            C - D
            D - A
            D - B
            D - C

.. _new_manual.combinations:

********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
Select unordered k-tuples within inputs excluding repeated elements using :ref:`@combinations <decorators.combinations>`
********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************

    Generates the **combinations** for all the elements of a set of **Input** (e.g. **A B C D**),
        * r-length tuples of *input* elements
        * without repeated elements (**A A**)
        * where order of the tuples is irrelevant (either **A B** or  **B A**, not both).

    :ref:`@combinations <decorators.combinations>` can be useful, for example, in calculating a transition probability matrix
    for a set of states. The diagonals are meaningless "self-self" transitions which are excluded.

    .. code-block:: pycon
        :emphasize-lines: 2

        >>> from itertools import combinations
        >>> # combinations('ABCD', 3) --> ABC ABD ACD BCD
        >>> [ "".join(a) for a in combinations("ABCD", 3)]
        ['ABC', 'ABD', 'ACD', 'BCD']

    This example calculates the **@combinations** of **A,B,C,D** files

        .. code-block:: python
            :emphasize-lines: 13,17,20,25,28-30

            from ruffus import *
            from ruffus.combinatorics import *

            #   initial file pairs
            @originate([ ['A.1_start', 'A.2_start'],
                         ['B.1_start', 'B.2_start'],
                         ['C.1_start', 'C.2_start'],
                         ['D.1_start', 'D.2_start']])
            def create_initial_files_ABCD(output_files):
                for output_file in output_files:
                    with open(output_file, "w") as oo: pass

            #   @combinations
            @combinations(create_initial_files_ABCD,      # Input
                          formatter(),                    # match input files

                          # tuple of 3 at a time
                          3,

                          # Output Replacement string
                          "{path[0][0]}/"
                          "{basename[0][1]}_vs_"
                          "{basename[1][1]}_vs_"
                          "{basename[2][1]}.combinations",

                          # Extra parameter: path for 1st set of files, 1st file name
                          "{path[0][0]}",

                          # Extra parameter
                          ["{basename[0][0]}",  # basename for 1st set of files, 1st file name
                           "{basename[1][0]}",  #              2nd
                           "{basename[2][0]}",  #              3rd
                           ])
            def combinations_task(input_file, output_parameter, shared_path, basenames):
                print " - ".join(basenames)


            #
            #       Run
            #
            pipeline_run(verbose=0)


    This results in:

        .. code-block:: pycon

            >>> pipeline_run(verbose=0)
            A - B - C
            A - B - D
            A - C - D
            B - C - D

.. _new_manual.combinations_with_replacement:

********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
Select unordered k-tuples within inputs *including* repeated elements with :ref:`@combinations_with_replacement <decorators.combinations_with_replacement>`
********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************

    Generates the **combinations_with_replacement** for all the elements of a set of **Input** (e.g. **A B C D**),
        * r-length tuples of *input* elements
        * including repeated elements (**A A**)
        * where order of the tuples is irrelevant (either **A B** or  **B A**, not both).


    :ref:`@combinations_with_replacement <decorators.combinations_with_replacement>` can be useful,
    for example, in bioinformatics for finding evolutionary relationships between genetic elements such as proteins
    and genes. Self-self comparisons can be used a baseline for scaling similarity scores.

    .. code-block:: pycon
        :emphasize-lines: 2

        >>> from itertools import combinations_with_replacement
        >>> # combinations_with_replacement('ABCD', 2) --> AA AB AC AD BB BC BD CC CD DD
        >>> [ "".join(a) for a in combinations_with_replacement('ABCD', 2)]
        ['AA', 'AB', 'AC', 'AD', 'BB', 'BC', 'BD', 'CC', 'CD', 'DD']

    This example calculates the **@combinations_with_replacement** of **A,B,C,D** files

        .. code-block:: python
            :emphasize-lines: 13,17,20,25,28-30

            from ruffus import *
            from ruffus.combinatorics import *

            #   initial file pairs
            @originate([ ['A.1_start', 'A.2_start'],
                         ['B.1_start', 'B.2_start'],
                         ['C.1_start', 'C.2_start'],
                         ['D.1_start', 'D.2_start']])
            def create_initial_files_ABCD(output_files):
                for output_file in output_files:
                    with open(output_file, "w") as oo: pass

            #   @combinations_with_replacement
            @combinations_with_replacement(create_initial_files_ABCD,   # Input
                          formatter(),                                  # match input files

                          # tuple of 2 at a time
                          2,

                          # Output Replacement string
                          "{path[0][0]}/"
                          "{basename[0][1]}_vs_"
                          "{basename[1][1]}.combinations_with_replacement",

                          # Extra parameter: path for 1st set of files, 1st file name
                          "{path[0][0]}",

                          # Extra parameter
                          ["{basename[0][0]}",  # basename for 1st set of files, 1st file name
                           "{basename[1][0]}",  #              2rd
                           ])
            def combinations_with_replacement_task(input_file, output_parameter, shared_path, basenames):
                print " - ".join(basenames)


            #
            #       Run
            #
            pipeline_run(verbose=0)


    This results in:

        .. code-block:: pycon

            >>> pipeline_run(verbose=0)
            A - A
            A - B
            A - C
            A - D
            B - B
            B - C
            B - D
            C - C
            C - D
            D - D