forked from philliphartin/taut-sensoranalysis-python
/
plotting.py
382 lines (286 loc) · 11.7 KB
/
plotting.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
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
import csv
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as sci
import seaborn as sns
import sensorprocessor as sp
import signalfilters as mf
csv_missed = '/Users/philliphartin/TAUT/SensorRecordings/3802/6/3802_1409230847_Accelerometer.csv'
csv_acknowledged = '/Users/philliphartin/TAUT/SensorRecordings/3802/6/3802_1403040715_Accelerometer.csv'
def calculate_percentagedifference(v1, v2):
import math
percentage_diff = abs((abs(v1) - abs(v2)) / ((v1 + v2) / 2) * 100)
if math.isnan(percentage_diff):
return 0
else:
return percentage_diff
def calculate_difference(original, comparison):
# Create a list of the difference in values between two dicts
percentage_change = {}
percentage_difference = {}
for key, value in original.items():
value_orig = value
value_comp = comparison[key]
# percentrage_change[key] = abs(value_orig - value_comp)
percentage_change[key] = calculate_percentagechange(value_orig, value_comp)
percentage_difference[key] = calculate_percentagedifference(value_orig, value_comp)
return percentage_difference
def calculate_percentagechange(old_value, new_value, multiply=True):
change = new_value - old_value
try:
percentage_change = (change / float(old_value))
if multiply:
percentage_change = percentage_change * 100
return percentage_change
except ZeroDivisionError as e:
print(e)
return None
def calcualate_meanfordictionary(data):
values = []
for key, value in data.items():
values.append(value)
return np.mean(values)
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i + 1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
def import_sensorfile(filepath):
with open(filepath) as csv_sensorfile:
sensorfile = csv.reader(csv_sensorfile, delimiter=',', quotechar='|')
sensor_rows = []
for row in sensorfile:
# the correct format has 4 elements (avoids header and footer rows)
if len(row) == 4:
try:
timestamp = int(row[0])
x = float(row[1])
y = float(row[2])
z = float(row[3])
sensor_rows.append([timestamp, x, y, z])
except ValueError:
continue
return sensor_rows
def process_input(data):
t_series = []
x_series = []
y_series = []
z_series = []
mag_series = []
for row in data:
# Get t at index in row
t = row[0]
x = row[1]
y = row[2]
z = row[3]
# Add to Series
t_series.append(t)
x_series.append(x)
y_series.append(y)
z_series.append(z)
mag_series.append(sp.get_magnitude(x, y, z))
numpymag = np.array(mag_series)
return numpymag
def window_data(data):
length = len(data)
# first 2/3rds of recording
endpoint = length / 10
endpoint *= 7
startpoint = endpoint - 100
return data[startpoint:endpoint]
def write_to_csv(data, filename):
import csv
# Get headers from dictionary
header = []
example = data[0]
for key, value in example.items():
header.append(key)
with open(str(filename) + '.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=sorted(header))
writer.writeheader()
for item in data:
writer.writerow(item)
def plot_against(missed, acknowledged):
sensor_miss = import_sensorfile(missed)
sensor_ack = import_sensorfile(acknowledged)
# Window data
mag_miss = window_data(process_input(sensor_miss))
mag_ack = window_data(process_input(sensor_ack))
# Filter setup
kernel = 15
# apply filter
mag_miss_filter = sci.medfilt(mag_miss, kernel)
mag_ack_filter = sci.medfilt(mag_ack, kernel)
# calibrate data
mag_miss_cal = mf.calibrate_median(mag_miss)
mag_miss_cal_filter = mf.calibrate_median(mag_miss_filter)
mag_ack_cal = mf.calibrate_median(mag_ack)
mag_ack_cal_filter = mf.calibrate_median(mag_ack_filter)
# PLOT
ylimit_top = [-5, 10]
ylimits_filtered = [-4, 4]
ylimits_filtered_bottom = [-1.5, 1.5]
sns.set_style("darkgrid")
current_palette = sns.color_palette('muted')
sns.set_palette(current_palette)
plt.figure(0)
# Plot RAW missed and acknowledged reminders
ax1 = plt.subplot2grid((4, 2), (0, 0), colspan=2)
plt.ylim(ylimit_top)
raw_miss = plt.plot(mag_miss_cal, label='Missed (Unfiltered)')
raw_ack = plt.plot(mag_ack_cal, label='Acknowledged (Unfiltered)')
plt.legend(loc='upper left')
ax2 = plt.subplot2grid((4, 2), (1, 0))
# Plot Missed Reminder RAW
plt.ylim(ylimits_filtered)
plt.plot(mag_miss_cal, linestyle='-', label='Unfiltered')
plt.legend(loc='lower left')
ax3 = plt.subplot2grid((4, 2), (1, 1))
# Plot Acknow Reminder RAW
plt.ylim(ylimits_filtered)
plt.plot(mag_ack_cal, linestyle='-', label='Unfiltered')
plt.legend(loc='lower left')
ax4 = plt.subplot2grid((4, 2), (2, 0))
# Plot Missed Reminder Filter
plt.ylim(ylimits_filtered)
plt.plot(mag_miss_cal, linestyle=':', label='Unfiltered')
plt.plot(mag_miss_cal_filter, linestyle='-', label='Median Filter (k=' + str(kernel) + ')')
plt.legend(loc='lower left')
ax5 = plt.subplot2grid((4, 2), (2, 1))
# Plot Acknow Reminder Filter
plt.ylim(ylimits_filtered)
plt.plot(mag_ack_cal, linestyle=':', label='Unfiltered')
plt.plot(mag_ack_cal_filter, linestyle='-', label='Median Filter (k=' + str(kernel) + ')')
plt.legend(loc='lower left')
ax6 = plt.subplot2grid((4, 2), (3, 0), colspan=2)
plt.ylim(ylimits_filtered_bottom)
plt.style.use('grayscale')
plt.plot(mag_miss_cal_filter, label='Missed (Filtered)')
plt.plot(mag_ack_cal_filter, label='Acknowledged (Filtered)')
plt.legend(loc='lower left')
plt.suptitle("Applying Filters to Signals")
plt.show()
def plot_singlewave(file):
sensor = import_sensorfile(file)
sensor_processed = process_input(sensor)
timestamps = []
[timestamps.append(str(item[0])) for item in sensor]
sensor_processed_calibrated = mf.calibrate_median(sensor_processed)
sensor_filtered = mf.medfilt(sensor_processed_calibrated, 3)
plt.plot(sensor_filtered, linewidth='0.8')
plt.xlim([0, 12000])
plt.ylim([-5, 5])
plt.ylabel('Acceleration (g)')
plt.xlabel('Time (ms)')
# plt.xticks(sensor_filtered, timestamps, rotation='vertical')
plt.show()
def plot_example(missed, acknowledged):
sensor_miss = import_sensorfile(missed)
sensor_ack = import_sensorfile(acknowledged)
# Window data
mag_miss = window_data(process_input(sensor_miss))
mag_ack = window_data(process_input(sensor_ack))
# Window data
mag_miss = window_data(process_input(sensor_miss))
mag_ack = window_data(process_input(sensor_ack))
# Filter setup
kernel = 15
# apply filter
mag_miss_filter = sci.medfilt(mag_miss, kernel)
mag_ack_filter = sci.medfilt(mag_ack, kernel)
# calibrate data
mag_miss_cal = mf.calibrate_median(mag_miss)
mag_miss_cal_filter = mf.calibrate_median(mag_miss_filter)
mag_ack_cal = mf.calibrate_median(mag_ack)
mag_ack_cal_filter = mf.calibrate_median(mag_ack_filter)
# PLOT
sns.set_style("white")
current_palette = sns.color_palette('muted')
sns.set_palette(current_palette)
plt.figure(0)
# Plot RAW missed and acknowledged reminders
ax1 = plt.subplot2grid((2, 1), (0, 0))
plt.ylim([-1.5, 1.5])
plt.ylabel('Acceleration (g)')
plt.plot(mag_miss_cal, label='Recording 1')
plt.legend(loc='lower left')
ax2 = plt.subplot2grid((2, 1), (1, 0))
# Plot Missed Reminder RAW
plt.ylim([-1.5, 1.5])
plt.ylabel('Acceleration (g)')
plt.xlabel('t (ms)')
plt.plot(mag_ack_cal, linestyle='-', label='Recording 2')
plt.legend(loc='lower left')
# CALC AND SAVE STATS
stats_one = sp.calc_stats_for_data_stream_as_dictionary(mag_miss_cal)
stats_two = sp.calc_stats_for_data_stream_as_dictionary(mag_ack_cal)
data = [stats_one, stats_two]
write_to_csv(data, 'example_waves')
plt.show()
def plot_kernal_length_experiment(missed, acknowledged):
sensor_miss = import_sensorfile(missed)
sensor_ack = import_sensorfile(acknowledged)
# Window data
mag_miss = window_data(process_input(sensor_miss))
mag_ack = window_data(process_input(sensor_ack))
# Filter setup
difference = []
stats_output = []
for num in range(3, 63):
# check if odd
if num % 2 != 0:
kernel = num
# apply filter
mag_miss_filter = sci.medfilt(mag_miss, kernel)
mag_ack_filter = sci.medfilt(mag_ack, kernel)
# calibrate data
mag_miss_cal = mf.calibrate_median(mag_miss)
mag_miss_cal_filter = mf.calibrate_median(mag_miss_filter)
mag_ack_cal = mf.calibrate_median(mag_ack)
mag_ack_cal_filter = mf.calibrate_median(mag_ack_filter)
# STATS
# Calculate the stats for raw and windowed for each
stats_miss = sp.calc_stats_for_data_stream_as_dictionary(mag_miss_cal)
stats_miss_filter = sp.calc_stats_for_data_stream_as_dictionary(mag_miss_cal_filter)
stats_ack = sp.calc_stats_for_data_stream_as_dictionary(mag_ack_cal)
stats_ack_filter = sp.calc_stats_for_data_stream_as_dictionary(mag_ack_cal_filter)
stats_data = [stats_miss, stats_miss_filter, stats_ack, stats_ack_filter]
[data.pop("med", None) for data in stats_data]
print('Stats Missed:' + str(stats_miss))
print('Stats Acknowledged: ' + str(stats_ack))
print('Stats Missed Filtered: ' + str(stats_miss_filter))
print('Stats Acknowledged Filtered:' + str(stats_ack_filter))
# Calculate the percentage difference between the values
dif_stats_raw = calculate_difference(stats_miss, stats_ack)
dif_stats_filtered = calculate_difference(stats_miss_filter, stats_ack_filter)
print('Difference in RAW as percentage:' + str(dif_stats_raw))
print('Difference in FILTERED as percentage:' + str(dif_stats_filtered))
dif_stats_raw_overall = calcualate_meanfordictionary(dif_stats_raw)
dif_stats_filtered_overall = calcualate_meanfordictionary(dif_stats_filtered)
print('Avg. Difference RAW: ' + str(dif_stats_raw_overall))
print('Avg. Difference Filtered: ' + str(dif_stats_filtered_overall))
difference.append((kernel, dif_stats_filtered_overall))
if kernel == 15:
stats_output.append(stats_miss)
stats_output.append(stats_ack)
stats_output.append(stats_miss_filter)
stats_output.append(stats_ack_filter)
stats_output.append(dif_stats_raw)
stats_output.append(dif_stats_filtered)
write_to_csv(stats_output)
x_val = [x[0] for x in difference]
y_val = [x[1] for x in difference]
xticks = [str(x) for x in x_val]
base_val = [54] * 63
plt.xticks(x_val, xticks)
plt.xlabel('Window Length (k)')
plt.ylabel('Percentage Difference (%)')
plt.ylim([40, 140])
plt.plot(x_val, y_val, label='Median Filter')
plt.plot(base_val, linestyle='--', label='Baseline (Unfiltered)')
plt.legend(loc='lower right')
plt.show()
# plot_against(csv_missed, csv_acknowledged)
# plot_kernal_length_experiment(csv_missed, csv_acknowledged)
# plot_example(csv_missed, csv_acknowledged)
# plot_singlewave(csv_acknowledged)