Robot dynamics and control
Derive manipulator dynamics and recursive Newton-Euler inverse dynamics, then study gravity-compensated PD, computed torque, impedance and operational-space control.
After this lesson you can
- Derive two-link manipulator equations using Euler-Lagrange.
- Implement recursive Newton-Euler inverse dynamics and mass-matrix forward dynamics.
- Prove stability of gravity-compensated PD control using a Lyapunov function.
- Design computed-torque and impedance controllers and compare their contact responses.
- Explain the low-level controller beneath position, velocity and torque actions predicted by a learned policy.
Before you start
What the arm executes
A policy can output positions, velocities or torques. Each interface delegates a different problem to the lower-level controller: a position requires converting error into an action that moves the arm; a torque requires considering its dynamics directly. Before comparing policies, specify which signal executes and at what frequency.
From energy to torques
The manipulator equations separate inertia, velocity and gravity:
is symmetric positive definite for a nondegenerate physical system; is not unique, although is fixed by the chosen dynamics. converts force applied to the end effector into joint torque through virtual work. Units matter: revolute joint position in radians, velocity in radians per second and torque in newton metres.
For two uniform rods with masses , lengths , centres and central moments , measure from the downward vertical and relative to the first link. Potential energy is . Kinetic energy sums translation of each centre and rotation around it. The Euler-Lagrange equation, , gives
With , one choice of is . The gravity vector is the gradient of . For this choice, is skew-symmetric: its diagonal is zero and opposite off-diagonal entries cancel. This property cancels velocity terms in the stability proof. The equations are also linear in suitable inertial parameters, although not in joint coordinates.
The first figure uses , rod moments and gravity 9.81. It starts at radians with zero velocity. It computes by solving the mass system and integrates for five seconds with a 0.02 s step. Viscous friction dissipates energy; with zero friction the exact mechanical energy is constant. Explicit Euler can create numerical drift even when the ideal system conserves energy. RK4 reduces error in this configuration but does not exactly conserve energy for every step or horizon.
Newton-Euler forward and backward
Recursive Newton-Euler inverse dynamics computes the torques required for a given position, velocity and acceleration. A forward pass propagates each link’s velocity and acceleration; a backward pass sums descendant forces and moments. The lab implements the planar version for a rod chain, with gravity incorporated as reference acceleration. It does not first form the mass matrix.
Forward dynamics solves . Each column of can be obtained by applying inverse dynamics with unit acceleration and zero velocity and gravity. Agreement between the two procedures requires the same frames, masses, inertias, gravity and external-force sign. This consistency check is especially useful when a hand-derived formula has sign errors.
Stability and control
In gravity-compensated PD, for a constant reference and error , apply with symmetric positive-definite gains. Take
Using skew symmetry, . On the set , the dynamics remain there only if , hence . Under smooth dynamics, uniformly positive masses, an exact gravity model and no saturation, LaSalle’s invariance principle gives convergence to equilibrium in the domain considered. For periodic angles, define the error and its domain; the proof does not cover representation jumps, latency or torque limits. Review the hypotheses for Lyapunov and stability before applying the conclusion to a physical controller.
The third figure shows a point-mass pendulum of mass 1 kg and length 0.5 m, kg m², and . Its horizontal axis is angular error, the other axis is velocity, and height is . With gravity compensated, . Without compensation, an additional term can be positive, so that candidate no longer certifies descent. RK4 integrates the curve and the indicator shows the largest increase in between samples, not a universal mathematical proof.
Computed torque uses a model to cancel nonlinear terms. If , the law gives with an exact model and no disturbances. Incorrect mass, contact and saturation break that cancellation. Linear dynamics design connects to second-order systems or LQR, but local linearization alone does not certify the entire system.
Impedance control seeks a relation between displacement and force, for example , with . Lower stiffness permits more deformation under the same force in a static model; it does not automatically remove peaks or guarantee stable contact. In operational-space control, if has full row rank, effective inertia is . Bias terms and the choice of a dynamic projection for secondary tasks also matter. Near singularities this inverse ceases to exist or becomes ill-conditioned.
The second figure uses the same rods as the first, joint viscous friction 0.08 and RK4 with a 0.01 s step. Its reference is radians, and derivative gain is . The wall exerts a unilateral elastic force with stiffness 100 N/m and damping 3 N s/m beyond ; it is converted to torques with the Jacobian. Impedance control uses Cartesian stiffness and damping five times the corresponding gains and estimated gravity compensation. The true second-link mass is 1 kg; the slider changes the controller model’s mass. The optional push adds 2 N m to the first joint from 2 to 2.1 s. These are results from this explicit simulation, not a commercial-arm trial.
An operational-space controller can use redundancy for a secondary task, but the projector must match the chosen dynamics and priority. Discretization turns the continuous system into a time-step problem: a gain stable in a continuous model can oscillate if frequency or delay is unsuitable. Linearization around equilibrium helps analyze a neighbourhood; integrating an ODE with initial conditions checks one scenario rather than proving stability for all.
As a real interface example, Franka Control Interface documents joint position, velocity or torque commands and Cartesian commands, with exchange at 1 kHz. Its documentation says torque commands on that interface include gravity and friction compensation; adding compensation again without considering the API would produce a different signal than intended. A position policy can run at a lower rate and feed a generator and controller that execute intermediate references. That layer’s rate, filtering, latency and limits are part of the system to evaluate.
Lab: derivation and Newton-Euler
The cells symbolically derive , and , verify the structural property and compare Newton-Euler with Lagrangian dynamics on 100 random states with a fixed seed. Angles are measured from the downward vertical and moments of inertia are taken about each rod’s centre.
import numpy as np
import sympy as sp
q1,q2,v1,v2=sp.symbols('q1 q2 v1 v2',real=True)
m1,m2,l1,l2,g=sp.symbols('m1 m2 l1 l2 g',positive=True)
Q=sp.Matrix([q1,q2]); V=sp.Matrix([v1,v2])
p1=sp.Matrix([l1*sp.sin(q1)/2,-l1*sp.cos(q1)/2])
p2=sp.Matrix([l1*sp.sin(q1)+l2*sp.sin(q1+q2)/2,-l1*sp.cos(q1)-l2*sp.cos(q1+q2)/2])
vone=p1.jacobian(Q)*V; vtwo=p2.jacobian(Q)*V
I1=m1*l1**2/12; I2=m2*l2**2/12
K=sp.expand((m1*vone.dot(vone)+I1*v1**2+m2*vtwo.dot(vtwo)+I2*(v1+v2)**2)/2)
U=g*(m1*p1[1]+m2*p2[1])
M=sp.trigsimp(sp.hessian(K,(v1,v2)))
C=sp.Matrix(2,2,lambda i,j:sum((sp.diff(M[i,j],Q[k])+sp.diff(M[i,k],Q[j])-sp.diff(M[j,k],Q[i]))*V[k]/2 for k in range(2)))
C=sp.simplify(C); G=sp.Matrix([sp.diff(U,q) for q in Q])
Mdot=sp.Matrix(2,2,lambda i,j:sum(sp.diff(M[i,j],Q[k])*V[k] for k in range(2)))
assert sp.simplify((Mdot-2*C)+(Mdot-2*C).T)==sp.zeros(2)
print('M =',M); print('C =',C); print('g =',G)
args=(q1,q2,v1,v2,m1,m2,l1,l2,g)
mf=sp.lambdify(args,M,'numpy'); cf=sp.lambdify(args,C,'numpy'); gf=sp.lambdify(args,G,'numpy')def perp(r): return np.array([-r[1],r[0]])
def cross(a,b): return a[0]*b[1]-a[1]*b[0]
def rnea(q,qd,qdd,model):
masses,lengths,inertias,gravity=model
angle=omega=alpha=0.; accel=np.zeros(2); data=[]
for i in range(len(q)):
angle+=q[i]; omega+=qd[i]; alpha+=qdd[i]
u=np.array([np.sin(angle),-np.cos(angle)])
rc=lengths[i]*u/2; re=lengths[i]*u
ac=accel+alpha*perp(rc)-omega**2*rc
F=masses[i]*(ac-np.array([0.,-gravity])); N=inertias[i]*alpha
data.append((rc,re,F,N))
accel=accel+alpha*perp(re)-omega**2*re
result=np.zeros(len(q)); nextF=np.zeros(2); nextN=0.
for i in range(len(q)-1,-1,-1):
rc,re,F,N=data[i]
result[i]=N+cross(rc,F)+nextN+cross(re,nextF)
nextF=F+nextF; nextN=result[i]
return result
rng=np.random.default_rng(2); model=([1.,1.],[1.,1.],[1/12,1/12],9.81); worst=0.
for _ in range(100):
q=rng.uniform(-2,2,2); qd=rng.normal(size=2); qdd=rng.normal(size=2)
vals=(*q,*qd,1.,1.,1.,1.,9.81)
expected=mf(*vals)@qdd+cf(*vals)@qd+gf(*vals).ravel()
worst=max(worst,np.max(np.abs(expected-rnea(q,qd,qdd,model))))
print('Error máximo Newton-Euler:',worst)
assert worst<1e-10In the backward pass, the next link’s moment must be moved to the current pivot, giving the term cross(re,nextF). Omitting it fails to transmit the weight of later links to the first motor.
The next cell integrates forward dynamics with RK4 and compares three laws on a smooth reference. Curves and errors come from this run with exact masses and model; change parameters and initial conditions to explore when that comparison stops being valid.
import matplotlib.pyplot as plt
def matrices(q,qd):
vals=(*q,*qd,1.,1.,1.,1.,9.81)
return np.asarray(mf(*vals),float),np.asarray(cf(*vals),float),np.asarray(gf(*vals),float).ravel()
def reference(t):
w=.7
return (np.array([.6+.25*np.sin(w*t),-.5+.15*np.sin(w*t)]),
np.array([.25*w*np.cos(w*t),.15*w*np.cos(w*t)]),
np.array([-.25*w*w*np.sin(w*t),-.15*w*w*np.sin(w*t)]))
def control(state,t,mode):
q,qd=state[:2],state[2:]; desired,vd,ad=reference(t)
mass,C,gravity=matrices(q,qd); feedback=20*(desired-q)+9*(vd-qd)
if mode=='PD': return feedback
if mode=='PD + gravedad': return feedback+gravity
return mass@(ad+feedback)+C@qd+gravity
def deriv(state,t,mode):
q,qd=state[:2],state[2:]; mass,C,gravity=matrices(q,qd)
qdd=np.linalg.solve(mass,control(state,t,mode)-C@qd-gravity)
return np.r_[qd,qdd]
def integrate(mode):
dt=.01; state=np.array([.3,-.3,0.,0.]); errors=[]
for i in range(301):
t=i*dt; desired,_,_=reference(t); errors.append(np.linalg.norm(state[:2]-desired))
if i<300:
k1=deriv(state,t,mode); k2=deriv(state+dt*k1/2,t+dt/2,mode)
k3=deriv(state+dt*k2/2,t+dt/2,mode); k4=deriv(state+dt*k3,t+dt,mode)
state=state+dt*(k1+2*k2+2*k3+k4)/6
return np.array(errors)
fig,ax=plt.subplots()
for mode in ['PD','PD + gravedad','par calculado']:
errors=integrate(mode); print(mode,'RMS angular:',round(np.sqrt(np.mean(errors**2)),6))
ax.plot(np.arange(len(errors))*.01,errors,label=mode)
ax.set(xlabel='tiempo (s)',ylabel='norma del error angular (rad)'); ax.legend(); plt.show()Local lab: Panda and contact
We use the MuJoCo Menagerie Panda at a pinned revision. It reuses oryon-panda-model from the previous lesson if present; otherwise the first run downloads XML and meshes. You need mujoco, NumPy and network access for the download. We add a table and measurement site and disable the model’s actuators to apply simulated torques directly. This is not a physical robot’s torque interface.
import os, urllib.request, xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
import mujoco
root=Path(os.environ.get('ORYON_PANDA_DIR',str(Path.cwd()/'oryon-panda-model')))
root.mkdir(parents=True,exist_ok=True)
base='https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/822c2d8f877dd166c5b7d3c9f7e3c3b6589473b7/franka_emika_panda/'
xml=root/'panda.xml'
if not xml.exists(): urllib.request.urlretrieve(base+'panda.xml',xml)
tree=ET.parse(xml)
for mesh in tree.findall('.//asset/mesh'):
filename=mesh.get('file')
if filename:
dest=root/'assets'/filename; dest.parent.mkdir(parents=True,exist_ok=True)
if not dest.exists(): urllib.request.urlretrieve(base+'assets/'+filename,dest)
hand=tree.find(".//body[@name='hand']")
ET.SubElement(hand,'site',{'name':'tool','pos':'0 0 0.10','size':'0.005'})
path=root/'panda_temp.xml'; tree.write(path,encoding='utf-8',xml_declaration=True)
temp=mujoco.MjModel.from_xml_path(str(path)); initial_data=mujoco.MjData(temp)
mujoco.mj_resetDataKeyframe(temp,initial_data,0); mujoco.mj_forward(temp,initial_data)
site0=mujoco.mj_name2id(temp,mujoco.mjtObj.mjOBJ_SITE,'tool'); start=initial_data.site_xpos[site0].copy()
position=f'{start[0]:.4f} {start[1]:.4f} {start[2]-0.04:.4f}'
ET.SubElement(tree.find('worldbody'),'geom',{'name':'table','type':'box','pos':position,'size':'0.15 0.15 0.02','friction':'1 0.005 0.0001'})
path=root/'panda_contact.xml'; tree.write(path,encoding='utf-8',xml_declaration=True)
model=mujoco.MjModel.from_xml_path(str(path)); model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_ACTUATION
site=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_SITE,'tool')
table=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_GEOM,'table')
joints=[mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_JOINT,f'joint{i}') for i in range(1,8)]
dofs=model.jnt_dofadr[joints]; qaddrs=model.jnt_qposadr[joints]
def full_mass(d,M):
try: mujoco.mj_fullM(model,d,M)
except TypeError: mujoco.mj_fullM(model,M,d.qM)
print('Paso de simulación (s):',model.opt.timestep)npm run lab and open the connection link.import matplotlib.pyplot as plt
def reset():
d=mujoco.MjData(model); mujoco.mj_resetDataKeyframe(model,d,0); mujoco.mj_forward(model,d); return d
def impedance(K):
d=reset(); initial=d.site_xpos[site].copy(); target=initial+np.array([0,0,-.04])
Jp=np.zeros((3,model.nv)); Jr=np.zeros((3,model.nv)); bias=np.zeros(model.nv); mass=np.zeros((model.nv,model.nv))
forces=[]; bias_error=0.
for _ in range(1500):
mujoco.mj_forward(model,d); mujoco.mj_jacSite(model,d,Jp,Jr,site)
mujoco.mj_rne(model,d,0,bias); full_mass(d,mass)
bias_error=max(bias_error,np.max(np.abs(bias-d.qfrc_bias)))
e=target-d.site_xpos[site]; velocity=Jp@d.qvel
force=K*e-2*np.sqrt(K)*velocity
torque=Jp[:,dofs].T@force+bias[dofs]-2*d.qvel[dofs]
d.qfrc_applied[:]=0; d.qfrc_applied[dofs]=np.clip(torque,-80,80)
mujoco.mj_step(model,d); normal=0.
for i in range(d.ncon):
c=d.contact[i]
if c.geom1==table or c.geom2==table:
f=np.zeros(6); mujoco.mj_contactForce(model,d,i,f); normal+=max(0.,f[0])
forces.append(normal)
return np.array(forces),bias_error
fig,ax=plt.subplots()
for stiffness in [100,300,600]:
forces,bias_error=impedance(stiffness)
print('K:',stiffness,'media final (N):',round(np.mean(forces[-100:]),6),'máximo (N):',round(np.max(forces),6),'error RNE:',bias_error)
ax.plot(np.arange(len(forces))*model.opt.timestep,forces,label=f'K={stiffness}')
ax.set(xlabel='tiempo (s)',ylabel='suma de fuerzas normales (N)'); ax.legend(); plt.show()
d=reset(); q0=d.qpos[qaddrs].copy(); bias=np.zeros(model.nv); mass=np.zeros((model.nv,model.nv)); errors=[]
for n in range(1500):
mujoco.mj_forward(model,d); t=n*model.opt.timestep; w=2*np.pi/3
qref=q0.copy(); qdref=np.zeros(7); qddref=np.zeros(7)
qref[0]+=.15*(1-np.cos(w*t)); qdref[0]=.15*w*np.sin(w*t); qddref[0]=.15*w*w*np.cos(w*t)
mujoco.mj_rne(model,d,0,bias); full_mass(d,mass)
accel=qddref+200*(qref-d.qpos[qaddrs])+28*(qdref-d.qvel[dofs])
d.qfrc_applied[:]=0; d.qfrc_applied[dofs]=mass[np.ix_(dofs,dofs)]@accel+bias[dofs]
errors.append(np.linalg.norm(qref-d.qpos[qaddrs])); mujoco.mj_step(model,d)
print('Par calculado RMS articular (rad):',np.sqrt(np.mean(np.square(errors))))
assert np.isfinite(errors).all()npm run lab and open the connection link.Computed torque is evaluated in free space; impedance presses against the table. Force is the sum of normal components reported by MuJoCo for contacts with the table, not a real-world measurement. The final mean uses the last 100 samples. Control applies an idealized bias model and limits impedance torques to 80 N m per component. The comparison keeps the same target and contact model; it does not establish that high stiffness is safe or generalize to other objects or integrators.
Exercises
Step 1 of 2. What is M dot ij?
Step 1 of 2. What remains in the derivative of V?
rnea(q, qd, qdd, model) for a planar chain of uniform rods, with angles from the downward vertical and model=(masses, lengths, central inertias, gravity). Return the torques.def rnea(q, qd, qdd, model):
pass