serialRobotTest.py

You can view and download this file on Github: serialRobotTest.py

  1#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  2# This is an EXUDYN example
  3#
  4# Details:  Test Example of a serial robot with redundant coordinates
  5#           NOTE: more efficient version in serialRobotTSD.py and serialRobotKinematicTree.py using TorsionalSpringDamper
  6#
  7# Author:   Johannes Gerstmayr
  8# Date:     2020-02-16
  9# Revised:  2021-07-09
 10#
 11# Copyright:This file is part of Exudyn. Exudyn is free software. You can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
 12#
 13#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 14
 15import exudyn as exu
 16from exudyn.utilities import * #includes itemInterface and rigidBodyUtilities
 17import exudyn.graphics as graphics
 18from exudyn.rigidBodyUtilities import *
 19from exudyn.robotics import *
 20from exudyn.robotics.motion import Trajectory, ProfileConstantAcceleration
 21
 22import numpy as np
 23from numpy import linalg as LA
 24
 25testIsActive = exu.sys.get('testIsActive', False)
 26
 27SC = exu.SystemContainer()
 28mbs = SC.AddSystem()
 29
 30#testIsActive = True
 31if not testIsActive:
 32    sensorWriteToFile = True
 33else:
 34    sensorWriteToFile = False
 35
 36jointWidth=0.1
 37jointRadius=0.06
 38linkWidth=0.1
 39
 40graphicsBaseList = [graphics.Brick([0,0,-0.15], [0.4,0.4,0.1], graphics.color.grey)]
 41graphicsBaseList +=[graphics.Cylinder([0,0,0], [0.5,0,0], 0.0025, graphics.color.red)]
 42graphicsBaseList +=[graphics.Cylinder([0,0,0], [0,0.5,0], 0.0025, graphics.color.green)]
 43graphicsBaseList +=[graphics.Cylinder([0,0,0], [0,0,0.5], 0.0025, graphics.color.blue)]
 44graphicsBaseList +=[graphics.Cylinder([0,0,-jointWidth], [0,0,jointWidth], linkWidth*0.5, graphics.colorList[0])] #belongs to first body
 45
 46ty = 0.03
 47tz = 0.04
 48zOff = -0.05
 49toolSize= [0.05,0.5*ty,0.06]
 50graphicsToolList = [graphics.Cylinder(pAxis=[0,0,zOff], vAxis= [0,0,tz], radius=ty*1.5, color=graphics.color.red)]
 51graphicsToolList+= [graphics.Brick([0,ty,1.5*tz+zOff], toolSize, graphics.color.grey)]
 52graphicsToolList+= [graphics.Brick([0,-ty,1.5*tz+zOff], toolSize, graphics.color.grey)]
 53
 54
 55#changed to new robot structure July 2021:
 56newRobot = Robot(gravity=[0,0,9.81],
 57                 base = RobotBase(visualization=VRobotBase(graphicsData=graphicsBaseList)),
 58                 tool = RobotTool(HT=exu.HT(translation=[0,0,0.1]), visualization=VRobotTool(graphicsData=graphicsToolList)),
 59                 referenceConfiguration = []) #referenceConfiguration created with 0s automatically
 60
 61newRobot.AddLink(RobotLink(mass=20, COM=[0,0,0], inertia=np.diag([1e-8,0.35,1e-8]), localHT = StdDH2HT([0,0,0,np.pi/2]), visualization=VRobotLink(linkColor=graphics.colorList[0])))
 62newRobot.AddLink(RobotLink(mass=17.4, COM=[-0.3638, 0.006, 0.2275], inertia=np.diag([0.13,0.524,0.539]), localHT = StdDH2HT([0,0,0.4318,0]), visualization=VRobotLink(linkColor=graphics.colorList[1])))
 63newRobot.AddLink(RobotLink(mass=4.8, COM=[-0.0203,-0.0141,0.07], inertia=np.diag([0.066,0.086,0.0125]), localHT = StdDH2HT([0,0.15,0.0203,-np.pi/2]), visualization=VRobotLink(linkColor=graphics.colorList[2])))
 64newRobot.AddLink(RobotLink(mass=0.82, COM=[0,0.019,0], inertia=np.diag([0.0018,0.0013,0.0018]), localHT = StdDH2HT([0,0.4318,0,np.pi/2]), visualization=VRobotLink(linkColor=graphics.colorList[3])))
 65newRobot.AddLink(RobotLink(mass=0.34, COM=[0,0,0], inertia=np.diag([0.0003,0.0004,0.0003]), localHT = StdDH2HT([0,0,0,-np.pi/2]), visualization=VRobotLink(linkColor=graphics.colorList[4])))
 66newRobot.AddLink(RobotLink(mass=0.09, COM=[0,0,0.032], inertia=np.diag([0.00015,0.00015,4e-5]), localHT = StdDH2HT([0,0,0,0]), visualization=VRobotLink(linkColor=graphics.colorList[5])))
 67
 68
 69# newRobot = Robot(gravity=[0,0,-9.81], referenceConfiguration = [])
 70# newRobot.BuildFromDictionary(myRobot) #this allows conversion from old structure
 71
 72#assumption, as the bodies in the mbs have their COM at the reference position
 73#for link in robot['links']:
 74#    link['COM']=[0,0,0]
 75
 76#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 77#configurations and trajectory
 78q0 = [0,0,0,0,0,0] #zero angle configuration
 79
 80q1 = [0,       np.pi/8, np.pi*0.25, 0,np.pi/8,0] #configuration 1
 81q2 = [np.pi/2,-np.pi/8,-np.pi*0.125, 0,np.pi/4,0] #configuration 2
 82#q2 = [np.pi*0.45,-np.pi*0.35,-np.pi*0.25, np.pi*0.10,np.pi*0.2,np.pi*0.3] #configuration 2
 83#q2 = [pi/2,-pi/8,-pi*0.125,0,pi/4,pi/2] #configuration 2
 84
 85trajectory=Trajectory(q0, 0)
 86if False: #tests for static torque compensation
 87    #trajectory.Add(ProfileConstantAcceleration(q0, 1)) #V1.2.37: torques at tEnd= 0.3773259482700045
 88    trajectory.Add(ProfileConstantAcceleration(q2, 0.25))
 89    trajectory.Add(ProfileConstantAcceleration(q2, 0.75))
 90else: #standard test case:
 91    trajectory.Add(ProfileConstantAcceleration(q1, 0.25))
 92    trajectory.Add(ProfileConstantAcceleration(q2, 0.25))
 93    trajectory.Add(ProfileConstantAcceleration(q0, 0.5 ))
 94    trajectory.Add(ProfileConstantAcceleration(q0, 1e6))
 95
 96#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 97#test robot model
 98#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 99#control parameters, per joint:
