-
Notifications
You must be signed in to change notification settings - Fork 0
/
armSimulator.py
495 lines (394 loc) · 18.4 KB
/
armSimulator.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# -*- coding: utf-8 -*-
"""
Created on Fri May 2 01:17:09 2014
@author: jrcapriles
"""
import pygame, ode, random, Buttons
from math import atan2, acos, asin
import matplotlib.pyplot as plt
from pygame.locals import *
from numpy import *
from Point import *
class armSimulator( object ):
def __init__( self, width, lenght, links):
# Initialize pygame
pygame.init()
self.width, self.lenght, self.links = width, lenght, links
self.L = ones(self.links)
self.desired = None
# Open a display
self.srf = pygame.display.set_mode((self.width,self.lenght))
pygame.display.set_caption(str(links) + "-Link Arm")
#Parameters
self.fps = 50
self.dt = 1.0/self.fps
self.loopFlag = True
self.g= -9.81
self.maxF = 20*ones((1,links))
self.thetad = zeros((1,links))
self.switch_counter = 0
#TODO create trasnformation matrix (n=2,3,4...)
self.T = []
for count in range(0,self.links):
self.T.append(zeros(shape=(4,4)))
#Buttons
self.goal_button = Buttons.Button(self.srf, color = (200,0,0), x = 10, y = 10, length = 50, height = 25, width = 0, text = "Goal", text_color = (255,255,255), font_size = 20, fade_on = False)
self.switch_button = Buttons.Button(self.srf, color = (200,0,0), x = 60, y = 10, length = 50, height = 25, width = 0, text = "Switch", text_color = (255,255,255), font_size = 20, fade_on = False)
self.follow_button = Buttons.Button(self.srf, color = (200,0,0), x = 110, y = 10, length = 50, height = 25, width = 0, text = "Follow", text_color = (255,255,255), font_size = 20, fade_on = False)
self.noise_button = Buttons.Button(self.srf, color = (200,0,0), x = 160, y = 10, length = 50, height = 25, width = 0, text = "Noise", text_color = (255,255,255), font_size = 20, fade_on = False)
#Button Dictionary
self.buttons = {0 : self.goal_button,
1 : self.switch_button,
2 : self.follow_button,
3 : self.noise_button}
def createIC(self, values = None):
rest = []
left = []
right = []
up =[]
extra=[]
print values
#First loop to create all different combinations of IC
for i in range(0,self.links+1):
rest.append(Point(0,-i,0))
left.append(Point(i,0,0))
right.append(Point(-i,0,0))
up.append(Point(0,i,0))
if values is not None:
extra.append(Point(0,values[i],0))
#Create the dicionary
if values is None:
self.ICList = {"Rest":rest,
"Left":left,
"Right":right,
"Up":up}
else:
self.ICList = {"Rest":rest,
"Left":left,
"Right":right,
"Up":up,
"Extra":extra}
def setTarget(self,target):
self.thetad = target
self.newGoal = target
def getTarget(self, i):
return self.thetad[i]
def getTargetRange(self, i,j):
return self.thetad[i:j]
def setIC(self, case):
self.IC = self.ICList[case]
def getIC(self,i):
return self.IC[i].getPoint()
def setMaxF(self, F):
if F is None:
self.maxF = [10 for i in range(self.links)]
else:
self.maxF = F
def getMaxF(self,i):
return self.maxF[i]
def getWidth(self):
return self.width
def getLenght(self):
return self.lenght
def getLinksLenght(self):
return self.L
def setLinksLenght(self, new_L):
self.L = new_L
return True
def world2screen(self,x,y):
return int(self.width/2 + 128*x), int(self.lenght/2 - 128*y)
def world2screenX(self,x):
return int(self.width/2 + 128*x)
def world2screenY(self,y):
return int(self.lenght/2 - 128*y)
def screen2worldX(self,x):
return (float(x - self.width/2)/128)
def screen2worldY(self,y):
return (float(-y + self.lenght/2)/128)
def screen2world(self,x,y):
return (float(x - self.width/2)/128), (float(-y + self.lenght/2)/128)
def surf(self, x,y):
return (pow(x-pi/2,2) + pow(0.9*pi*y,2) - pow(pi/2,2))
def phi(self, y):
return -y -(2*self.a/sqrt(pow(self.a,2)-1))*arctan(sqrt((self.a-1)/(self.a+1))*tan(y/2))
def checkEvents(self):
#Get the list of events from Pygame
events = pygame.event.get()
for e in events:
if e.type==QUIT:
self.loopFlag=False
elif e.type==KEYDOWN:
if e.key == K_g:
print "New Goals: please click the new goal over the red circle"
self.setNewGoal()
elif e.key == K_f:
self.follow = not self.follow
if self.follow:
self.updateBottons(2,(100,0,0))
else:
self.updateBottons(2,(200,0,0))
elif e.key == K_s:
print "Switching side"
self.switchSide()
elif e.key == K_n:
self.noise = not self.noise
if self.noise:
self.updateBottons(3,(100,0,0))
else:
self.updateBottons(3,(200,0,0))
else:
self.loopFlag=False
elif e.type == MOUSEBUTTONDOWN:
if self.goal_button.pressed(pygame.mouse.get_pos()):
print "New Goals: please click the new goal over the red circle"
self.setNewGoal()
elif self.switch_button.pressed(pygame.mouse.get_pos()):
print "Switching side"
self.switchSide()
elif self.follow_button.pressed(pygame.mouse.get_pos()):
self.follow = not self.follow
if self.follow:
self.updateBottons(2,(100,0,0))
else:
self.updateBottons(2,(200,0,0))
elif self.noise_button.pressed(pygame.mouse.get_pos()):
self.noise = not self.follow
if self.noise:
self.updateBottons(3,(100,0,0))
else:
self.updateBottons(3,(200,0,0))
def runSimulation(self, case, targets,extra=None):
if extra is not None:
self.createIC(extra)
else:
self.createIC()
self.createArm(case)
self.setTarget(targets)
# Simulation loop.
self.clk = pygame.time.Clock()
self.follow = False
self.noise = False
while self.loopFlag:
# Check for events
self.checkEvents()
if self.follow:
self.desired = pygame.mouse.get_pos()
print self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1])
self.newGoal = self.IK(self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1]) )
self.setTarget(self.newGoal)
# Clear the screen
self.srf.fill((255,255,255))
if self.follow:
pygame.draw.circle(self.srf, (255,0,0), (self.world2screen(0,0)), 130*self.links, 1)
x = []
xd = []
y = []
yd = []
z = []
vx = []
vy = []
vz = []
theta = []
errTheta = []
thetaDot = []
errThetaDot = []
T = []
for i in range(0,self.links):
x1,y1,z1 = self.body[i].getPosition()
if self.noise:
x1 += random.uniform(-0.01, 0.01)
y1 += random.uniform(-0.01, 0.01)
x.append(x1)
y.append(y1)
z.append(z1)
vx1,vy1,vz1 = self.body[i].getAngularVel()
vx.append(vx1)
vy.append(vy1)
vz.append(vz1)
theta.append(self.j[i].getAngle())
#Compute error (normalized)
if (theta[i]- self.getTarget(i)) > pi:
err = theta[i] - self.getTarget(i) - 2*pi
elif (theta[i]- self.getTarget(i)) < -pi:
err = theta[i] - self.getTarget(i) + 2*pi
else:
err = theta[i] - self.getTarget(i)
errTheta.append(err) #theta[i]- self.getTarget(i))
#if i == 0:
# print errTheta[0]
thetaDot.append(sum(vz))
errThetaDot.append(self.getTarget(i)+thetaDot[i])
if i == 0: #Kinematics
xd.append(-self.L[0]*sin(-self.getTarget(0)))
yd.append(-self.L[0]*cos(-self.getTarget(0)))
else:
xd.append(xd[i-1]+self.L[i]*sin(-sum(self.thetad)))
yd.append(yd[i-1]-self.L[i]*cos(-sum(self.thetad)))
#print "theta ", i, theta[i]
T.append(-errTheta[i])
#Set servo values
self.j[i].setParam(ode.ParamVel, T[i])
self.j[i].setParam(ode.ParamFMax, self.getMaxF(i))
if self.desired is not None: #(Targets)
pygame.draw.circle(self.srf, (200,45,10), (self.desired[0],self.desired[1]), 12, 0)
pygame.draw.circle(self.srf, (255,255,255), (self.desired[0],self.desired[1]), 10, 0)
for i in range(0,self.links):
pygame.draw.circle(self.srf, (55,0,200), self.world2screen(x[i],y[i]), 10, 0) #(Motors)
if i==0:
pygame.draw.line(self.srf, (55,0,200), self.world2screen(self.IC[0].getPointX(),self.IC[0].getPointY()), self.world2screen(x[i],y[i]), 10)
pygame.draw.circle(self.srf, (255,0,0), self.world2screen(self.IC[i].getPointX(),self.IC[i].getPointY()), 5, 0) #(origin)
else:
pygame.draw.line(self.srf, (55,0,200), self.world2screen(x[i-1],y[i-1]), self.world2screen(x[i],y[i]), 10)
self.drawBackLines()
self.updateBottons()
pygame.display.flip()
# Next simulation step
self.world.step(self.dt)
# Try to keep the specified framerate
self.clk.tick(self.fps)
def updateBottons(self,i=None,color = None):
#Function to update the buttons defined at the button dictionary.
if i is None and color is None:
self.goal_button.update()
self.switch_button.update()
self.follow_button.update()
self.noise_button.update()
return True
elif color is None:
self.buttons[i].update()
else:
self.buttons[i].color = color
self.buttons[i].update()
def drawBackLines(self):
#Draw the back lines of the screen
pygame.draw.line(self.srf, (0,0,0), self.world2screen(0,-self.lenght/2), self.world2screen(0,self.lenght/2), 1)
pygame.draw.line(self.srf, (0,0,0), self.world2screen(-self.width/2,0), self.world2screen(self.width/2,0), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(1,-self.lenght/2),self.world2screen(1,self.lenght/2), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(2,-self.lenght/2),self.world2screen(2,self.lenght/2), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-1,-self.lenght/2),self.world2screen(-1,self.lenght/2), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-2,-self.lenght/2),self.world2screen(-2,self.lenght/2), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,1),self.world2screen(self.width/2,1), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,2),self.world2screen(self.width/2,2), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-1),self.world2screen(self.width/2,-1), 1)
pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-2),self.world2screen(self.width/2,-2), 1)
def createArm(self,case):
#This routine create the arm and set the initial condition accordingly.
self.setIC(case)
# Create a world object
self.world = ode.World()
self.world.setGravity((0,self.g,0))
# Create the bodies
self.body = []
self.M = []
self.j = []
for i in range(0,self.links):
self.body.append(ode.Body(self.world))
self.M.append(ode.Mass())
self.M[i].setSphere(2500, 0.025)
self.body[i].setMass(self.M[i])
self.body[i].setPosition(self.getIC(i+1))
self.j.append(ode.HingeJoint(self.world))
if i==0:
self.j[i].attach(self.body[0], ode.environment)
self.j[i].setAnchor(self.getIC(0))
else:
self.j[i].attach(self.body[i-1], self.body[i])
self.j[i].setAnchor(self.body[i-1].getPosition())
self.j[i].setAxis( (0,0,1) )
self.j[i].setParam(ode.ParamLoStop, -5.0)
self.j[i].setParam(ode.ParamHiStop,5.0)
self.j[i].MaxForce = 1
def FK(self,thetas):
self.T[0][0][0] = cos(thetas[0])
self.T[0][0][1] = -sin(thetas[0])
self.T[0][1][0] = sin(thetas[0])
self.T[0][1][1] = cos(thetas[0])
#self.T[1][0][3] = self.L[0]
self.T[0][2][2] = 1
self.T[0][3][3] = 1
self.T[1][0][0] = cos(thetas[1])
self.T[1][0][1] = -sin(thetas[1])
self.T[1][1][0] = sin(thetas[1])
self.T[1][1][1] = cos(thetas[1])
self.T[1][0][3] = self.L[0]
self.T[1][1][3] = self.L[0]
self.T[1][2][2] = 1
self.T[1][3][3] = 1
Tend = zeros(shape=(4,4))
Tend[0][0] = 1
Tend[1][1] = 1
Tend[2][2] = 1
Tend[3][3] = 1
Tend[0][3] = self.L[1]
Tend[1][3] = self.L[1]
prod = self.T[0]*(self.T[1]*Tend)
# print sum(prod2[0])
# print sum(prod2[1])
x_e=self.L[0]*sin(thetas[0])+self.L[1]*sin(sum(thetas))
y_e=self.L[0]*cos(thetas[0])+self.L[1]*cos(sum(thetas))
print x_e, y_e
return x_e, -y_e
def IK(self, x, y,switch = None):
#inverse kinematics
if self.links == 2:
ang2b = acos(self.clean_cos((x**2+y**2-self.L[0]**2-self.L[1]**2)/(2*self.L[0]*self.L[1])))
if switch is not None:
ang2b = -ang2b
ang1b = atan2(y,x) - atan2(self.L[1]*sin(ang2b),(self.L[0]+self.L[1]*cos(ang2b))) +pi/2
#print "New Angles",ang1b, ang2b
return (ang1b, -ang2b)
# elif self.links == 3:
# c2 = self.clean_cos((x**2+y**2-self.L[0]**2-self.L[1]**2)/(2*self.L[0]*self.L[1]))
# s2 = sqrt(1-c2**2)
# ang2 = atan2(s2,c2)
# k1 = self.L[0]+self.L[1]*c2
# k2 = self.L[1]*s2
# ang1 = atan2(y,x)-atan2(k2,k1) + pi/2
# sphi = (y-self.L[0]*sin(ang1)-self.L[1]*sin(ang1+ang2))/self.L[2]
# cphi = (y-self.L[0]*cos(ang1)-self.L[1]*cos(ang1+ang2))/self.L[2]
# ang3 = atan2(sphi,cphi) - ang1 - ang2
# return (ang1, ang2, ang3)
def is_odd(self, num):
return num & 0x1
def clean_cos(self,cos_angle):
return min(1,max(cos_angle,-1))
def setNewGoal(self):
self.go = (0,0)
self.newGoal = zeros(self.links)
i = 0
self.red_circle = (self.width/2,self.lenght/2)
self.white_circle = (self.width/2,self.lenght/2)
self.newGoalFlag =True
self.switch_counter = 0
while self.newGoalFlag:
# Draw the current circle in red and erase previous
pygame.draw.circle(self.srf, (255,0,0), (self.world2screen(0,0)), 130*self.links, 1)
pygame.display.flip()
events = pygame.event.get()
for e in events:
if e.type==QUIT:
self.loopFlag=False
self.newGoalFlag = False
if e.type==KEYDOWN:
self.loopFlag=False
self.newGoalFlag = False
if e.type == MOUSEBUTTONDOWN:
self.desired = pygame.mouse.get_pos()
print self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1])
self.white_circle = self.red_circle
self.red_circle = self.desired
self.newGoal = self.IK(self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1]) )
self.setTarget(self.newGoal)
self.FK(self.newGoal)
self.newGoalFlag = False
self.updateBottons(0,(100,0,0)) #0 for goal
#After the while
self.updateBottons(0,(200,0,0))
def switchSide(self):
if self.is_odd(self.switch_counter):
self.newGoal = self.IK(self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1]))
else:
self.newGoal = self.IK(self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1]),True)
#self.newGoal = self.IK(self.screen2worldX(self.desired[0]), self.screen2worldY(self.desired[1]),True)
self.setTarget(self.newGoal)
self.switch_counter +=1