comparison transpose.py @ 0:e0b5980139d9

maaslin
author george-weingart
date Tue, 13 May 2014 22:00:40 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e0b5980139d9
1 #!/usr/bin/env python
2 #######################################################################################
3 # This file is provided under the Creative Commons Attribution 3.0 license.
4 #
5 # You are free to share, copy, distribute, transmit, or adapt this work
6 # PROVIDED THAT you attribute the work to the authors listed below.
7 # For more information, please see the following web page:
8 # http://creativecommons.org/licenses/by/3.0/
9 #
10 # This file is a component of the SflE Scientific workFLow Environment for reproducible
11 # research, authored by the Huttenhower lab at the Harvard School of Public Health
12 # (contact Curtis Huttenhower, chuttenh@hsph.harvard.edu).
13 #
14 # If you use this environment, the included scripts, or any related code in your work,
15 # please let us know, sign up for the SflE user's group (sfle-users@googlegroups.com),
16 # pass along any issues or feedback, and we'll let you know as soon as a formal citation
17 # is available.
18 #######################################################################################
19
20 """
21 Examples
22 ~~~~~~~~
23
24 ``data.pcl``::
25
26 a b
27 c d
28 e f
29
30 ``Examples``::
31
32 $ transpose.py < data.pcl
33 a c e
34 b d f
35
36 $ echo "a b c" | transpose.py
37 a
38 b
39 c
40
41 .. testsetup::
42
43 from transpose import *
44 """
45
46 import argparse
47 import csv
48 import sys
49
50 def transpose( aastrIn, ostm ):
51 """
52 Outputs the matrix transpose of the input tab-delimited rows.
53
54 :param aastrIn: Split lines from which data are read.
55 :type aastrIn: collection of string collections
56 :param ostm: Output stream to which transposed rows are written.
57 :type ostm: output stream
58
59 >>> aastrIn = [list(s) for s in ("ab", "cd", "ef")]
60 >>> transpose( aastrIn, sys.stdout ) #doctest: +NORMALIZE_WHITESPACE
61 a c e
62 b d f
63
64 >>> transpose( [list("abc")], sys.stdout ) #doctest: +NORMALIZE_WHITESPACE
65 a
66 b
67 c
68 """
69
70 aastrLines = [a for a in aastrIn]
71 csvw = csv.writer( ostm, csv.excel_tab )
72 for iRow in range( len( aastrLines[0] ) ):
73 csvw.writerow( [aastrLines[iCol][iRow] for iCol in range( len( aastrLines ) )] )
74
75 argp = argparse.ArgumentParser( prog = "transpose.py",
76 description = """Transposes a tab-delimited text matrix.
77
78 The transposition process is robust to missing elements and rows of differing lengths.""" )
79 __doc__ = "::\n\n\t" + argp.format_help( ).replace( "\n", "\n\t" ) + __doc__
80
81 def _main( ):
82 args = argp.parse_args( )
83 transpose( csv.reader( sys.stdin, csv.excel_tab ), sys.stdout )
84
85 if __name__ == "__main__":
86 _main( )