100Pcontrol = np.array([40000, 40000, 40000, 100, 100, 10])
101Dcontrol = np.array([400,   400,   100,   1,   1,   0.05])  #last value 0.05 gives less oscillations as compared to earlier values of 0.1!
102# Pcontrol = 0.01*Pcontrol #soft behavior
103
104
105#++++++++++++++++++++++++++++++++++++++++++++++++
106#base, graphics, object and marker:
107graphicsBaseList = [graphics.Brick([0,0,-0.2], [0.4,0.4,0.1], graphics.color.grey)]
108graphicsBaseList +=[graphics.Cylinder([0,0,0], [0.5,0,0], 0.0025, graphics.color.red)]
109graphicsBaseList +=[graphics.Cylinder([0,0,0], [0,0.5,0], 0.0025, graphics.color.green)]
110graphicsBaseList +=[graphics.Cylinder([0,0,0], [0,0,0.5], 0.0025, graphics.color.blue)]
111#oGround = mbs.AddObject(ObjectGround(referencePosition=list(HT2translation(Tcurrent)), 
112objectGround = mbs.AddObject(ObjectGround(referencePosition=newRobot.GetBaseHT().translation, 
113                                     visualization=VObjectGround(graphicsData=graphicsBaseList)))
114
115#baseMarker; could also be a moving base!
116baseMarker = mbs.AddMarker(MarkerBodyRigid(bodyNumber=objectGround, localPosition=[0,0,0]))
117
118
119
120#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
121#build mbs robot model:
122robotDict = newRobot.CreateRedundantCoordinateMBS(mbs, baseMarker=baseMarker)
123    
124#   !!!!!IMPORTANT!!!!!:
125jointList = robotDict['jointList'] #must be stored there for the load user function
126
127unitTorques0 = robotDict['unitTorque0List'] #(left body)
128unitTorques1 = robotDict['unitTorque1List'] #(right body)
129
130loadList0 = robotDict['jointTorque0List'] #(left body)
131loadList1 = robotDict['jointTorque1List'] #(right body)
132#print(loadList0, loadList1)
133#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
134#control robot
135compensateStaticTorques = True
136def ComputeMBSstaticRobotTorques(newRobot):
137    q=[]
138    for joint in jointList:
139        q += [mbs.GetObjectOutput(joint, exu.OutputVariableType.Rotation)[2]] #z-rotation
140    HT=newRobot.JointHT(q)
141    return newRobot.StaticTorques(HT)
142
143#user function which is called only once per step, speeds up simulation drastically
144def PreStepUF(mbs, t):
145    if compensateStaticTorques:
146        staticTorques = ComputeMBSstaticRobotTorques(newRobot)
147    else:
148        staticTorques = np.zeros(len(jointList))
149    #compute load for joint number
150    for i in range(len(jointList)):
151        joint = i
152        phi = mbs.GetObjectOutput(jointList[joint], exu.OutputVariableType.Rotation)[2] #z-rotation
153        omega = mbs.GetObjectOutput(jointList[joint], exu.OutputVariableType.AngularVelocityLocal)[2] #z-angular velocity
154
155        #[u,v,a] = MotionInterpolator(t, robotTrajectory, joint) #OLD, until V1.1.135
156        [u,v,a] = trajectory.EvaluateCoordinate(t, joint)
157        
158    
159        torque = -(Pcontrol[joint]*(phi-u) + Dcontrol[joint]*(omega-v)) #negative sign in feedback control!
160        # torque = (Pcontrol[joint]*(phi+u) + Dcontrol[joint]*(omega+v)) #until V1.2.; but static Torque compensation is wrong in this case!
161        torque -= staticTorques[joint] #add static torque compensation
162        
163        load0 = torque * unitTorques0[i] #includes sign and correct unit-torque vector
164        load1 = torque * unitTorques1[i] #includes sign and correct unit-torque vector
165        
166    #     #write updated torque to joint loads, applied to left and right body
167        mbs.SetLoadParameter(loadList0[i], 'loadVector', list(load0))
168        mbs.SetLoadParameter(loadList1[i], 'loadVector', list(load1))
169    
170    return True
171
172mbs.SetPreStepUserFunction(PreStepUF)
173
174
175
176#add sensors:
177sJointRot = []
178sJointAngVel = []
179sJointTorque = []
180cnt = 0
181for jointLink in jointList:
182    sJointRot += [mbs.AddSensor(SensorObject(objectNumber=jointLink, 
183                               storeInternal=True,#fileName="solution/joint" + str(cnt) + "Rot.txt",
184                               outputVariableType=exu.OutputVariableType.Rotation,
185                               writeToFile = sensorWriteToFile))]
186    sJointAngVel += [mbs.AddSensor(SensorObject(objectNumber=jointLink, 
187                               storeInternal=True,#fileName="solution/joint" + str(cnt) + "AngVel.txt",
188                               outputVariableType=exu.OutputVariableType.AngularVelocityLocal,
189                               writeToFile = sensorWriteToFile))]
190    cnt+=1
191
192cnt = 0
193for load0 in robotDict['jointTorque0List']:
194    sJointTorque += [mbs.AddSensor(SensorLoad(loadNumber=load0,storeInternal=True,# fileName="solution/jointTorque" + str(cnt) + ".txt", 
195                                              writeToFile = sensorWriteToFile))]
196    cnt+=1
197
198
199
200mbs.Assemble()
201#mbs.systemData.Info()
202
203SC.visualizationSettings.connectors.showJointAxes = True
204SC.visualizationSettings.connectors.jointAxesLength = 0.02
205SC.visualizationSettings.connectors.jointAxesRadius = 0.002
206
207SC.visualizationSettings.nodes.showBasis = True
208SC.visualizationSettings.nodes.basisSize = 0.1
209SC.visualizationSettings.loads.show = False
210
211SC.visualizationSettings.openGL.multiSampling=4
212    
213tEnd = 0.2 #0.2 for testing
214h = 0.001
215
216if not testIsActive:
217    tEnd = 0.2
218    #tEnd = 1 #shows exactly static torques ComputeMBSstaticRobotTorques(newRobot) and desired angles (q2) at end
219
220#SC.renderer.DoIdleTasks()
221simulationSettings = exu.SimulationSettings() #takes currently set values or default values
222
223simulationSettings.timeIntegration.numberOfSteps = int(tEnd/h)
224simulationSettings.timeIntegration.endTime = tEnd
225simulationSettings.solution.file.writePeriod = h
226simulationSettings.solution.sensors.writePeriod = h
227simulationSettings.solution.file.write = (not testIsActive)
228# simulationSettings.timeIntegration.realtime.active = True
229# simulationSettings.timeIntegration.realtime.factor = 0.25
230
231simulationSettings.timeIntegration.verboseMode = 1
232simulationSettings.show.computationTime = False
233simulationSettings.show.statistics = False
234simulationSettings.linearSolver.solverType = exu.LinearSolverType.EigenSparse
235
236simulationSettings.timeIntegration.newton.useModifiedNewton = False #Just for the test; modified Newton is usually faster
237simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints = False
238simulationSettings.timeIntegration.generalizedAlpha.useNewmark = simulationSettings.timeIntegration.generalizedAlpha.useIndex2Constraints
239simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 0.5 #0.6 works well 
240
241simulationSettings.timeIntegration.generalizedAlpha.computeInitialAccelerations=True
242
243mbs.SolveDynamic(simulationSettings)
244
245if not testIsActive:
246    SC.visualizationSettings.general.autoFitScene=False
247    SC.renderer.Start()
248    SC.renderer.RestoreSavedState()
249
250    
251    mbs.SolutionViewer()
252    SC.renderer.Stop()
253
254lastRenderState = SC.renderer.GetState() #store model view
255
256#compute final torques:
257measuredTorques=[]
258
259for cnt, sensorNumber in enumerate(sJointTorque):
260    if not testIsActive:
261        exu.Print('sensor torque',cnt, '=', mbs.GetSensorValues(sensorNumber))
262    measuredTorques += [1e-2*mbs.GetSensorValues(sensorNumber)[2]]
263
264if not testIsActive:
265    for cnt, sensorNumber in enumerate(sJointRot):
266        exu.Print('sensor rot ',cnt, '=', mbs.GetSensorValues(sensorNumber))
267
268
269
270exu.Print("torques at tEnd=", np.sum(measuredTorques))
271
272#add larger test tolerance for 32/64bits difference
273exu.sys['testResult'] = np.sum(measuredTorques)   
274
275
276if not testIsActive:
277    
278    
279    mbs.PlotSensor(sJointTorque, components=2, closeAll=True, yLabel='joint torques (Nm)', title='joint torques')
280
281    mbs.PlotSensor(sJointRot, components=2, yLabel='joint angles (rad)', title='joint angles')
282
283    #V1.2.40, P39: with D[-1]=0.05: since 2022-04-22:
284    # sensor torque 0 = [  0.           0.         -12.68901871]
285    # sensor torque 1 = [-0.         -0.         76.45031947]
286    # sensor torque 2 = [-0.         -0.         12.97010176]
287    # sensor torque 3 = [ 0.00000000e+00  0.00000000e+00 -8.56924875e-05]
288    # sensor torque 4 = [-0.         -0.          0.08725323]
289    # sensor torque 5 = [ 0.0000000e+00  0.0000000e+00 -9.5769297e-07]
290    # sensor rot  0 = [-1.04899069e-15  3.05694259e-19 -3.19543456e-04]
291    # sensor rot  1 = [-4.57411886e-14 -1.77599905e-14  3.63829923e-01]
292    # sensor rot  2 = [ 4.68252006e-14 -1.78150803e-14  7.25569701e-01]
293    # sensor rot  3 = [-1.07990283e-13  1.95010674e-13  2.42757634e-07]
294    # sensor rot  4 = [ 1.07852866e-13 -2.06184741e-13  3.63658987e-01]
295    # sensor rot  5 = [ 1.84235149e-16 -6.26054764e-13 -5.07549126e-08]
296    # torques at tEnd= 0.7681856909852399 
297
298    #V1.2.40, P39: with D[-1]=0.1:
299    # sensor torque 0 = [  0.           0.         -12.68901812]
300    # sensor torque 1 = [-0.        -0.        76.4503195]
301    # sensor torque 2 = [-0.         -0.         12.97010177]
302    # sensor torque 3 = [ 0.0000000e+00  0.0000000e+00 -8.9097007e-05]
303    # sensor torque 4 = [-0.         -0.          0.08725323]
304    # sensor torque 5 = [-0.00000000e+00 -0.00000000e+00  1.09612342e-05]
305    # sensor rot  0 = [-1.04899069e-15  3.32799313e-19 -3.19543454e-04]
306    # sensor rot  1 = [-4.59632332e-14 -1.77794520e-14  3.63829923e-01]
307    # sensor rot  2 = [ 4.71643413e-14 -1.78734434e-14  7.25569701e-01]
308    # sensor rot  3 = [-1.07609037e-13  1.95343741e-13  2.42965135e-07]
309    # sensor rot  4 = [ 1.07471637e-13 -2.06279100e-13  3.63658987e-01]
310    # sensor rot  5 = [ 1.84106879e-16 -6.25874352e-13  8.28833899e-08]
311    # torques at tEnd= 0.7681857824086907 
312
313    #V1.2.37, P37: ==> uses wrong static torque compensation
314    # sensor torque 0 = [  0.           0.         -12.67938332]
315    # sensor torque 1 = [-0.         -0.         76.42613004]
316    # sensor torque 2 = [-0.         -0.         12.96641046]
317    # sensor torque 3 = [ 0.00000000e+00  0.00000000e+00 -8.93114211e-05]
318    # sensor torque 4 = [-0.         -0.          0.08723331]
319    # sensor torque 5 = [-0.0000000e+00 -0.0000000e+00  1.1143982e-05]
320    # sensor rot  0 = [ 1.60812265e-16 -2.71050543e-20  3.19257214e-04]
321    # sensor rot  1 = [ 5.06049354e-14 -1.91882065e-14 -3.63432530e-01]
322    # sensor rot  2 = [-4.07000942e-14  3.58791681e-14 -7.25182770e-01]
323    # sensor rot  3 = [ 9.91554982e-13  4.63740157e-13 -2.41708605e-07]
324    # sensor rot  4 = [-9.26617234e-13  3.52539928e-13 -3.63103888e-01]
325    # sensor rot  5 = [ 9.21913969e-18  3.74700271e-16 -8.34127775e-08]
326    # torques at tEnd= 0.7680031232065901