-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
280 lines (238 loc) · 9.16 KB
/
utilities.py
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
#!/usr/bin/env python
"""
Utility functions.
Authors:
- Arno Klein, 2015 ([email protected]) http://binarybottle.com
Copyright 2015, Sage Bionetworks (http://sagebase.org), Apache v2.0 License
"""
def run_command(command, flag1='', arg1='', flags='', args=[],
flagn='', argn='', closing=''):
"""
Run a generic command.
Parameters
----------
command : string
name of command: "SMILExtract"
flag1 : string
optional first command line flag
arg1 : string
optional first argument, handy for iterating over in the pipeline
flags : string or list of strings
command line flags precede their respective args: ["-C", "-I", "-O"]
args : string or list of strings
command line arguments: ["config.conf", "input.wav", "output.csv"]
flagn : string
optional last command line flag
argn : string
optional last argument, handy for iterating over in the pipeline
closing : string
closing string in command
Returns
-------
command_line : string
full command line
args : list of strings
command line arguments
arg1 : string
optional first argument, handy for iterating over in the pipeline
argn : string
optional last argument, handy for iterating over in the pipeline
Examples
--------
>>> from mhealthx.utilities import run_command
>>> command = 'ls'
>>> flag1 = ''
>>> arg1 = ''
>>> flags = ['-l', '']
>>> args = ['/software', '/desk']
>>> flagn = ''
>>> argn = ''
>>> closing = '' #'> test.txt'
>>> command_line, args, arg1, argn = run_command(command, flag1, arg1, flags, args, flagn, argn, closing)
"""
from nipype.interfaces.base import CommandLine
# Join flags with args:
if type(flags) == list and type(args) == list:
flag_arg_tuples = zip(flags, args)
flags_args = ''
for flag_arg_tuple in flag_arg_tuples:
flags_args = ' '.join([flags_args, ' '.join(flag_arg_tuple)])
elif type(flags) == str and type(args) == str:
flags_args = ' '.join([flags, args])
else:
raise IOError("-flags and -args should both be strings or lists")
options = ' '.join([' '.join([flag1, arg1]), flags_args,
' '.join([flagn, argn]), closing])
command_line = ' '.join([command, options])
# Nipype command line wrapper:
try:
cli = CommandLine(command=command)
cli.inputs.args = options
cli.cmdline
cli.run()
except:
import traceback; traceback.print_exc()
print("'{0}' unsuccessful".format(command_line))
return command_line, args, arg1, argn
def plotxyz(x, y, z, t, title='', limits=[]):
"""
Plot each accelerometer axis separately against relative time.
Parameters
----------
x : list or numpy array of floats
y : list or numpy array of floats
z : list or numpy array of floats
t : list or numpy array of floats
time points
title : string
limits : list of floats
Examples
--------
>>> from mhealthx.xio import read_accel_json
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp'
>>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-5981e0a8-6481-41c8-b589-fa207bfd2ab38771455825726024828.tmp'
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp'
>>> start = 150
>>> device_motion = True
>>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion)
>>> ax, ay, az = axyz
>>> from mhealthx.utilities import plotxyz
>>> plotxyz(ax, ay, az, t, title='', limits=[])
"""
import numpy as np
import matplotlib.pyplot as plt
t -= np.min(t)
plt.figure()
plt.subplot(3, 1, 1)
plt.plot(t, x)
if limits:
plt.ylim((limits[0], limits[1]))
plt.title('x-axis ' + title)
plt.ylabel(title)
plt.subplot(3, 1, 2)
plt.plot(t, y)
if limits:
plt.ylim((limits[0], limits[1]))
plt.title('y-axis ' + title)
plt.ylabel(title)
plt.subplot(3, 1, 3)
plt.plot(t, z)
if limits:
plt.ylim((limits[0], limits[1]))
plt.title('z-axis ' + title)
plt.xlabel('Time (s)')
plt.ylabel(title)
plt.show()
def plotxyz3d(x, y, z, title=''):
"""
Plot accelerometer readings in 3-D.
(If trouble with "projection='3d'", try: ipython --pylab)
Parameters
----------
x : list or numpy array of floats
y : list or numpy array of floats
z : list or numpy array of floats
title : string
title
Examples
--------
>>> from mhealthx.xio import read_accel_json
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp'
>>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-5981e0a8-6481-41c8-b589-fa207bfd2ab38771455825726024828.tmp'
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp'
>>> start = 150
>>> device_motion = True
>>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion)
>>> x, y, z = axyz
>>> title = 'Test vectors'
>>> from mhealthx.utilities import plotxyz3d
>>> plotxyz3d(x, y, z, title)
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
#ax.plot(x, y, z) #, marker='o'
ax.plot(x[1::], y[1::], z[1::], label='x, y, z') #, marker='o'
ax.legend()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
#ax.set_xlim3d(0, 1)
#ax.set_ylim3d(0, 1)
#ax.set_zlim3d(0, 1)
plt.xlabel('x')
plt.ylabel('y')
plt.zlabel('z')
plt.title(title)
plt.show()
def plot_vectors(x, y, z, hx=[], hy=[], hz=[], title=''):
"""
Plot vectors in 3-D from the origin [0,0,0].
(If trouble with "projection='3d'", try: ipython --pylab)
From: http://stackoverflow.com/questions/22867620/
putting-arrowheads-on-vectors-in-matplotlibs-3d-plot
Parameters
----------
x : list or numpy array of floats
x-axis data for vectors
y : list or numpy array of floats
y-axis data for vectors
z : list or numpy array of floats
z-axis data for vectors
hx : list or numpy array of floats
x-axis data for vectors to highlight
hy : list or numpy array of floats
y-axis data for vectors to highlight
hz : list or numpy array of floats
z-axis data for vectors to highlight
title : string
title
Examples
--------
>>> from mhealthx.xio import read_accel_json
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp'
>>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-5981e0a8-6481-41c8-b589-fa207bfd2ab38771455825726024828.tmp'
>>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp'
>>> start = 150
>>> device_motion = True
>>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion)
>>> x, y, z = axyz
>>> hx, hy, hz = [[0,1],[0,1],[0,1]]
>>> title = 'Test vectors'
>>> from mhealthx.utilities import plot_vectors
>>> plot_vectors(x, y, z, hx, hy, hz, title)
"""
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
FancyArrowPatch.draw(self, renderer)
fig = plt.figure()
ax = fig.gca(projection='3d')
for i, x in enumerate(x):
a = Arrow3D([0, x], [0, y[i]], [0, z[i]],
mutation_scale=20, lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
if hx:
for i, hx in enumerate(hx):
a = Arrow3D([0, hx], [0, hy[i]], [0, hz[i]],
mutation_scale=20, lw=1, arrowstyle="-|>", color="r")
ax.add_artist(a)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.title(title)
plt.draw()
plt.show()
def create_directory(path):
import os
if not os.path.exists(path):
os.makedirs(path)
print "Created directory: ", path