/
intentionClassifier.py
373 lines (286 loc) · 13.4 KB
/
intentionClassifier.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
"""
Author: Kevin Ta
Date: 2021 March 13th
Purpose: This Python script tests terrain classification by passing streamed data.
"""
# IMPORTED LIBRARIES
import os
import sys
import threading
import time
from multiprocessing import Process, Queue
from threading import Thread
import pandas as pd
from joblib import load, dump
from scipy import signal
from sklearn.metrics import accuracy_score, balanced_accuracy_score
# LOCALLY IMPORTED LIBRARIES
dir_path = os.path.dirname(os.path.realpath(__file__))
# from WheelModuleLib import *
from featuresLib import *
# DEFINITIONS
# Classification frequency
CLASS_DELAY = 0.2 # in s
# Direction Vectors
DATA_COLUMNS = ['Torque_L', 'Torque_R', 'Torque_sum', 'Torque_diff', 'Torque_L_roc', 'Torque_R_roc']
EPSILON = 0.00001 # For small float values
# filter parameters
PAD_LENGTH = 10 # pad length to let filtering be better
# DICTIONARIES
INTENTIONS_DICT = [
('Mahsa', 'Obstacles15', 'T1'),
('Mahsa', 'Obstacles35', 'T3'),
('Mahsa', 'RampA', 'T1'),
('Mahsa', 'StraightF', 'T2'),
('Mahsa', 'Turn90FL', 'T2'),
('Mahsa', 'Turn90FR', 'T1'),
('Mahsa', 'Turn180L', 'T2'),
('Mahsa', 'Turn180R', 'T2'),
# ('Jaimie', 'Obstacles15', 'T3'),
# ('Jaimie', 'Obstacles35', 'T3'),
# ('Jaimie', 'RampA', 'T3'),
# ('Jaimie', 'StraightF', 'T3'),
# ('Jaimie', 'Turn90FL', 'T3'),
# ('Jaimie', 'Turn90FR', 'T3'),
# ('Jaimie', 'Turn180L', 'T3'),
# ('Jaimie', 'Turn180R', 'T3'),
]
# Time domain feature functions and names
TIME_FEATURES = {'Mean': np.mean, 'Std': np.std,
'Max': np.amax, 'Min': np.amin, 'RMS': rms}
# TIME_FEATURES_NAMES = ['Mean', 'Std', 'Norm', 'AC', 'Max', 'Min', 'RMS', 'ZCR', 'Skew', 'EK']
TIME_FEATURES_NAMES = ['Mean', 'Std', 'Max', 'Min', 'RMS']
# Different data sets
SENSOR_MODULE = {'wLength': 32, 'fSamp': 240, 'fLow': 5, 'fHigh': 1}
PERFORMANCE = {}
# CLASSES
class ClIntentionDetector:
"""
Class for establishing wireless communications.
"""
def __init__(self, testSet, protocol='TCP'):
"""
Purpose: Initialize various sensors and class variables
Passed: Nothing
"""
self.testSet = testSet
self.sensorParam = SENSOR_MODULE
print('unpickling')
self.RFTimelinePipeline = load('models/modelRFKinetic.joblib')
self.RFResults = pd.DataFrame(columns=["Time", "Cluster 1", "Cluster 2", "Cluster 3", "Cluster 4",
"Cluster 5", "Cluster 6", "Torque L", "Torque R"])
# Prepopulate pandas dataframe
EFTimeColumnNames = ['{} {}'.format(featName, direction) for direction in DATA_COLUMNS for
featName in TIME_FEATURES_NAMES]
self.EFTimeColumnedFeatures = pd.DataFrame(data=np.zeros((1, len(EFTimeColumnNames))),
columns=EFTimeColumnNames)
self.protocol = protocol
# Initialize data queue and marker to pass for separate prcoesses
self.dataQueue = Queue()
self.runMarker = Queue()
# Create class variables
self.windowIMUraw = np.zeros((self.sensorParam['wLength'] + 2 * PAD_LENGTH, 6))
self.windowIMUfiltered = np.zeros((self.sensorParam['wLength'], len(DATA_COLUMNS)))
# Instantiate sensor information retrieval
self.instDAQLoop = ClSensorDataStream(self.sensorParam['fSamp'], self.dataQueue, self.runMarker, self.testSet)
def fnStart(self):
"""
Purpose: Intialize all active sensors in separate processed and collects data from the Queue
Passed: Frequency for 6-axis IMU to operate at
"""
print('Start Process.')
# Start terrain classification in separate thread
intention = Thread(target=self.fnIntentionDetection, args=(CLASS_DELAY,))
intention.start()
# Start various data collection sensors
processDAQLoop = Process(target=self.instDAQLoop.fnRun)
processDAQLoop.start()
# Keep collecting data and updating rolling window
while self.runMarker.empty():
try:
transmissionData = self.dataQueue.get(timeout=2)
self.windowIMUraw = np.roll(self.windowIMUraw, -1, axis=0)
self.windowIMUraw[-1, :] = transmissionData[:]
except Exception as e:
print('Exception: {}'.format(e))
# wait for all processes and threads to complete
intention.join()
print("Intention detector joined.")
print("Sensor loop joining.")
processDAQLoop.join()
print("Sensor loop joined.")
def fnIntentionDetection(self, waitTime):
"""
Purpose: Class method for running terrain classification
Passed: Time in between runs
"""
count = 0
startTime = time.time()
# Keep running until run marker tells to terminate
while self.runMarker.empty():
# time.sleep(waitTime - (time.perf_counter() % waitTime))
count += 1
# Filter window
self.fnFilterButter(self.windowIMUraw)
# Build extracted feature vector
self.fnBuildTimeFeatures(TIME_FEATURES_NAMES)
# intentionRFTime = self.RFTimelinePipeline.predict(self.EFTimeColumnedFeatures)
intentionRFTime = self.RFTimelinePipeline.predict_proba(self.EFTimeColumnedFeatures)
try:
# print('Prediction: {}'.format(intentionRFTime))
self.RFResults = self.RFResults.append({"Cluster 1": intentionRFTime[0, 0],
"Cluster 2": intentionRFTime[0, 1],
"Cluster 3": intentionRFTime[0, 2],
"Cluster 4": intentionRFTime[0, 3],
"Cluster 5": intentionRFTime[0, 4],
"Cluster 6": intentionRFTime[0, 5],
"Torque L": self.EFTimeColumnedFeatures['Mean Torque_L'][0],
"Torque R": self.EFTimeColumnedFeatures['Mean Torque_R'][0],
"Time": time.time()},
ignore_index=True)
except Exception as e:
print("Exception: {}".format(e))
break
endTime = time.time()
print("Classification Frequency: {:>8.2f} Hz. ({} Samples in {:.2f} s)".format(count / (endTime - startTime),
count, (endTime - startTime)))
print("Intention Detection completed.")
PERFORMANCE["{}-{}-{}-Classification".format(
self.sensorParam['wLength'], self.testSet[1], self.testSet[0])] = (count, endTime - startTime)
self.RFResults.to_csv(
os.path.join('2021-Results',
"{:.0f}Hz-{}-{}-{}.csv".format(self.sensorParam['fSamp'], self.sensorParam['wLength'],
self.testSet[1], self.testSet[0])))
print('Saved.')
def fnShutDown(self):
print('Closing Socket')
self.socket.close()
try:
self.sock.close()
except Exception as e:
print(e)
def fnFilterButter(self, dataWindow):
"""
Purpose: Low pass butterworth filter onto rolling window and
stores in filtered class variable
Applies hanning window
Passed: Rolling raw IMU data
"""
# Get normalized frequencies
w_low = 2 * self.sensorParam['fLow'] / self.sensorParam['fSamp']
# Get Butterworth filter parameters
sos = signal.butter(N=2, Wn=w_low, btype='low', output='sos')
dataSet = np.copy(dataWindow)
torqueL = signal.sosfiltfilt(sos, dataSet[:, 4])
torqueR = signal.sosfiltfilt(sos, dataSet[:, 5])
self.windowIMUfiltered[:, 0] = torqueL[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH]
self.windowIMUfiltered[:, 1] = torqueR[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH]
self.windowIMUfiltered[:, 2] = torqueL[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH] + \
torqueR[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH]
self.windowIMUfiltered[:, 3] = torqueR[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH] - \
torqueL[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH]
self.windowIMUfiltered[:, 4] = (torqueL[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH] -
torqueL[PAD_LENGTH - 1:self.sensorParam['wLength'] + PAD_LENGTH - 1])
self.windowIMUfiltered[:, 5] = (torqueR[PAD_LENGTH:self.sensorParam['wLength'] + PAD_LENGTH] -
torqueR[PAD_LENGTH - 1:self.sensorParam['wLength'] + PAD_LENGTH - 1])
def fnBuildTimeFeatures(self, features):
"""
Purpose: Perform all time domain feature extraction on filtered data,
then columns the data
Passed: Feature dictionary to perform
"""
dataList = [TIME_FEATURES[featName](self.windowIMUfiltered[:, i]) for i, direction in enumerate(DATA_COLUMNS)
for featName in features]
dataNames = ['{} {}'.format(featName, direction) for direction in DATA_COLUMNS for featName
in features]
self.EFTimeColumnedFeatures = pd.DataFrame(data=[dataList], columns=dataNames)
class ClSensorDataStream(threading.Timer):
"""
Class for establishing wireless communications.
"""
def __init__(self, frequency, dataQueue, runMarker, testSet):
self.testSet = testSet
self.streamFile = pd.read_excel(
os.path.join(dir_path, "Trimmed_Data", testSet[0],
"{}_{}.xls".format(testSet[1], testSet[2])))
self.streamRow = 0
self.streamRowEnd = len(self.streamFile.index)
self.dataQueue = dataQueue
self.runMarker = runMarker
self.frequency = frequency
self.data = np.zeros(2)
self.data_prev = np.zeros(2)
def fnRetrieveData(self):
"""
Purpose: Send data to main data queue for transfer with timestamp and sensor ID.
Passed: None
"""
timeRecorded = time.time()
if self.streamRow < self.streamRowEnd:
self.data = self.streamFile.iloc[self.streamRow, 1:7]
self.dataQueue.put([self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5]])
self.data_prev = self.data
self.streamRow += 1
else:
self.runMarker.put(False)
def fnRun(self):
"""
Purpose: Script that runs until termination message is sent to queue.
Passed: Frequency of data capture
"""
# Sets time interval between signal capture
waitTime = 1 / self.frequency
# Sets trigger so code runs
self.trigger = threading.Event()
self.trigger.set()
# Create repeating timer that ensures code runs at specified intervals
timerRepeat = threading.Thread(target=self.fnRunThread, args=(waitTime,))
timerRepeat.start()
count = 0
startTime = time.time()
# Continuously reruns code and clears the trigger
while self.runMarker.empty():
count += 1
self.trigger.wait()
self.trigger.clear()
self.fnRetrieveData()
endTime = time.time()
print("Sampling Frequency: {:>8.2f} Hz. ({} Samples in {:.2f} s)".format(count / (endTime - startTime),
count, (endTime - startTime)))
# Joins thread
timerRepeat.join()
def fnRunThread(self, waitTime):
"""
Purpose: Sets the trigger after waiting for specified interval
Passed: Interval of time to wait
"""
while self.runMarker.empty():
time.sleep(waitTime - (time.perf_counter() % waitTime))
self.trigger.set()
# MAIN PROGRAM
if __name__ == "__main__":
for testSet in INTENTIONS_DICT:
connectedStatus = False
processStatus = False
runCompletion = False
while runCompletion == False:
try:
instIntentionDetector = ClIntentionDetector(testSet, protocol='TCP')
processStatus = True
instIntentionDetector.fnStart()
instIntentionDetector.runMarker.close()
instIntentionDetector.dataQueue.close()
print("Application Completed.")
runCompletion = True
except Exception as e:
time.sleep(1)
if processStatus:
instIntentionDetector.runMarker.put(False)
instIntentionDetector.fnShutDown()
instIntentionDetector.runMarker.close()
instIntentionDetector.dataQueue.close()
connectedStatus = False
print(e)
print(PERFORMANCE)
os.makedirs(os.path.join(dir_path, '2021-Results'), exist_ok=True)
dump(PERFORMANCE, os.path.join(dir_path, '2021-Results', 'performance.joblib'))