Commit fea1e38f authored by Nicolas Mansard's avatar Nicolas Mansard Committed by Nicolas Mansard
Browse files

[TP0] Candidate final for 2022.

parent 994b9547
%% Cell type:markdown id: tags:
# Introduction to numerical robotics
This notebook is a very general introduction to Pinocchio. It presents the main method to manipulate the geometry model of a manipulator robot: set the configuration, compute the position of an effector, check the collision or the distance to the obstacle. The main idea is to give a brief introduction of the general topic: how to discover and learn a robot movement constrained by the environment, using iterative optimization methods.
%% Cell type:code id: tags:
``` python
import magic_donotload
```
%% Cell type:markdown id: tags:
## Set up
For this class, we need the UR5 robot model (urdf, in the robotpkg_example_robot_data), the pinocchio python software, the python optimizers from scipy and for the display of the results: the gepetto viewer and the python matplotlib. We have that with this set of imports:
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_import
import pinocchio as pin
from utils.meshcat_viewer_wrapper import MeshcatVisualizer
import time
import numpy as np
from numpy.linalg import inv,norm,pinv,svd,eig
from scipy.optimize import fmin_bfgs,fmin_slsqp
from utils.load_ur5_with_obstacles import load_ur5_with_obstacles,Target
import matplotlib.pylab as plt
```
%% Cell type:markdown id: tags:
Let's first load the robot model and display it. You should first start Gepetto Viewer: in a shell (CTRL-ALT-T to open a terminal), run the command: gepetto-gui. A new GUI widow will open (with the logo of our team): this is the viewer. You are not suppose to close this window during the rest of the class, and if you do close it, remember to reopen it before trying to display anything from Python.
%% Cell type:markdown id: tags:
For this class, I wrapped the methods to load the robot model and create the obstacle field.
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_robot
robot = load_ur5_with_obstacles(reduced=True)
```
%% Cell type:markdown id: tags:
The next few lines initialize a 3D viewer.
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_viewer
viz = MeshcatVisualizer(robot,url='classical')
viz = MeshcatVisualizer(robot)
viz.display(robot.q0)
```
%% Cell type:code id: tags:
``` python
hasattr(viz.viewer, 'jupyter_cell') and viz.viewer.jupyter_cell()
```
%% Cell type:markdown id: tags:
The scene should not be displayed in the viewer (check it). The robot and the red obstacles are encoded in the robot object (we will not need to see in depth what is inside this object). The object Target is the green dot that the robot should reach. You can change the target position by editing target.position, and display the new position with target.display().
You can display a new configuration of the robot with viz.display (take a numpy.array of dimension 6 in input):
%% Cell type:code id: tags:
``` python
viz.display(np.array([1.,-1.5]))
```
%% Cell type:markdown id: tags:
We also set up a target with is visualized as a green dot:
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_target
target = Target(viz,position = np.array([.5,.5]))
```
%% Cell type:markdown id: tags:
## Using the robot model
The robot is originally a 6 degrees-of-freedom (DOF) manipulator. Yet to make the example simple, we will only use the joints 1 and 2. The model has simply be loaded with "frozen" extra joints, which will then not appear in this notebook. Just load the model with reduced=False if you want to recover a model with full DOF.
%% Cell type:markdown id: tags:
The following function computes the position of the end effector (in 2d):
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_endef
def endef(q):
'''Return the 2d position of the end effector.'''
pin.framesForwardKinematics(robot.model,robot.data,q)
return robot.data.oMf[-1].translation[[0,2]]
```
%% Cell type:markdown id: tags:
The next function computes the distance between the end effector and the target.
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_dist
def dist(q):
'''Return the distance between the end effector end the target (2d).'''
return norm(endef(q)-target.position)
```
%% Cell type:markdown id: tags:
The last function checks if the robot is in collision, and returns True if a collision is detected.
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_coll
def coll(q):
'''Return true if in collision, false otherwise. TOTO '''
'''Return true if in collision, false otherwise.'''
pin.updateGeometryPlacements(robot.model,robot.data,robot.collision_model,robot.collision_data,q)
return pin.computeCollisions(robot.collision_model,robot.collision_data,False)
```
%% Cell type:markdown id: tags:
## Random search of a valid configuration
The free space is difficult to represent explicitely. We can sample the configuration space until a free configuration is found:
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_qrand
def qrand(check=False):
'''
Return a random configuration. If check is True, this
configuration is not is collision
'''
while True:
q = np.random.rand(2)*6-3 # sample between -3 and +3.
q = np.random.rand(2)*6.4-3.2 # sample between -3.2 and +3.2.
if not check or not coll(q): return q
```
%% Cell type:code id: tags:
``` python
viz.display(qrand(check=True))
```
%% Cell type:markdown id: tags:
Let's now find a valid configuration that is arbitrarily close to the target: sample until dist is small enough and coll is false (you may want to display the random trials inside the loop).
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_qrand
def qrand(check=False):
'''
Return a random configuration. If check is True, this
configuration is not is collision
'''
while True:
q = np.random.rand(2)*6-3 # sample between -3 and +3.
q = np.random.rand(2)*6.4-3.2 # sample between -3.2 and +3.2.
if not check or not coll(q): return q
```
%% Cell type:markdown id: tags:
## From a random configuration to the target
Let' s now start from a random configuration. How can we find a path that bring the robot toward the target without touching the obstacles. Any idea?
%% Cell type:code id: tags:
``` python
%do_not_load tp0/generated/simple_path_planning_random_descent
```
%% Cell type:markdown id: tags:
## Configuration space
Let's try to have a better look of the configuration space. In this case, it is easy, as it is dimension 2: we can sample it exhaustively and plot it in 2d. For that, let's introduce another function to compute the distance to collision:
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_coll
def coll(q):
'''Return true if in collision, false otherwise. TOTO '''
# %load tp0/generated/simple_path_planning_colldist
def collisionDistance(q):
'''Return the minimal distance between robot and environment. '''
pin.updateGeometryPlacements(robot.model,robot.data,robot.collision_model,robot.collision_data,q)
return pin.computeCollisions(robot.collision_model,robot.collision_data,False)
if pin.computeCollisions(robot.collision_model,robot.collision_data,False): 0
idx = pin.computeDistances(robot.collision_model,robot.collision_data)
return robot.collision_data.distanceResults[idx].min_distance
```
%% Cell type:markdown id: tags:
Now, let's sample the configuration space and plot the distance-to-target and the distance-to-obstacle field (I put 500 samples to spare your CPU, but you need at least 10x more for obtaining a good picture).
%% Cell type:code id: tags:
``` python
# %load tp0/generated/simple_path_planning_sample
def sampleSpace(nbSamples=500):
'''
Sample nbSamples configurations and store them in two lists depending
if the configuration is in free space (hfree) or in collision (hcol), along
with the distance to the target and the distance to the obstacles.
'''
hcol = []
hfree = []
for i in range(nbSamples):
q = qrand(False)
if not coll(q):
hfree.append( list(q.flat) + [ dist(q), collisionDistance(q) ])
else:
hcol.append( list(q.flat) + [ dist(q), 1e-2 ])
return hcol,hfree
def plotConfigurationSpace(hcol,hfree):
def plotConfigurationSpace(hcol,hfree,markerSize=20):
'''
Plot 2 "scatter" plots: the first one plot the distance to the target for
each configuration, the second plots the distance to the obstacles (axis q1,q2,
distance in the color space).
'''
htotal = hcol + hfree
h=np.array(htotal)
plt.subplot(2,1,1)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=markerSize,lw=0)
plt.title("Distance to the target")
plt.colorbar()
plt.subplot(2,1,2)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=markerSize,lw=0)
plt.title("Distance to the obstacles")
plt.colorbar()
hcol,hfree = sampleSpace(100)
plotConfigurationSpace(hcol,hfree)
```
%% Cell type:markdown id: tags:
You can try to match your representation of the free space of the robot with this plot.
As an example, you can display on this plot some trajectories discover by random walk.
%% Cell type:code id: tags:
``` python
%do_not_load tp0/generated/simple_path_planning_traj
```
%% Cell type:code id: tags:
``` python
if 'traj' in locals():
plotConfigurationSpace(hcol,hfree)
plt.plot(traj[:,0],traj[:,1],'r',lw=3)
```
%% Cell type:markdown id: tags:
## Optimize the distance under non-collision constraint
Finally, let's use one of the classic python solvers (from scipy) to search for a robot configuration that optimizes the distance to the target, under the constraint that the distance to collision is positive.
For that, we need to define a cost function (taking the robot configuration and return a scalar) and a constraint function (taking again the robot configuration and returning a scalar or a vector of scalar that should be positive). We additionally use the "callback" functionnality of the solver, to render the robot configuration corresponding to the current value of the decision variable inside the solver algorithm.
We are going to use the "SLSQP" solver from scipy, which implements a "sequential quadratic program" algorithm and accepts constraints.
%% Cell type:code id: tags:
``` python
%do_not_load tp0/generated/simple_path_planning_optim
```
%% Cell type:markdown id: tags:
Look at the output of the solver. It always returns a variable value, but sometimes the algorithm fails being traped in an unfeasible region. Most of the time, the solver converges to a local minimum where the final distance to the target is nonzero
%% Cell type:code id: tags:
``` python
%do_not_load tp0/generated/simple_path_planning_useit
```
......
def collisionDistance(q):
'''Return the minimal distance between robot and environment. '''
threshold = 1e-2
pin.updateGeometryPlacements(robot.model,robot.data,robot.collision_model,robot.collision_data,q)
if pin.computeCollisions(robot.collision_model,robot.collision_data,False): return -threshold
if pin.computeCollisions(robot.collision_model,robot.collision_data,False): 0
idx = pin.computeDistances(robot.collision_model,robot.collision_data)
return pin.computeDistance(robot.collision_model,robot.collision_data,idx).min_distance - threshold
return robot.collision_data.distanceResults[idx].min_distance
......@@ -4,5 +4,5 @@ def qrand(check=False):
configuration is not is collision
'''
while True:
q = np.random.rand(2)*6-3 # sample between -3 and +3.
q = np.random.rand(2)*6.4-3.2 # sample between -3.2 and +3.2.
if not check or not coll(q): return q
# Random descent: crawling from one free configuration to the target with random
# steps.
def randomDescent():
q = qrand(check=True)
def randomDescent(q0 = None):
q = qrand(check=True) if q0 is None else q0
hist = [ q.copy() ]
for i in range(100):
dq = qrand()*.1 # Choose a random step ...
qtry = q+dq # ... apply
if dist(q)>dist(q+dq) and not coll(q+dq): # If distance decrease without collision ...
q = q+dq # ... keep the step
hist.append(q.copy()) # ... keep a trace of it
viz.display(q) # ... display it
time.sleep(5e-3) # ... and sleep for a short while
randomDescent()
return hist
randomDescent();
......@@ -14,7 +14,7 @@ def sampleSpace(nbSamples=500):
hcol.append( list(q.flat) + [ dist(q), 1e-2 ])
return hcol,hfree
def plotConfigurationSpace(hcol,hfree):
def plotConfigurationSpace(hcol,hfree,markerSize=20):
'''
Plot 2 "scatter" plots: the first one plot the distance to the target for
each configuration, the second plots the distance to the obstacles (axis q1,q2,
......@@ -23,11 +23,11 @@ def plotConfigurationSpace(hcol,hfree):
htotal = hcol + hfree
h=np.array(htotal)
plt.subplot(2,1,1)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=markerSize,lw=0)
plt.title("Distance to the target")
plt.colorbar()
plt.subplot(2,1,2)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=markerSize,lw=0)
plt.title("Distance to the obstacles")
plt.colorbar()
......
......@@ -54,18 +54,17 @@ def qrand(check=False):
configuration is not is collision
'''
while True:
q = np.random.rand(2)*6-3 # sample between -3 and +3.
q = np.random.rand(2)*6.4-3.2 # sample between -3.2 and +3.2.
if not check or not coll(q): return q
# %end_load
# %do_load colldist
def collisionDistance(q):
'''Return the minimal distance between robot and environment. '''
threshold = 1e-2
pin.updateGeometryPlacements(robot.model,robot.data,robot.collision_model,robot.collision_data,q)
if pin.computeCollisions(robot.collision_model,robot.collision_data,False): return -threshold
if pin.computeCollisions(robot.collision_model,robot.collision_data,False): 0
idx = pin.computeDistances(robot.collision_model,robot.collision_data)
return pin.computeDistance(robot.collision_model,robot.collision_data,idx).min_distance - threshold
return robot.collision_data.distanceResults[idx].min_distance
# %end_load
################################################################################
################################################################################
......@@ -91,16 +90,19 @@ viz.display(qrandTarget())
# %do_not_load random_descent
# Random descent: crawling from one free configuration to the target with random
# steps.
def randomDescent():
q = qrand(check=True)
def randomDescent(q0 = None):
q = qrand(check=True) if q0 is None else q0
hist = [ q.copy() ]
for i in range(100):
dq = qrand()*.1 # Choose a random step ...
qtry = q+dq # ... apply
if dist(q)>dist(q+dq) and not coll(q+dq): # If distance decrease without collision ...
q = q+dq # ... keep the step
hist.append(q.copy()) # ... keep a trace of it
viz.display(q) # ... display it
time.sleep(5e-3) # ... and sleep for a short while
randomDescent()
return hist
randomDescent();
# %end_load
################################################################################
......@@ -124,7 +126,7 @@ def sampleSpace(nbSamples=500):
hcol.append( list(q.flat) + [ dist(q), 1e-2 ])
return hcol,hfree
def plotConfigurationSpace(hcol,hfree):
def plotConfigurationSpace(hcol,hfree,markerSize=20):
'''
Plot 2 "scatter" plots: the first one plot the distance to the target for
each configuration, the second plots the distance to the obstacles (axis q1,q2,
......@@ -133,11 +135,11 @@ def plotConfigurationSpace(hcol,hfree):
htotal = hcol + hfree
h=np.array(htotal)
plt.subplot(2,1,1)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,2],s=markerSize,lw=0)
plt.title("Distance to the target")
plt.colorbar()
plt.subplot(2,1,2)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=20,lw=0)
plt.scatter(h[:,0],h[:,1],c=h[:,3],s=markerSize,lw=0)
plt.title("Distance to the obstacles")
plt.colorbar()
......@@ -149,6 +151,26 @@ plotConfigurationSpace(hcol,hfree)
################################################################################
################################################################################
### Plot random trajectories in the same plot
# %do_not_load traj
qinit = np.array([-1.1, -3. ])
for i in range(100):
traj = randomDescent(qinit)
if dist(traj[-1])<5e-2:
print('We found a good traj!')
break
traj = np.array(traj)
### Chose trajectory end to be in [-pi,pi]
qend = (traj[-1]+np.pi) % (2*np.pi) - np.pi
### Take the entire trajectory it modulo 2 pi
traj += (qend-traj[-1])
# %end_load
plt.plot(traj[:,0],traj[:,1],'r',lw=5)
################################################################################
################################################################################
################################################################################
# %do_not_load optim
def cost(q):
'''
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment