-
Notifications
You must be signed in to change notification settings - Fork 0
/
SafetyMomentManagerOld.py
334 lines (254 loc) · 11.8 KB
/
SafetyMomentManagerOld.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
import time
import numpy as np
from AngleManager import AngleManager
import os
from MomentManager import MomentManager
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import os
from MutliprocessPlot import MutliprocessPlot
from multiprocessing import Pipe
import scipy.signal
sns.set_style('whitegrid')
class SafetyMomentManager:
def __init__(self, userName, momentManager, angelManager, sampleRate=20, autoPlot = False, savePath = './data', safetyRate = 3.5):
'''
userName: The User Name
sampleRate: Hz, the value must less than 4, because of the momentManager have the limited rate
'''
self.userName = userName
self.sampleRate = sampleRate
self.autoPlot = autoPlot
self.momentManager = momentManager
self.angelManager = angelManager
self.savaPath = savePath
self.safetyRate = safetyRate
self.minMoment = np.array([-10000, -10000, -10000, -10000])
self.maxMoment = np.array([10000, 10000, 10000, 10000, ])
self.main_conn, self.plot_conn = Pipe()
self.plotProcess = MutliprocessPlot(self.plot_conn, drawSize=100, bound=[-60, 60])
self.plotProcess.SetStatus(True)
def Update(self, data):
'''
update the safety moment data
'''
data[8:] *= self.safetyRate
self.main_conn.send(data)
def DetectMoment(self):
'''
detect the moment is safe or not
'''
angelList = []
momentList = None
idxList = []
indx = 0
if self.SafetyMoment is None:
print("You have not record the raw data, please record the raw data first!")
return
try:
print('detecting...')
while True:
indx += 1
moment = self.momentManager.GetAllMoments()[0]
angel = self.angelManager.getInfo()
if angel[2] == 1:
checkResult, idx = self.CheckMoment(np.hstack((moment, angel[1])))
idxList.append(idx)
tempdata = np.hstack((moment, self.SafetyMoment[idx, 0:8]))
if type(momentList) != type(np.array([[1,2,3,4]])):
momentList = tempdata.reshape(1, 12)
else:
momentList = np.vstack((momentList, tempdata))
angelList.append(angel[1])
if not checkResult:
self.angelManager.emergencyStopButton()
print('Emergency Stop!')
self.plotMomentList(momentList[-400:])
break
# return
# Send Data to plot process
self.Update(tempdata)
else:
print('angel paresed failed!')
except KeyboardInterrupt:
print("Program Terminated!")
finally:
angelList = np.array(angelList)
angelList = np.reshape(angelList, (len(angelList), 1))
print(momentList.shape, angelList.shape)
np.save('./data/detect_' + self.userName + time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) + '.npy', np.hstack((momentList, angelList)))
def CheckMoment(self, momentAndAngel):
'''
check the moment is safe or not
'''
momentAndAngel = momentAndAngel.reshape(1, momentAndAngel.shape[0])
idx = np.abs(self.SafetyMoment[:, -1] - momentAndAngel[:, -1]).argmin()
for i in range(4):
if abs(self.SafetyMoment[idx, i] - momentAndAngel[0, i]) > self.safetyRate * self.SafetyMoment[idx, 4+i]:
return False, idx
return True, idx
def SimpleCheckMoment(self, momentAndAngel):
dangerousRate = 10
if max(self.maxMoment) > 9999 or min(self.minMoment) < -9999:
self.maxMoment = np.max(self.rawMomentData, axis=0)
self.minMoment = np.min(self.rawMomentData, axis=0)
if (momentAndAngel[:4] > dangerousRate + self.maxMoment).any() or (momentAndAngel[:4] < self.minMoment - dangerousRate).any():
return False, 0
return True, 0
def plotMomentList(self, momentList):
color = cm.viridis(0.7)
plt.subplot(221)
plt.plot(momentList[:, 0])
plt.plot(momentList[:, 4], color = color)
plt.fill_between(range(len(momentList[:, 0])), momentList[:, 4] + self.safetyRate * momentList[:, 8], momentList[:, 4] - self.safetyRate * momentList[:, 8], color=color, alpha=0.2)
plt.title('left hip')
plt.subplot(223)
plt.plot(momentList[:, 1])
plt.plot(momentList[:, 5], color = color)
plt.fill_between(range(len(momentList[:, 0])), momentList[:, 5] + self.safetyRate * momentList[:, 9], momentList[:, 5] - self.safetyRate * momentList[:, 9], color=color, alpha=0.2)
plt.title('left knee')
plt.subplot(222)
plt.plot(momentList[:, 2])
plt.plot(momentList[:, 6], color = color)
plt.fill_between(range(len(momentList[:, 0])), momentList[:, 6] + self.safetyRate * momentList[:, 10], momentList[:, 6] - self.safetyRate * momentList[:, 10], color=color, alpha=0.2)
plt.title('right hip')
plt.subplot(224)
plt.plot(momentList[:, 3])
plt.plot(momentList[:, 7], color = color)
plt.fill_between(range(len(momentList[:, 0])), momentList[:, 7] + self.safetyRate * momentList[:, 11], momentList[:, 7] - self.safetyRate * momentList[:, 11], color=color, alpha=0.2)
plt.title('right knee')
plt.show()
def plotPic(self):
'''
plot the safety moment data
'''
color = cm.viridis(0.7)
f, ax = plt.subplots(1,1)
ax.plot(range(len(self.SafetyMoment[:, 0])), self.SafetyMoment[:, 0], color=color)
r1 = list(map(lambda x: x[0]-x[1], zip(self.SafetyMoment[:, 0], self.SafetyMoment[:, 4])))
r2 = list(map(lambda x: x[0]+x[1], zip(self.SafetyMoment[:, 0], self.SafetyMoment[:, 4])))
ax.fill_between(range(len(self.SafetyMoment[:, 0])), r1, r2, color=color, alpha=0.2)
plt.show()
# TODO: maybe the 5 should changed
def GetSafetyMoment(self):
# path = './data/' + self.userName + '_Safety.npy'
path = self.savaPath + '/combinedData.npy'
if os.path.exists(path):
choise = input("Found Existing Safety Data, Do you want to load from existing data?[y]/n:")
if choise == '' or choise == 'y' or choise == 'Y':
self.SafetyMoment = np.load(path)
# self.plotPic()
for i in range(1, self.SafetyMoment.shape[0]):
for j in range(4):
if self.SafetyMoment[i, 4+j] < 2:
# self.SafetyMoment[i, 4+j] = self.SafetyMoment[i - 1, 4+j]
self.SafetyMoment[i, 4+j] = 2
for i in range(8):
self.SafetyMoment[:, i] = scipy.signal.savgol_filter(self.SafetyMoment[:, i], 101, 3)
# np.save(self.savaPath + '/filterData.npy', self.SafetyMoment)
else:
self.SafetyMoment = self._ProcessRawSafetyMoment()
else:
input("You will record the raw data, press any key to continue...press CTRL-C to terminate")
self.SafetyMoment = self._ProcessRawSafetyMoment()
# TODO
def _ProcessRawSafetyMoment(self):
'''
process raw safety moment data to get the final safety moment data throught Least squares method
'''
rawMomentData, rawAngleData = self._RecordRawSafetyMoment()
self.rawMomentData = rawMomentData
self.rawAngleData = rawAngleData
assert(len(rawAngleData) == len(rawMomentData))
rawAngleData = rawAngleData.reshape(rawAngleData.shape[0], 1)
combinedData = np.hstack((rawMomentData, rawAngleData))
print(combinedData)
combinedData = combinedData[combinedData[:, -1].argsort()]
lastValue = combinedData[0, -1]
sumValue = combinedData[0, 0:4].reshape(1,4)
avarageSafetyMoment = []
for i in range(1, combinedData.shape[0]):
if abs(combinedData[i, -1] - lastValue) < 0.01:
sumValue = np.vstack((sumValue, combinedData[i, 0:4]))
else:
avarag = np.mean(sumValue, axis=0)
var = np.std(sumValue, axis=0)
avarageSafetyMoment.append(np.hstack((avarag, var, lastValue)))
lastValue = combinedData[i, -1]
sumValue = combinedData[i, 0:4].reshape(1,4)
combinedData = np.array(avarageSafetyMoment)
for i in range(1, combinedData.shape[0]):
for j in range(4):
if combinedData[i, 4+j] < 4:
# self.SafetyMoment[i, 4+j] = self.SafetyMoment[i - 1, 4+j]
combinedData[i, 4+j] = 4
for i in range(8):
combinedData[:, i] = scipy.signal.savgol_filter(combinedData[:, i], 51, 3)
# print(combinedData)
np.save(self.savaPath + '/combinedData.npy', combinedData)
return combinedData
def _RecordRawSafetyMoment(self):
'''
record angle and moment
'''
timeDuration = 1.0 / self.sampleRate
momentData = []
angleData = []
timeLong = input("Please input how long you want to record,[60](s):")
if timeLong == "":
timeLong = "60"
timeLong = int(timeLong)
try:
if self.autoPlot:
plt.figure(1)
recordStartTime = time.time()
while(1):
if self.autoPlot:
plt.clf()
startTime = time.time()
moment = self.momentManager.GetAllMoments()
angel = self.angelManager.getInfo()
if angel[2] == 1:
momentData.append(moment[0])
angleData.append(angel[1])
else:
print('angel paresed failed!', angel)
endTime = time.time()
assert(endTime - startTime <= timeDuration)
# print('time stop: ', timeDuration - (endTime - startTime))
time.sleep(timeDuration - (endTime - startTime))
if self.autoPlot:
plt.plot(momentData[-100:])
plt.pause(0.01)
if time.time() - recordStartTime > timeLong:
break
print("used %.3f, remains: %.3f"%( endTime - startTime, timeLong - time.time() + recordStartTime))
except KeyboardInterrupt:
print("End the Record!")
np.save('rawdata_' + self.userName + time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) + '.npy', momentData, angleData)
return np.array(momentData), np.array(angleData)
if __name__ == "__main__":
angleManagerPort = input("Please input angel manager port (like \"com8\"): ")
if angleManagerPort == "":
angleManagerPort = "com3"
momentManagerPort = input("Please input moment manager port (like \"com3\"): ")
if momentManagerPort == "":
momentManagerPort = "com4"
momentManager = MomentManager(momentManagerPort)
angelManager = AngleManager(angleManagerPort)
# momentManager = 1
# angelManager = 2
smm = SafetyMomentManager(
'dyj',
sampleRate=35,
autoPlot = False,
momentManager = momentManager,
angelManager = angelManager,
safetyRate=4
)
angelManager.autoStartWalk()
smm.GetSafetyMoment()
# smm.plotPic()
smm.DetectMoment()