summaryrefslogtreecommitdiff
path: root/scripts/plotsto.py
blob: 01c76f499a758837fc1f8d84fd50ec38b9dd73d7 (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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# plotsto.py -- Plot all muscle activation signals in a .sto file
#
# Copyright (C) 2013 Tobias Klauser <tklauser@distanz.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

import getopt
import os, sys
import numpy as np
import matplotlib.pyplot as plt

def usage():
    print("""usage: {} [OPTION...] STO-FILE...

Plot all muscle activation signals in a .sto file.

options:

    -h  show this help and exit""".format(os.path.basename(sys.argv[0])))

def read_sto(sto):
    f = open(sto, 'r')

    # .sto header format:
    # control
    # version=N
    # nRows=N
    # nColumns=N
    # endheader
    name = f.readline().strip()
    line = f.readline().strip().split('=')
    if line[0] != 'version' or not line[1].isdigit():
        f.close()
        print("Error: invalid version header line in {}: {}".format(sto, "=".join(line)))
        return None
    version = int(line[1])

    line = f.readline().strip().split('=')
    if line [0] != 'nRows' or not line[1].isdigit():
        f.close()
        print("Error: invalid nRows header line in {}: {}".format(sto, "=".join(line)))
        return None
    nRows = int(line[1])

    line = f.readline().strip().split('=')
    if line[0] != 'nColumns' or not line[1].isdigit():
        f.close()
        print("Error: invalid nColumns header line in {}: {}".format(sto, "=".join(line)))
        return None
    nColumns = int(line[1])

    endheader = f.readline().strip()
    if endheader != 'endheader':
        f.close()
        print("Error: header not properly terminated by 'endheader' in {}".format(sto))
        return None

    print("name: " + name)
    print("version: " + str(version))
    print("nRows: " + str(nRows))
    print("nColumns: " + str(nColumns))

    cols = f.readline().strip().split()
    if len(cols) != nColumns:
        f.close()
        print("Error: nColumns does not match number of columns in file")
        return None

    i = 0
    for line in f:
        i += 1

    f.close()

    if i != nRows:
        print("Error: nRows does not match number of rows in file")
        return None

    act = np.zeros((nRows, nColumns))

    f = open(sto, 'r')
    # skip first 6 lines (header)
    for i in range(6):
        _ = f.readline()
    i = 0
    for line in f:
        data = line.split()
        if len(data) != nColumns:
            f.close()
            print("Error: row {} has less than {} columns".format(i+7, nColumns))
            return None
        for j, val in enumerate(data):
            act[i,j] = float(val)
        i += 1
    f.close()

    return act, cols

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

    if len(args) < 1:
        usage()
        sys.exit(-1)

    for o, a in opts:
        if o == '-h':
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option"

    for sto in args:
        if not os.path.exists(sto):
            print "Error: File %s not found, skipping" % sto
            continue

        act, cols = read_sto(sto)
        # transpose so we can access it more conveniently
        act = act.transpose()
        t, ys = act[0], act[1:]
        l = []
        # see matplotlib.org/examples/pylab_examples/subplots.demo.html
        f, ax = plt.subplots(nrows=(len(cols) - 1) / 2, ncols=2, sharex='col', sharey='row')
        for i, y in enumerate(ys):
            ax[i/2,i%2].plot(t, y)
            l.append(cols[i+1])

        plt.axis([0, t.max(), 0, 1.0], 'equal')
    #    plt.legend(l, bbox_to_anchor=(1.05, 1.), loc=2, borderaxespad=0.)
        plt.show()

if __name__ == '__main__':
    main()