This example shows how to position the end effector of a manipulator robot to a given pose (position and orientation). The example employs a simple Jacobian-based iterative algorithm, which is called closed-loop inverse kinematics (CLIK).
Python
1import numpy as np
2import pinocchio
3from numpy.linalg import norm, solve
4
5model = pinocchio.buildSampleModelManipulator()
6data = model.createData()
7
8JOINT_ID = 6
9oMdes = pinocchio.SE3(np.eye(3), np.array([1.0, 0.0, 1.0]))
10
12eps = 1e-4
13IT_MAX = 1000
14DT = 1e-1
15damp = 1e-12
16
17i = 0
18while True:
20 iMd = data.oMi[JOINT_ID].actInv(oMdes)
21 err = pinocchio.log(iMd).vector
22 if norm(err) < eps:
23 success = True
24 break
25 if i >= IT_MAX:
26 success = False
27 break
29 J = -np.dot(pinocchio.Jlog6(iMd.inverse()), J)
30 v = -J.T.dot(solve(J.dot(J.T) + damp * np.eye(6), err))
32 if not i % 10:
33 print(f"{i}: error = {err.T}")
34 i += 1
35
36if success:
37 print("Convergence achieved!")
38else:
39 print(
40 "\n"
41 "Warning: the iterative algorithm has not reached convergence "
42 "to the desired precision"
43 )
44
45print(f"\nresult: {q.flatten().tolist()}")
46print(f"\nfinal error: {err.T}")
void integrate(const ModelTpl< Scalar, Options, JointCollectionTpl > &model, const Eigen::MatrixBase< ConfigVectorType > &q, const Eigen::MatrixBase< TangentVectorType > &v, const Eigen::MatrixBase< ReturnType > &qout)
Integrate a configuration vector for the specified model for a tangent vector during one unit time.
void forwardKinematics(const ModelTpl< Scalar, Options, JointCollectionTpl > &model, DataTpl< Scalar, Options, JointCollectionTpl > &data, const Eigen::MatrixBase< ConfigVectorType > &q)
Update the joint placements according to the current joint configuration.
void computeJointJacobian(const ModelTpl< Scalar, Options, JointCollectionTpl > &model, DataTpl< Scalar, Options, JointCollectionTpl > &data, const Eigen::MatrixBase< ConfigVectorType > &q, const JointIndex joint_id, const Eigen::MatrixBase< Matrix6Like > &J)
Computes the Jacobian of a specific joint frame expressed in the local frame of the joint and store t...
void neutral(const ModelTpl< Scalar, Options, JointCollectionTpl > &model, const Eigen::MatrixBase< ReturnType > &qout)
Return the neutral configuration element related to the model configuration space.
Explanation of the code
First of all, we import the necessary libraries and we create the Model and Data objects:
2from numpy.linalg
import norm, solve
4model = pinocchio.buildSampleModelManipulator()
5data = model.createData()
The end effector corresponds to the 6th joint
and its desired pose is given as
8oMdes = pinocchio.SE3(np.eye(3), np.array([1.0, 0.0, 1.0]))
Next, we define an initial configuration
This is the starting point of the algorithm. A priori, any valid configuration would work. We decided to use the robot's neutral configuration, returned by algorithm neutral. For a simple manipulator such as the one in this case, it simply corresponds to an all-zero vector, but using this method generalizes well to more complex kinds of robots, ensuring validity.
Next, we set some computation-related values
corresponding to the desired position precision (we will see later what it exactly means), a maximum number of iterations (to avoid infinite looping in case the position is not reachable), a positive "time step" defining the convergence rate, and a fixed damping factor for the pseudoinversion (see below).
Then, we begin the iterative process. At each iteration, we begin by computing the forward kinematics:
Next, we compute the error between the desired pose d and the current one i, expressed in the current joint frame i:
20 iMd = data.oMi[JOINT_ID].actInv(oMdes)
21 err = pinocchio.log(iMd).vector
Here, data.oMi[JOINT_ID] corresponds to the placement of the sixth joint (previously computed by forwardKinematics), dMi corresponds to the transformation between the desired pose and the current one, and err is the error. In order to compute the error, we employed log: this is a Motion object, and it is one way of computing an error in \(SO(3)\) as a six-dimensional vector.
If the error norm is below the previously-defined threshold, we have found the solution and we break out of the loop
Notice that, strictly speaking, the norm of a spatial velocity does not make physical sense, since it mixes linear and angular quantities. A more rigorous implementation should treat the linar part and the angular part separately. In this example, however, we choose to slightly abuse the notation in order to keep it simple.
If we have reached the maximum number of iterations, it means a solution has not been found. We take notice of the failure and we also break
Otherwise, we search for another configuration trying to reduce the error.
We start by computing the Jacobian in the joint frame:
To get the proper Jacobian of our task, we should include a call to the Jlog6 function (see e.g. this note for derivation details):
29 J = -np.dot(pinocchio.Jlog6(iMd.inverse()), J)
Next, we can compute the evolution of the configuration by solving the inverse kinematics. In order to avoid problems at singularities, we employ the damped pseudo-inverse: \(v = - J^T (J J^T + \lambda I)^{-1} e\) implementing the equation as
30 v = -J.T.dot(solve(J.dot(J.T) + damp * np.eye(6), err))
Notice that this way to compute the damped pseudo-inverse was chosen mostly because of its simplicity of implementation. It is not necessarily the best nor the fastest way, and using a fixed damping factor \(\lambda\) is not necessarily the best course of action.
Finally, we can add the obtained tangent vector to the current configuration
where integrate in our case amounts to a simple sum. The resulting error will be verified in the next iteration.
At the end of the loop, we display the result:
38 print(
"Convergence achieved!")
42 "Warning: the iterative algorithm has not reached convergence " 43 "to the desired precision" 46print(f
"\nresult: {q.flatten().tolist()}")
47print(f
"\nfinal error: {err.T}")
C++
The equivalent C++ implemetation is given below
1#include <Eigen/Cholesky>
2#include <Eigen/Core>
3#include <Eigen/SparseCore>
4
5#include <boost/core/ref.hpp>
6#include <boost/fusion/algorithm.hpp>
7#include <boost/fusion/functional.hpp>
8#include <boost/variant.hpp>
9
10#include <iostream>
11#include <vector>
12
13#include "pinocchio/algorithm/check-data.hpp"
14#include "pinocchio/algorithm/jacobian.hpp"
15#include "pinocchio/algorithm/joint-configuration.hpp"
16#include "pinocchio/algorithm/kinematics.hpp"
17#include "pinocchio/eigen-common.hpp"
18#include "pinocchio/math.hpp"
19#include "pinocchio/multibody.hpp"
20#include "pinocchio/multibody/joint.hpp"
21#include "pinocchio/multibody/sample-models.hpp"
22#include "pinocchio/spatial.hpp"
23#include "pinocchio/utils/check.hpp"
24#include "pinocchio/utils/static-if.hpp"
25
26int main(int , char ** )
27{
28 pinocchio::Model model;
29 pinocchio::buildModels::manipulator(model);
30 pinocchio::Data data(model);
31
32 const int JOINT_ID = 6;
33 const pinocchio::SE3 oMdes(Eigen::Matrix3d::Identity(), Eigen::Vector3d(1., 0., 1.));
34
36 const double eps = 1e-4;
37 const int IT_MAX = 1000;
38 const double DT = 1e-1;
39 const double damp = 1e-6;
40
41 pinocchio::Data::Matrix6x J(6, model.nv);
42 J.setZero();
43
44 bool success = false;
45 typedef Eigen::Matrix<double, 6, 1> Vector6d;
46 Vector6d err;
47 Eigen::VectorXd v(model.nv);
48 for (int i = 0;; i++)
49 {
51 const pinocchio::SE3 iMd = data.oMi[JOINT_ID].actInv(oMdes);
52 err = pinocchio::log6(iMd).toVector();
53 if (err.norm() < eps)
54 {
55 success = true;
56 break;
57 }
58 if (i >= IT_MAX)
59 {
60 success = false;
61 break;
62 }
64 pinocchio::Data::Matrix6 Jlog;
65 pinocchio::Jlog6(iMd.inverse(), Jlog);
66 J = -Jlog * J;
67 pinocchio::Data::Matrix6 JJt;
68 JJt.noalias() = J * J.transpose();
69 JJt.diagonal().array() += damp;
70 v.noalias() = -J.transpose() * JJt.ldlt().solve(err);
72 if (!(i % 10))
73 std::cout << i << ": error = " << err.transpose() << std::endl;
74 }
75
76 if (success)
77 {
78 std::cout << "Convergence achieved!" << std::endl;
79 }
80 else
81 {
82 std::cout
83 << "\nWarning: the iterative algorithm has not reached convergence to the desired precision"
84 << std::endl;
85 }
86
87 std::cout << "\nresult: " << q.transpose() << std::endl;
88 std::cout << "\nfinal error: " << err.transpose() << std::endl;
89}
Explanation of the code
The code follows exactly the same steps as Python. Apart from the usual syntactic discrepancies between Python and C++, we can identify two major differences. The first one concerns the Jacobian computation. In C++, you need to pre-allocate its memory space, set it to zero, and pass it as an input
This allows to always use the same memory space, avoiding re-allocation and achieving greater efficiency.
The second difference consists in the way the velocity is computed
This code is longer than the Python version, but equivalent to it. Notice we explicitly employ the ldlt decomposition.