summaryrefslogtreecommitdiff
path: root/scripts/csv2sto.py
blob: 8e5300b35cd58becfd644fe5d8ca489d6f5f3b6b (plain)
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
#!/usr/bin/env python

import os, sys
import getopt
import csv

DEFAULT_NAME = 'control'

def usage():
    print """usage: %s [OPTION...] CSV-FILE STO-FILE

  -f  force overwrite of existing files
  -n  name of the sto file (default: %s)
  -h  show this help and exit""" % (DEFAULT_NAME, os.path.basename(sys.argv[0]))

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "fh")
    except getopt.GetoptError, err:
        print(str(err))
        usage()
        sys.exit(-1)

    if len(args) < 2:
        usage()
        sys.exit(-1)
    elif len(args) > 2:
        print "Merging CSV files currently not supported, only %s considered" % args[1]

    overwrite = False
    name = DEFAULT_NAME
    for o, a in opts:
        if o == '-f':
            overwrite = True
        elif o == '-n':
            name = a
        elif o == '-h':
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option"

    f_csv = args[0]
    f_sto = args[-1]
    if not os.path.exists(f_csv):
        print "Error: CSV file %s does not exist" % f_csv
        sys.exit(-1)
    if not overwrite and os.path.exists(f_sto):
        print "Error: STO file %s already exists" % f_sto
        sys.exit(-1)

    # determine number of columns and rows
    fd = open(f_csv, 'r')
    nRows = nColumns = 0
    for line in fd:
        if nRows == 0:
            nCols = len(line.split(','))
        nRows += 1
    fd.close()

    fd_sto = open(f_sto, 'w')
    fd_sto.write(name + "\n")
    fd_sto.write("nRows=" + str(nRows) + "\n")
    fd_sto.write("nColumns=" + str(nColumns) + "\n")
    fd_sto.write("endheader\n")

    print "Writing sto file %s with name %s" % (f_sto, name)

    colname = os.path.splitext(f_csv)[0]
    print "[+] Adding muscle %s..." % colname
    fd_sto.write("time\t" + colname + "\n")

    fd_csv = open(f_csv, 'r')
    cr = csv.reader(fd_csv, delimiter=',')

    for i, row in enumerate(cr):
        if i == 0:
            continue    # skip header line
        fd_sto.write("\t".join(row) + "\n")

    fd_csv.close()
    fd_sto.close()

if __name__ == '__main__':
    main()