Motion planning: configuration space, sampling and trajectory optimization
Plan collision-free motion in configuration space with PRM, RRT variants and trajectory optimization, then time-parameterize a geometric path.
After this lesson you can
- Construct the configuration space of a planar arm and explain why it is not explicitly computed in high dimensions.
- Implement PRM, RRT and RRT-Connect with collision checking and path smoothing.
- Distinguish probabilistic completeness from asymptotic optimality and explain RRT*'s decreasing rewiring radius.
- Formulate trajectory optimization with smoothness and obstacle costs and solve it with a gradient method.
- Time-parameterize a geometric path under velocity and acceleration limits.
Before you start
The space where planning happens
An end effector can have a clear straight line to a cube while the elbow sweeps into a shelf. Planning must check the entire body, not just hand position. First find a collision-free geometric path; then decide how fast to traverse it and how the controller executes it.
The configuration space contains all allowed joint coordinates. For two unlimited revolute joints, : a torus. Plotting each angle in yields a square whose opposite edges represent the same configurations. Angular distance must use the difference wrapped to ; and are separated by , not . With limited joints those endpoints are not necessarily identified.
World obstacles induce : all configurations where any part of the robot collides. The first figure uses two links of length 1, a circle and a 48 by 48 grid; the test calculates the circle’s distance to each segment. Blue represents the fixed angular path from to radians, not a guaranteed free path. Each cell summarizes its centre: the discretized image can miss a narrow region. For a seven-degree-of-freedom arm, a grid of only 100 values per axis would have cells before storing edges; collision queries are made as needed.
For example, with and , the elbow is at and the tip at ; the path of every arm point matters, not only those endpoints. Dragging a circle in the world makes the figure recalculate which angle pairs bring either segment within the radius of its centre. The same obstacle occupies an irregular shape in configuration space. Crossing the map’s right edge to the left represents a small angular change even though the drawing appears discontinuous.
Oracles and paths
Collision checking combines geometry, kinematics and pair detection. Bounding volumes discard distant pairs; intersection or distance is then calculated in more detail. Self-collisions and joint limits must also be checked. A positive margin compensates for some uncertainty, but a poorly chosen margin does not guarantee real safety.
Checking only a segment’s endpoints is insufficient: it may cross a thin wall. The labs interpolate configurations at a declared resolution; reducing it detects more collisions, but finitely many samples are not a continuous proof. Continuous collision checking or a conservative bound on each geometry’s movement is needed for a stronger guarantee. The metric matters for nearest neighbours and cost: circular joints wrap, while limited joints and heterogeneous scales need an appropriate metric.
A check can also fail because geometry is incomplete: if the gripper, a table or link self-collision is excluded, a “free” path is free only for that model. In a changing work cell, update the world when the scene changes and consider uncertainty in poses and sizes. For debugging, record the geometry pair and configuration producing first contact; a Boolean label alone makes it hard to distinguish a real obstacle from an internal collision or misplaced frame.
Sampling: roadmaps and trees
A PRM takes free samples, connects neighbours using a local planner and searches the graph, for example with Dijkstra or A*. Construction can be amortized across many queries in a fixed cell. In a space with a positive-clearance path and suitable sampling and connection assumptions, failure probability tends to zero as samples increase: this is probabilistic completeness, not a promise for a finite count.
The classic formulation by Kavraki, Švestka, Latombe and Overmars (1996) builds probabilistic roadmaps for high-dimensional spaces. LaValle, Planning Algorithms develops configuration space and sampling methods.
An RRT starts a tree at the origin. For each sample it chooses the nearest node, advances at most one step and adds the segment if free. Regions with large Voronoi cells receive more samples, favouring frontier exploration. RRT-Connect grows from start and goal and tries to connect both trees. It is often useful for one query, but a narrow corridor may need many samples and the first path is not necessarily short. A shortcut replaces a subpath with an edge only if the whole edge is checked.
Step size changes the trade-off: long steps advance quickly in open space but are often rejected near obstacles and do not automatically solve a narrow corridor. Goal bias attempts an earlier connection, although too much reduces sampling elsewhere. Compare several seeds, retain failures and successes and report the budget: averaging cost only over successful runs can hide a low success rate. A PRM roadmap may suit repeated queries better, but loses its advantage if geometry changes and edges need revalidation.
RRT* considers neighbours to choose a low-cost parent and rewires neighbours if going through the new node reduces their cost. The improvement must propagate to descendants. In dimensions, a radius on the order of with suitable conditions and constants permits asymptotic optimality: cost converges to the optimum under the theorem’s assumptions, not in each finite run. Ordinary RRT generally lacks this property. Karaman and Frazzoli (2011) establish this distinction; Kuffner and LaValle (2000) introduce RRT-Connect.
In the second figure the trees receive the same samples and seed, but their structures diverge. The RRT* radius shrinks as in the 2D square, and the nearest neighbour is also considered. The segment-against-rectangles test is geometric; the goal connects only from a node within one step. Cost is Euclidean path length. A particular result depends on the map, budget and parameters: this demonstration does not verify the assumptions or prove convergence.
Optimize and time
Trajectory optimization represents a path by points and combines, for example, a smoothness penalty with a penalty for obstacle proximity. Gradient descent can improve an initial trajectory, but the nonconvex cost has local minima. The third figure uses a point in a plane, a circle and distance at nodes: it is not CHOMP and does not prove collision freedom between nodes. With a symmetric path through the centre, the chosen gradient is exactly zero at the centre; moving a point breaks that symmetry. A sampling planner can provide an initialization on the obstacle’s other side.
CHOMP formulates trajectory improvement with a covariant gradient and smoothness metric; TrajOpt uses sequential convex optimization and considers continuous collision. Their formulations are richer than the toy figure and still require solution validation.
Time parameterization transforms into . For each lab segment take , : and velocity match at the endpoints, but acceleration can jump between segments. Since and , choose large enough for all per-joint limits. A free path can still be dynamically impossible or saturate an actuator; checking reference velocities does not replace simulating and measuring tracking.
If a joint must travel 0.5 rad with a 0.5 rad/s limit, cubic velocity requires s. With maximum acceleration 1 rad/s² it also requires s; choose the larger value. For multiple joints take the maximum of their constraints because all share the same . Stopping at every point avoids velocity discontinuities but may create slow motion; a more advanced method can retain velocity between segments and optimize times while respecting acceleration, torque and robot constraints.
Lab: four planners
This lab implements periodic distances, collision of a two-link arm with circles and checking of sampled angular segments. cKDTree uses boxsize=2π for neighbours on the torus; PRM runs Dijkstra, RRT explores from the start, RRT-Connect alternates two trees and RRT* propagates costs on rewiring. Two maps, several seeds and two budgets form a small trial, not a conclusive benchmark. Mean cost is calculated only over successes; time includes construction and search and depends on the environment. The browser cell uses one seed and reduced budgets; the next repeats an expanded local comparison with three seeds.
import numpy as np, time, heapq
from scipy.spatial import cKDTree
TAU=2*np.pi
def delta(a,b):return (np.asarray(b)-a+np.pi)%TAU-np.pi
def dist(a,b):return float(np.linalg.norm(delta(a,b)))
def wrap(q):return np.asarray(q)%TAU
def point_segment(p,a,b):
d=b-a;t=np.clip(np.dot(p-a,d)/np.dot(d,d),0,1)
return np.linalg.norm(a+t*d-p)
def free(q,obstacles):
a=np.zeros(2);b=np.array([np.cos(q[0]),np.sin(q[0])]);c=b+np.array([np.cos(q.sum()),np.sin(q.sum())])
return all(point_segment(np.array([x,y]),a,b)>r and point_segment(np.array([x,y]),b,c)>r for x,y,r in obstacles)
def edge(a,b,obstacles,res=.04):
d=delta(a,b);n=max(1,int(np.ceil(np.linalg.norm(d)/res)))
qs=(a+np.linspace(0,1,n+1)[:,None]*d)%TAU
elbow=np.column_stack((np.cos(qs[:,0]),np.sin(qs[:,0])))
direction=np.column_stack((np.cos(qs.sum(axis=1)),np.sin(qs.sum(axis=1))))
for x,y,r in obstacles:
p=np.array([x,y]);u=np.clip(elbow@p,0,1);v=np.clip(np.sum((p-elbow)*direction,axis=1),0,1)
if np.any(np.linalg.norm(elbow*u[:,None]-p,axis=1)<=r) or np.any(np.linalg.norm(elbow+direction*v[:,None]-p,axis=1)<=r):return False
return True
def tree(points):return cKDTree(np.asarray(points),boxsize=TAU)
def nearest(points,q):return int(tree(points).query(wrap(q))[1])
def steer(a,b,step):
d=delta(a,b);return wrap(a+d*min(1,step/max(np.linalg.norm(d),1e-12)))
def cost(path):return sum(dist(a,b) for a,b in zip(path[:-1],path[1:]))
def back(points,parents,i):
result=[]
while i>=0:result.append(points[i]);i=parents[i]
return result[::-1]
def prm(start,goal,obs,n,rng,k=12):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start),wrap(goal)]
for _ in range(n):
q=rng.uniform(0,TAU,2)
if free(q,obs):points.append(q)
kd=tree(points);graph=[[] for _ in points];seen=set()
for i,q in enumerate(points):
_,near=kd.query(q,k=min(k+1,len(points)))
for j in np.atleast_1d(near):
j=int(j);pair=tuple(sorted((i,j)))
if i==j or pair in seen:continue
seen.add(pair)
if edge(q,points[j],obs):
w=dist(q,points[j]);graph[i].append((j,w));graph[j].append((i,w))
best=[np.inf]*len(points);best[0]=0;prev=[-1]*len(points);queue=[(0.,0)]
while queue:
c,i=heapq.heappop(queue)
if c>best[i]:continue
if i==1:return back(points,prev,1)
for j,w in graph[i]:
if c+w<best[j]:best[j]=c+w;prev[j]=i;heapq.heappush(queue,(best[j],j))
return None
def rrt(start,goal,obs,n,rng,step=.25):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start)];parents=[-1]
for _ in range(n):
q=wrap(goal) if rng.random()<.1 else rng.uniform(0,TAU,2);i=nearest(points,q);new=steer(points[i],q,step)
if dist(points[i],new)<1e-12 or not edge(points[i],new,obs):continue
points.append(new);parents.append(i)
if dist(new,goal)<=step and edge(new,goal,obs):return back(points,parents,len(points)-1)+[wrap(goal)]
return None
def rrt_connect(start,goal,obs,n,rng,step=.25):
if not free(start,obs) or not free(goal,obs):return None
a=[wrap(start)];ap=[-1];b=[wrap(goal)];bp=[-1];forward=True
for _ in range(n):
q=rng.uniform(0,TAU,2);i=nearest(a,q);new=steer(a[i],q,step)
if dist(a[i],new)>1e-12 and edge(a[i],new,obs):
a.append(new);ap.append(i);ia=len(a)-1;j=nearest(b,new)
while True:
old=b[j];qnext=steer(old,new,step)
if dist(old,qnext)<1e-12:reached=True;break
if not edge(old,qnext,obs):reached=False;break
b.append(qnext);bp.append(j);j=len(b)-1
if dist(qnext,new)<1e-9:reached=True;break
if reached:
left=back(a,ap,ia);right=back(b,bp,j)
path=left+right[-2::-1]
return path if forward else path[::-1]
a,b=b,a;ap,bp=bp,ap;forward=not forward
return None
def rrt_star(start,goal,obs,n,rng,step=.25,gamma=3.):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start)];parents=[-1];costs=[0.]
for _ in range(n):
q=wrap(goal) if rng.random()<.1 else rng.uniform(0,TAU,2);kd=tree(points);i=int(kd.query(q)[1]);new=steer(points[i],q,step)
if dist(points[i],new)<1e-12 or not edge(points[i],new,obs):continue
radius=min(1.,gamma*np.sqrt(np.log(len(points)+1)/(len(points)+1)));near=kd.query_ball_point(new,radius);parent=i;c=costs[i]+dist(points[i],new)
for j in near:
candidate=costs[j]+dist(points[j],new)
if candidate<c and edge(points[j],new,obs):parent=j;c=candidate
idx=len(points);points.append(new);parents.append(parent);costs.append(c)
def ancestor(j):
p=idx
while p>=0:
if p==j:return True
p=parents[p]
return False
for j in near:
candidate=c+dist(points[j],new)
if j!=parent and not ancestor(j) and candidate+1e-12<costs[j] and edge(points[j],new,obs):
shift=candidate-costs[j];parents[j]=idx;stack=[j]
while stack:
v=stack.pop();costs[v]+=shift;stack.extend(t for t,p in enumerate(parents) if p==v)
options=[(costs[i]+dist(q,goal),i) for i,q in enumerate(points) if dist(q,goal)<=step and edge(q,goal,obs)]
return None if not options else back(points,parents,min(options)[1])+[wrap(goal)]
start=np.array([4.8,1.]);goal=np.array([1.2,5.3])
maps={'un círculo':[(.8,.5,.3)],'dos círculos':[(.8,.5,.3),(.1,1.3,.3)]}
for mapname,obstacles in maps.items():
assert free(start,obstacles) and free(goal,obstacles)
for budget in (100,250):
for planner in [prm,rrt,rrt_connect,rrt_star]:
values=[];times=[]
for seed in (7,):
t=time.perf_counter();path=planner(start,goal,obstacles,budget,np.random.default_rng(seed));times.append(time.perf_counter()-t)
if path is not None:
assert all(edge(a,b,obstacles,res=.01) for a,b in zip(path[:-1],path[1:]));values.append(cost(path))
print(mapname,budget,planner.__name__,'éxitos',len(values),'/ 1','coste medio',round(np.mean(values),3) if values else None,'segundos medios',round(np.mean(times),3))The local version runs more samples and seeds using the same functions. It requires NumPy and SciPy and records cost only on success.
import numpy as np, time, heapq
from scipy.spatial import cKDTree
TAU=2*np.pi
def delta(a,b):return (np.asarray(b)-a+np.pi)%TAU-np.pi
def dist(a,b):return float(np.linalg.norm(delta(a,b)))
def wrap(q):return np.asarray(q)%TAU
def point_segment(p,a,b):
d=b-a;t=np.clip(np.dot(p-a,d)/np.dot(d,d),0,1)
return np.linalg.norm(a+t*d-p)
def free(q,obstacles):
a=np.zeros(2);b=np.array([np.cos(q[0]),np.sin(q[0])]);c=b+np.array([np.cos(q.sum()),np.sin(q.sum())])
return all(point_segment(np.array([x,y]),a,b)>r and point_segment(np.array([x,y]),b,c)>r for x,y,r in obstacles)
def edge(a,b,obstacles,res=.04):
d=delta(a,b);n=max(1,int(np.ceil(np.linalg.norm(d)/res)))
return all(free(wrap(a+d*i/n),obstacles) for i in range(n+1))
def tree(points):return cKDTree(np.asarray(points),boxsize=TAU)
def nearest(points,q):return int(tree(points).query(wrap(q))[1])
def steer(a,b,step):
d=delta(a,b);return wrap(a+d*min(1,step/max(np.linalg.norm(d),1e-12)))
def cost(path):return sum(dist(a,b) for a,b in zip(path[:-1],path[1:]))
def back(points,parents,i):
result=[]
while i>=0:result.append(points[i]);i=parents[i]
return result[::-1]
def prm(start,goal,obs,n,rng,k=12):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start),wrap(goal)]
for _ in range(n):
q=rng.uniform(0,TAU,2)
if free(q,obs):points.append(q)
kd=tree(points);graph=[[] for _ in points];seen=set()
for i,q in enumerate(points):
_,near=kd.query(q,k=min(k+1,len(points)))
for j in np.atleast_1d(near):
j=int(j);pair=tuple(sorted((i,j)))
if i==j or pair in seen:continue
seen.add(pair)
if edge(q,points[j],obs):
w=dist(q,points[j]);graph[i].append((j,w));graph[j].append((i,w))
best=[np.inf]*len(points);best[0]=0;prev=[-1]*len(points);queue=[(0.,0)]
while queue:
c,i=heapq.heappop(queue)
if c>best[i]:continue
if i==1:return back(points,prev,1)
for j,w in graph[i]:
if c+w<best[j]:best[j]=c+w;prev[j]=i;heapq.heappush(queue,(best[j],j))
return None
def rrt(start,goal,obs,n,rng,step=.25):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start)];parents=[-1]
for _ in range(n):
q=wrap(goal) if rng.random()<.1 else rng.uniform(0,TAU,2);i=nearest(points,q);new=steer(points[i],q,step)
if dist(points[i],new)<1e-12 or not edge(points[i],new,obs):continue
points.append(new);parents.append(i)
if dist(new,goal)<=step and edge(new,goal,obs):return back(points,parents,len(points)-1)+[wrap(goal)]
return None
def rrt_connect(start,goal,obs,n,rng,step=.25):
if not free(start,obs) or not free(goal,obs):return None
a=[wrap(start)];ap=[-1];b=[wrap(goal)];bp=[-1];forward=True
for _ in range(n):
q=rng.uniform(0,TAU,2);i=nearest(a,q);new=steer(a[i],q,step)
if dist(a[i],new)>1e-12 and edge(a[i],new,obs):
a.append(new);ap.append(i);ia=len(a)-1;j=nearest(b,new)
while True:
old=b[j];qnext=steer(old,new,step)
if dist(old,qnext)<1e-12:reached=True;break
if not edge(old,qnext,obs):reached=False;break
b.append(qnext);bp.append(j);j=len(b)-1
if dist(qnext,new)<1e-9:reached=True;break
if reached:
left=back(a,ap,ia);right=back(b,bp,j)
path=left+right[-2::-1]
return path if forward else path[::-1]
a,b=b,a;ap,bp=bp,ap;forward=not forward
return None
def rrt_star(start,goal,obs,n,rng,step=.25,gamma=3.):
if not free(start,obs) or not free(goal,obs):return None
points=[wrap(start)];parents=[-1];costs=[0.]
for _ in range(n):
q=wrap(goal) if rng.random()<.1 else rng.uniform(0,TAU,2);kd=tree(points);i=int(kd.query(q)[1]);new=steer(points[i],q,step)
if dist(points[i],new)<1e-12 or not edge(points[i],new,obs):continue
radius=min(1.,gamma*np.sqrt(np.log(len(points)+1)/(len(points)+1)));near=kd.query_ball_point(new,radius);parent=i;c=costs[i]+dist(points[i],new)
for j in near:
candidate=costs[j]+dist(points[j],new)
if candidate<c and edge(points[j],new,obs):parent=j;c=candidate
idx=len(points);points.append(new);parents.append(parent);costs.append(c)
def ancestor(j):
p=idx
while p>=0:
if p==j:return True
p=parents[p]
return False
for j in near:
candidate=c+dist(points[j],new)
if j!=parent and not ancestor(j) and candidate+1e-12<costs[j] and edge(points[j],new,obs):
shift=candidate-costs[j];parents[j]=idx;stack=[j]
while stack:
v=stack.pop();costs[v]+=shift;stack.extend(t for t,p in enumerate(parents) if p==v)
options=[(costs[i]+dist(q,goal),i) for i,q in enumerate(points) if dist(q,goal)<=step and edge(q,goal,obs)]
return None if not options else back(points,parents,min(options)[1])+[wrap(goal)]
start=np.array([4.8,1.]);goal=np.array([1.2,5.3])
maps={'un círculo':[(.8,.5,.3)],'dos círculos':[(.8,.5,.3),(.1,1.3,.3)]}
for mapname,obstacles in maps.items():
assert free(start,obstacles) and free(goal,obstacles)
for budget in (100,250):
for planner in [prm,rrt,rrt_connect,rrt_star]:
values=[];times=[]
for seed in (7,8,9):
t=time.perf_counter();path=planner(start,goal,obstacles,budget,np.random.default_rng(seed));times.append(time.perf_counter()-t)
if path is not None:
assert all(edge(a,b,obstacles,res=.01) for a,b in zip(path[:-1],path[1:]));values.append(cost(path))
print(mapname,budget,planner.__name__,'éxitos',len(values),'/ 3','coste medio',round(np.mean(values),3) if values else None,'segundos medios',round(np.mean(times),3))npm run lab and open the connection link.Each path found is checked again at angular resolution 0.01 rad, finer than the 0.04 rad used for planning. This reduces discretization errors but does not prove continuous collision freedom. On the second map a test trajectory passes near a circle; compare results and vary obstacles, seeds and budget before drawing conclusions.
Local lab: Panda among shelves
Install MuJoCo and NumPy; the first run downloads the Menagerie Panda at a pinned revision, or reuses ORYON_PANDA_DIR. We add three shelf boxes. The oracle uses MuJoCo contacts with a 2 cm shelf margin and rejects self-penetration. It finds a free goal whose direct line is blocked, plans over seven joints, tries shortcuts and checks a finer grid. The simulated robot uses ideal computed torque with an exact model; error, reference maxima, torque and penetration are measured.
import os,urllib.request,xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np, 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'):
name=mesh.get('file')
if name:
dest=root/'assets'/name;dest.parent.mkdir(parents=True,exist_ok=True)
if not dest.exists():urllib.request.urlretrieve(base+'assets/'+name,dest)
world=tree.find('worldbody')
for name,pos,size in [('shelf_left','.65 -.35 .45','.25 .025 .45'),('shelf_right','.65 .35 .45','.25 .025 .45'),('shelf_top','.65 0 .9','.25 .35 .025')]:
ET.SubElement(world,'geom',{'name':name,'type':'box','pos':pos,'size':size,'rgba':'.5 .5 .5 1'})
path=root/'panda_shelves.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
shelves={mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_GEOM,name) for name in ('shelf_left','shelf_right','shelf_top')}
for geom in shelves:model.geom_margin[geom]=.02
ids=[mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_JOINT,f'joint{i}') for i in range(1,8)];qa=model.jnt_qposadr[ids];va=model.jnt_dofadr[ids];limits=model.jnt_range[ids]
home=np.array([0,0,0,-1.57079,0,1.57079,-.7853]);data=mujoco.MjData(model)
def reset():
d=mujoco.MjData(model);mujoco.mj_resetDataKeyframe(model,d,0);mujoco.mj_forward(model,d);return d
def free(q):
mujoco.mj_resetDataKeyframe(model,data,0);data.qpos[qa]=q;mujoco.mj_forward(model,data)
return all(c.dist >= (.02 if c.geom1 in shelves or c.geom2 in shelves else 0.) for c in data.contact)
def edge(a,b,res=.08):
n=max(1,int(np.ceil(np.linalg.norm(b-a)/res)))
return all(free(a+(b-a)*i/n) for i in range(n+1))
print('home free',free(home),'contacts',data.ncon)
rng=np.random.default_rng(314)
goal=None
for _ in range(1000):
q=np.clip(home+rng.uniform(-1,1,7),limits[:,0]+.03,limits[:,1]-.03)
if free(q) and not edge(home,q):goal=q;break
print('goal',goal)
if goal is None:raise RuntimeError('No se encontró configuración libre con línea bloqueada')
print('goal free',free(goal),'direct edge',edge(home,goal))
def nearest(points,q):return int(np.argmin(np.linalg.norm(np.asarray(points)-q,axis=1)))
def trace(points,parents,index):
out=[]
while index>=0:out.append(points[index]);index=parents[index]
return out[::-1]
def rrt_connect(start,goal,seed=123,limit=2500,step=.35):
gen=np.random.default_rng(seed);a=[start];ap=[-1];b=[goal];bp=[-1];forward=True
for it in range(limit):
q=gen.uniform(limits[:,0],limits[:,1]);i=nearest(a,q);d=q-a[i];new=a[i]+d*min(1,step/max(np.linalg.norm(d),1e-12))
if edge(a[i],new):
a.append(new);ap.append(i);j=nearest(b,new)
while True:
old=b[j];d=new-old;dist=np.linalg.norm(d)
if dist<1e-10:reached=True;break
nextq=old+d*min(1,step/dist)
if not edge(old,nextq):reached=False;break
b.append(nextq);bp.append(j);j=len(b)-1
if np.linalg.norm(nextq-new)<1e-10:reached=True;break
if reached:
p=trace(a,ap,len(a)-1)+trace(b,bp,j)[-2::-1]
return (p if forward else p[::-1]),it+1
a,b=b,a;ap,bp=bp,ap;forward=not forward
raise RuntimeError('No se encontró camino con esta semilla y presupuesto')
path,attempts=rrt_connect(home,goal)
print('RRT-Connect:',attempts,'muestras;',len(path),'puntos')
for _ in range(200):
i,j=sorted(rng.choice(len(path),2,replace=False))
if j>i+1 and edge(path[i],path[j],.04):path=path[:i+1]+path[j:]
assert all(edge(a,b,.02) for a,b in zip(path[:-1],path[1:]))
print('atajos:',len(path),'puntos; longitud',sum(np.linalg.norm(b-a) for a,b in zip(path[:-1],path[1:])))
vmax=.5;amax=1.;dt=model.opt.timestep;d=reset();M=np.zeros((model.nv,model.nv));bias=np.zeros(model.nv);errors=[];refv=[];refa=[];max_torque=0.;penetration=0.
for startq,endq in zip(path[:-1],path[1:]):
diff=endq-startq
T=max(1.5*np.max(np.abs(diff))/vmax,np.sqrt(6*np.max(np.abs(diff))/amax),dt)
count=int(np.ceil(T/dt));T=count*dt
for n in range(count):
u=n/count;s=3*u*u-2*u*u*u;sd=(6*u-6*u*u)/T;sdd=(6-12*u)/(T*T)
qref=startq+diff*s;vref=diff*sd;aref=diff*sdd
mujoco.mj_forward(model,d);mujoco.mj_rne(model,d,0,bias)
try:mujoco.mj_fullM(model,d,M)
except TypeError:mujoco.mj_fullM(model,M,d.qM)
accel=np.zeros(model.nv);accel[va]=aref+200*(qref-d.qpos[qa])+28*(vref-d.qvel[va]);accel[7:]=200*(.04-d.qpos[7:9])-28*d.qvel[7:]
torque=M@accel+bias;d.qfrc_applied[:]=torque;max_torque=max(max_torque,float(np.max(np.abs(torque))))
errors.append(np.linalg.norm(qref-d.qpos[qa]));refv.append(np.max(np.abs(vref)));refa.append(np.max(np.abs(aref)))
for c in d.contact:penetration=max(penetration,max(0.,-c.dist))
mujoco.mj_step(model,d)
print('RMS articular (rad):',np.sqrt(np.mean(np.square(errors))),'vref máxima:',max(refv),'aref máxima:',max(refa),'par máximo:',max_torque,'penetración máxima:',penetration)
assert max(refv)<=vmax+1e-9 and max(refa)<=amax+1e-9 and np.isfinite(errors).all()npm run lab and open the connection link.The 0.5 rad/s and 1 rad/s² limits apply to the reference and do not guarantee real motor or torque limits. The trajectory stops at each spline point for simplicity and is not time-optimal. The detector samples configurations and tracking may deviate from them, so penetration is measured during simulation. Any physical application would need appropriate models, limits, perception and validation.
Practice
Step 1 of 3. What upper bound applies to the probability that a particular ball remains empty after n independent samples?
rrt(start, goal, collision_free, sample, step, max_samples). Configurations are NumPy vectors; collision_free(a,b) checks the whole segment and sample() returns a sample. Return a list of points from start to goal or None, never advancing more than step per edge.import numpy as np
def rrt(start, goal, collision_free, sample, step, max_samples):
pass