/
ACRL-two-old.py
474 lines (360 loc) · 14.7 KB
/
ACRL-two-old.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# coding: utf-8
# In[6]:
# get_ipython().magic(u'matplotlib inline')
# In[7]:
# import matplotlib.pyplot as plt
import numpy as np
import time
import math
from collections import Counter
from tqdm import tqdm
from joblib import Parallel, delayed
import multiprocessing
import sys
import tiles
num_cores = multiprocessing.cpu_count()
print("numCores = " + str(num_cores))
# In[8]:
# plt.xkcd() # Yes...
tmax = 3000
phase1maxT = 300000
phase2maxT = phase1maxT + 300000
t = tmax*np.linspace(0, 1, tmax, endpoint=False)
# Define the target angles
targetAngles = np.zeros((tmax,2))
for i in range(0, tmax, 4000):
targetAngles[i:i+1000,0] = 0.5
targetAngles[i+1000:i+2000,0] = 1
targetAngles[i+2000:i+3000,0] = 1.5
targetAngles[i+3000:i+4000,0] = 1
targetAngles[i:i+1000,1] = -3
targetAngles[i+1000:i+2000,1] = -1.5
targetAngles[i+2000:i+3000,1] = 0
targetAngles[i+3000:i+4000,1] = -1.5
angleMins = np.amin(targetAngles, 0)
angleMaxs = np.amax(targetAngles, 0)
# Two subplots, unpack the axes array immediately
# plt.figure(figsize=(40,40))
# f, ax1 = plt.subplots(1, 1, sharey=False)
# ax1.set_ylim(-4,2)
# ax1.plot(t, targetAngles)
# ax1.set_title('Target Joint Signals')
# In[ ]:
delay = 0
# Noise is defined by a random normal variable
noise = np.random.normal(0,0.001,(tmax,2))
simEMG = np.zeros((tmax+delay,2))
for i in range(1,tmax):
if targetAngles[i,0] == 1:
simEMG[i + delay,0] = -1
simEMG[i + delay,1] = 1
elif targetAngles[i,0] < 1:
simEMG[i + delay,0] = 0
simEMG[i + delay,1] = 0
elif targetAngles[i,0] > 1:
simEMG[i + delay,0] = 1
simEMG[i + delay,1] = -1
simEMGdiff = simEMG[0:tmax, :] # + noise
emgMins = np.amin(simEMGdiff, 0)
emgMaxs = np.amax(simEMGdiff, 0)
# plt.figure(figsize=(40,40))
# f, ax2 = plt.subplots(1, 1, sharey=False)
# ax2.plot(t, simEMGdiff)
# ax2.set_ylim(-1.5, 1.5)
# ax2.set_title('Simulated Noisy EMG Signal')
# In[ ]:
# Implement a learning algorithm to try to fit the signal
numJoints = 1
numEMG = 1
jointAngle = np.zeros((tmax, numJoints))
# Initialize the state array for the trajectory
# Possible feedback from the simulated arm includes the angle
# (in radians) and angular velocity (in radians per second) of
# each joint, and the Cartesian position of the end effector.
# Initialize the continuous state space
# composed of joint angles (thetaW,thetaE)
# and differential EMG signals (dS1,dS2)
# thetaW, thetaE, dS1, dS2
s = np.zeros(numJoints+numEMG)
# Grab the initial values of the state space
# TODO: make sure this is valuable
s = np.hstack((targetAngles[0, :numJoints], simEMG[0, :numEMG]))
# Standard deviation should cover the possible action set
maxAngVelInt_stdC = 1023
# Initialize the saved variables
reward = np.zeros(tmax)
delta = np.zeros(tmax)
agentMean = np.zeros((tmax,numJoints))
agentStd = np.zeros((tmax,numJoints))
# define the number of tilings
numTilings = 25 # 5 25
# this defines the resolution of the tiling
resolutions = np.array([5, 8, 12, 20]) # resolutions = np.array([5,8,12,20])
numFeatures = len(s)
# Initialize the learning parameters
# m is the number of active features in the feature vector
m = numTilings * len(resolutions) + 1
gamma = 0.92 # 0.97
lambd = 0.3
# Different values for the 2013 paper
lambdw = 0.3
lambdv = lambdw # 0.7
alphaV = 0.1/m
alphaW = 0.01/m
alphaU = alphaW # 0.005/m # 0.01/m
alphaS = alphaW # 0.25*alphaU # 0.01/m #
# Actual length is the concatenation at different resolutions
# and the baseline feature
featVecLength = sum(np.power(resolutions, numFeatures)*numTilings)+1
# Initialize the weight vectors to zero
# the should be as long as the feature vector x
elV = np.zeros(featVecLength)
v = np.zeros(featVecLength)
elU = np.zeros((featVecLength,numJoints))
elS = np.zeros((featVecLength,numJoints))
wU = np.zeros((featVecLength,numJoints))
wS = np.zeros((featVecLength,numJoints))
# This function converts the angular velocity from an integer in the range [-1023,1023]
# to an angular velocity in radians per second.
# The no-load speed of the motor is ~60RPM, which is around 6 radians per second
# rad/s = rot(RPM) 2*pi/60
# This should give a good simulation of the true robotic kinematics
def conAngIntToangVel(angInt):
motorVel = 60
angVel = motorVel * angInt / maxAngVelInt_stdC
return angVel
def normsingle(val, oldmin, oldmax, newmin, newmax):
return (((val - oldmin) * (newmax - newmin)) / (oldmax - oldmin)) + newmin
def normalize(state):
# Normalize the state value given the maximum and minimum possible values
# All components in s were normalized to the range [0, 1]
# according to their minimum and maximum POSSIBLE VALUES!
sMins = np.concatenate((angleMins[:numJoints], emgMins[:numEMG]))
sMaxs = np.concatenate((angleMaxs[:numJoints], emgMaxs[:numEMG]))
# define the normalization constant
nct = 0.5
return Parallel(n_jobs=num_cores)(delayed(normsingle)(state[j], sMins[j]-nct, sMaxs[j]+nct, 0, 1) for j in range(len(state)))
def getfeatvec(res, normS):
scalednormS = [x * res for x in normS]
# x is the active tiles in this featurization
# This featurization should return a single binary feature vector
# with exactly m features in x(s) active at any time
# Binary feature vector has a length of 4636426 or
# sum(np.power(np.array([5,8,12,20]),4)*25)+1
x = np.zeros(np.power(res, numFeatures)*numTilings)
tilesOut = tiles.tiles(numTilings, res, scalednormS)
for idx, val in enumerate(tilesOut):
# for each tile index put out by the tile coder
# we need to flip a bit in the feature vector
# this bit index is given by the value of the tile from the tile coder
# the index this value was at, the resolution of the tile
x[val + (res**2 * idx)] = 1
return x
def featurize(s):
normS = normalize(s)
featvecs = Parallel(n_jobs=num_cores)(delayed(getfeatvec)(resolutions[res], normS) for res in range(len(resolutions)))
# Concatenate the feature vectors and add
# Single active baseline unit
catfeat = np.hstack(featvecs)
catfeat = np.hstack((0, catfeat))
print catfeat[0]
print len(catfeat)
print sum(np.power(np.array(resolutions), numFeatures)*numTilings)+1
# For each resolution the features are needed
for res in np.nditer(resolutions):
# Tilecoding hash table
# ctu = tiles.CollisionTable(32, 'super safe')
# ctu = tiles.CollisionTable(4096, 'unsafe')
# cts = tiles.CollisionTable(4096, 'safe')
# ctss = tiles.CollisionTable(4096, 'super safe')
resVec = np.zeros(np.power(res, numFeatures)*numTilings)
# resVecHash = np.zeros(4096)
# Get the indexes of the tiles
tilesOut = tiles.tiles(numTilings, res, normS*res)
print tilesOut
# print tilesOut
# tilesOutHash = tiles.tiles(numTilings, ctu, normS*res)
# print tilesOutHash
# resVecHash[tilesOutHash] = 1
# print resVecHash
# For each tile index flip a feature in the feature vector
# for tileIndex in range(len(tilesOut)):
# resVec[tilesOut[tileIndex] + (res**2 * tileIndex)] = 1
# x = np.append(x, resVec)
return catfeat
def getReward(newAngles,timeStep):
# Define the reward function of the system
# A positive reward of rt = 1.0 was
# delivered when θw and θe were both within 0.1 radians of
# their target angles. A reward of rt = −0.5 was delivered
# in all other cases, in essence penalizing the learning system
# when the arm’s posture differed from the target posture.
target = targetAngles[timeStep,range(numJoints)]
absAngleError = np.abs(newAngles-target)
if all(absAngleError < 0.1):
r = 0.1
else:
r = -0.5
return r
def perform(vel,s,timeStep):
# take the action and observe the new state and the reward
# new state is defined by the new joint angle
# which is defined by the old joint angle and the new angular velocity
# which is applied for that time step and the
# emg signal at that time index
# Calculate the new angular state of the joint
# old angle + angular velocity * time (in this case time = 5ms, the period of action selection)
# this limits the amount of motion of the joint possible in each action selection
# Define the new state space with the new angle and the emg information from the next step
newAngles = np.zeros(numJoints)
newAngles[:] = np.clip((s[:numJoints] + (vel[:] * 0.005)), 0, math.pi)
s = np.hstack((newAngles, simEMGdiff[timeStep, range(numEMG)]))
# Get the reward for the new angle
r = getReward(newAngles,timeStep)
return r, s
# process the training samples that are given
for i in tqdm(range(tmax)):
jointAngle[i, :] = s[:numJoints]
# Featurize the state
x = featurize(s)
a = np.zeros(numJoints)
angVels = np.zeros(numJoints)
# Calculate the mean and standard deviation of the action selection
for j in range(numJoints):
agentMean[i,j] = np.dot(wU[:,j],x)
agentStd[i,j] = max(1,np.exp(np.dot(wS[:,j],x) + np.log(maxAngVelInt_stdC)))
# get the action from the normal distribution
# angular velocity commands are sent to joints (simulated servos)
# as integers in the range [−maxAngVelInt_stdC, maxAngVelInt_stdC]
a[j] = round(np.random.normal(agentMean[i,j],agentStd[i,j]))
# If the action is outside the range, crop to the range
if a[j] < -maxAngVelInt_stdC:
a[j] = -maxAngVelInt_stdC
elif a[j] > maxAngVelInt_stdC:
a[j] = maxAngVelInt_stdC
# Convert the action to an angular velocity
angVels[j] = conAngIntToangVel(a[j])
# Take action a and observe the reward, r, and the new state, s
reward[i],s = perform(angVels,s,i)
if numJoints > 1:
# Initially, parameter vectors for the wrist and elbow joints
# were each trained in isolation for 100k time steps;
if i < phase1maxT:
# set joint 2 to desired position
s[1] = targetAngles[i,1]
elif i < phase2maxT:
# set joint 1 to desired position
s[0] = targetAngles[i,0]
# Featurize the new state
newX = featurize(s)
# Calculate the TD Error based on the old state and the new state
delta[i] = reward[i] + (gamma * np.dot(v,newX)) - np.dot(v,x)
# Critic's eligibility traces
# Updated eligibility trace from the 2013 paper
# replacing eligibility traces in the critic used to accelerate learning
elV = (lambdv * elV) + x
elV = np.minimum(np.ones(featVecLength),elV)
# Critic's parameter vector
v = v + (alphaV * delta[i] * elV)
if numJoints > 1:
# Initially, parameter vectors for the wrist and elbow joints
# were each trained in isolation for 100k time steps;
if i < phase1maxT:
# learn parameter vectors for joint 1
# set joint 2 to desired position
elU[:,0] = lambdw * elU[:,0] + np.multiply((a[0] - agentMean[i,0]),x)
wU[:,0] = wU[:,0] + alphaU * delta[i] * elU[:,0]
elS[:,0] = lambdw * elS[:,0] + np.multiply(((np.power((a[0] - agentMean[i,0]),2) / np.power(agentStd[i,0],2)) - 1),x)
wS[:,0] = wS[:,0] + alphaS * delta[i] * elS[:,0]
elif i < phase2maxT:
# learn parameter vectors for joint 2
# set joint 1 to desired position
elU[:,1] = lambdw * elU[:,1] + np.multiply((a[1] - agentMean[i,1]),x)
wU[:,1] = wU[:,1] + alphaU * delta[i] * elU[:,1]
elS[:,1] = lambdw * elS[:,1] + np.multiply(((np.power((a[1] - agentMean[i,1]),2) / np.power(agentStd[i,1],2)) - 1),x)
wS[:,1] = wS[:,1] + alphaS * delta[i] * elS[:,1]
else:
for j in range(numJoints):
# Actors parameters (eligibiliy traces and weight vectors)
elU[:,j] = lambdw * elU[:,j] + np.multiply((a[j] - agentMean[i,j]),x)
wU[:,j] = wU[:,j] + alphaU * delta[i] * elU[:,j]
elS[:,j] = lambdw * elS[:,j] + np.multiply(((np.power((a[j] - agentMean[i,j]),2) / np.power(agentStd[i,j],2)) - 1),x)
wS[:,j] = wS[:,j] + alphaS * delta[i] * elS[:,j]
else:
for j in range(numJoints):
# Actors parameters (eligibiliy traces and weight vectors)
elU[:,j] = lambdw * elU[:,j] + np.multiply((a[j] - agentMean[i,j]),x)
wU[:,j] = wU[:,j] + alphaU * delta[i] * elU[:,j]
elS[:,j] = lambdw * elS[:,j] + np.multiply(((np.power((a[j] - agentMean[i,j]),2) / np.power(agentStd[i,j],2)) - 1),x)
wS[:,j] = wS[:,j] + alphaS * delta[i] * elS[:,j]
if (i%5000 == 0):
print 'Step: ' + str(i)
print np.sum(reward)
# print 'Joint Angle: ' + str(jointAngle[i,:]) + ' rads'
# print 'Target Angle: ' + str(targetAngles[i,range(numJoints)]) + ' rads'
# print 'Agent Mean: ' + str(agentMean[i,:])
# print 'Agent Std: ' + str(agentStd[i,:])
# print 'Action: ' + str(angVels) + ' rad/s, move ' + str(angVels*0.005) + ' rads'
# print 'New Joint Angles: ' + str(s[range(numJoints)]) + ' rads'
# print 'Reward: ' + str(reward[i])
# print 'TD Error: ' + str(delta[i])
# print '\n'
# In[ ]:
# Visualize the learning
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, targetAngles[:,range(numJoints)])
# ax1.set_title('Target Angles')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, jointAngle)
# ax1.set_title('Learned Joint Angles')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, delta)
# ax1.set_title('TD Error')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, np.cumsum(reward))
# ax1.set_title('Cumulative Return')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, agentMean)
# ax1.set_title('Agent Mean')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t, agentStd)
# ax1.set_title('Agent Standard Deviation')
# #####
# In[ ]:
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t[-30000:], jointAngle[-30000:])
# ax1.plot(t[-30000:], targetAngles[-30000:])
# ax1.set_title('Target and Learned Angles')
# ax1.set_ylim([0, 2])
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t[0:30000], agentMean[0:30000])
# ax1.set_title('Agent Mean')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t[0:30000], agentStd[0:30000])
# ax1.set_title('Agent Standard Deviation')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t[-30000:], agentMean[-30000:])
# ax1.set_title('Agent Mean')
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.plot(t[-30000:], agentStd[-30000:])
# ax1.set_title('Agent Standard Deviation')