Qontrol
Velocity control using Generalized resolution

Introduction

This resolution strategy is based on the Generalized Hierarchical Control method published in this paper. Most existing techniques to handle strict task priorities in hierarchical control are based on null-space projectors or a sequence of quadratic programs; whereas non strict task priorities are usually handled by optimization based on a weighting strategy. This approach handles both strict and non-strict priorities of an arbitrary number of tasks, and achieves multiple priority rearrangements simultaneously. It relies on a generalized projector, which makes it possible to completely project a task into the null-space of a set of tasks, while partially projecting it into the null-space of some other tasks. Priority transitions are achieved by smooth variations of the generalized projector.

Formulation

The following example solves a qp problem expressed at the torque level such that:

\begin{equation} \begin{array}{l} X^T = [\dot{q}_1^T, \ldots, \dot{q}_{n_t}^T] \\ X^{opt} = \underset{X}{\mathrm{argmin}} \sum_{i=1}^{n_t} \left\| J_i S_{q_i} X - v_i^* \right\|^2 + \left\| X \right\|^2 \\ \textrm{s.t.} \\ \quad \frac{q_{min} - q_k}{\Delta T} \leq PX \leq \frac{q_{max} - q_k}{\Delta T}\\ \quad \dot{q}_{min} \leq PX \leq \dot{q}_{max} \\ P = [P_1, \ldots, P_{n_t}], \quad \dot{q} = PX = \sum_i P_i \dot{q}_i \\ \end{array} \end{equation}

Where P is the concatenation of the generalized projectors of each task.

For the i-th task we compute its projector \(P_i\) using its corresponding \(\alpha_i\) input: \( P_i(\alpha_i) = I_n − B_i(J_{s_i})^T \alpha_{i,r}^s(\alpha_i ,origin) B_i (J_{s_i} ) \)

Where \( J_{s_i}\) is a matrix made of the rows of J sorted in descending order with respect to the values of the diagonal elements in \(\alpha_i\) .

The values in \(\alpha_i\) are sorted accordingly, leading to \(\alpha_{i}^s\).

\(B_i(J_{s_i})\) is a \(r\) x \(n\) matrix , (where \(r = rank(J_{s_i} )\)), such that the rows of \(B_i(J_{s_i})\) form an orthonormal basis of the joint space.

Finally, \(\alpha_{i,r}^s\) is a diagonal matrix of degree r. The vector \(origin\) is a vector of the row indexes of \( J_{s_i}\) selected during the construction of the orthonormal basis \( B_i\)

The robot main tasks consists in keeping the end effector at a defined pose in Cartesian space. A second task is added to control the position on the y axis of the elbow of the robot. The mujoco library is used to simulate the robot behaviour.

Simulation

To run this example run the following command from the build/examples directory:

./velocityQontrol_GHC robot_name

where robot_name can be only panda

Full code

1 // Copyright 2021 DeepMind Technologies Limited
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "mujoco/mujoco_sim.h"
16 #include "Qontrol/Qontrol.hpp"
17 #include "trajectory_generation/trajectory_generation.h"
18 
19 
20 using namespace Qontrol;
21 
22 class MujocoQontrol : public MujocoSim
23 {
24 public:
25 //------------------------------------------- simulation -------------------------------------------
26 std::shared_ptr<Qontrol::Model::RobotModel<Qontrol::ModelImpl::PINOCCHIO>> model;
27 std::shared_ptr<Qontrol::JointVelocityProblem> velocity_problem;
28 std::shared_ptr<Qontrol::Task::CartesianVelocity<Qontrol::ControlOutput::JointVelocity>> main_task;
29 std::shared_ptr<Qontrol::Task::CartesianVelocity<Qontrol::ControlOutput::JointVelocity>> elbow_task;
30 std::shared_ptr<Qontrol::Task::GenericTask> regularization_task;
31 
32 
33 Qontrol::RobotState robot_state;
34 
35 TrajectoryGeneration* traj;
36 std::string resource_path;
37 bool initialized = false;
38 double t = 0;
39 
40 void initController( ) override
41 {
42  model =
44 
45  const int ndof = model->getNrOfDegreesOfFreedom();
46 
47  velocity_problem = std::make_shared<Qontrol::JointVelocityProblem>(model,ResolutionStrategy::Generalized);
48  main_task = velocity_problem->task_set->add<Task::CartesianVelocity>("MainTask");
49  elbow_task = velocity_problem->task_set->add<Task::CartesianVelocity>("CommunicationTask");
50  Eigen::MatrixXd selection_matrix = Eigen::MatrixXd::Zero(6,6);
51  selection_matrix(1,1) = 1.0; //y axis control only
52  elbow_task->setControledFrameName("panda_link4");
53  elbow_task->setReferenceFrame(ReferenceFrame::LOCAL_WORLD_ALIGNED);
54  elbow_task->setSelectionMatrix(selection_matrix);
55  regularization_task = velocity_problem->task_set->add("RegularisationTask",14,14,1e-5);
56 
57  auto joint_configuration_constraint = velocity_problem->constraint_set->add<Constraint::JointConfiguration>("JointConfigurationConstraint");
58  auto joint_velocity_constraint = velocity_problem->constraint_set->add<Constraint::JointVelocity>("JointVelocityConstraint");
59 
60  velocity_problem->init();
61 
62  mju_copy(d->qpos, m->key_qpos, m->nu);
63  robot_state.joint_position.resize(ndof);
64  robot_state.joint_velocity.resize(ndof);
65 
66  traj = new TrajectoryGeneration(resource_path + "trajectory.csv",
67  m->opt.timestep);
68  initialized = true;
69 }
70 
71 void updateController() override
72 {
73  while (!initialized)
74  {
75  // init_pose = model->getFramePose(model->getTipFrameName());
76  std::cout << "Waiting for initialization" << std::endl;
77  std::this_thread::sleep_for(std::chrono::milliseconds(100));
78  }
79 
80  const int ndof = model->getNrOfDegreesOfFreedom();
81 
82  for (int i=0; i<ndof ; ++i)
83  {
84  robot_state.joint_position[i] = d->qpos[i];
85  robot_state.joint_velocity[i] = d->qvel[i];
86  }
87  model->setRobotState(robot_state);
88 
89  traj->update();
90  pinocchio::SE3 traj_pose(traj->pose.matrix());
91 
92  pinocchio::SE3 current_pose(model->getFramePose(model->getTipFrameName()).matrix());
93  const pinocchio::SE3 tipMdes = current_pose.actInv(traj_pose);
94  auto err = pinocchio::log6(tipMdes).toVector();
95  Eigen::Matrix<double,6,1> p_gains;
96  p_gains << 10,10,10,10,10,10;
97  Eigen::Matrix<double,6,1> xd_star = p_gains.cwiseProduct(err);
98 
99  double y_des_elbow =0.15;
100  t+=m->opt.timestep;
101  if(sin(0.5*t)<0){
102  y_des_elbow = -0.15;
103  }
104  double current_y_elbow_pose = model->getFramePose("panda_link4").matrix()(1,3);
105  double error_elbow_y = y_des_elbow-current_y_elbow_pose;
106  Eigen::VectorXd xd_star_elbow = Eigen::VectorXd::Zero(6);
107  xd_star_elbow[1]= 10.0 * error_elbow_y - 10.0*model->getFrameVelocity("panda_link4").matrix()(1,3);
108 
109  Eigen::MatrixXd alpha_1 = Eigen::MatrixXd::Zero(7,7); //here absolute priority to main task
110  Eigen::MatrixXd alpha_2 = Eigen::MatrixXd::Identity(7,7); //activation of the elbow task but should not impact the main task
111  alpha_2(6,6)=0.0;
112  std::vector<Eigen::MatrixXd> alphas;
113  alphas.push_back(alpha_1);
114  alphas.push_back(alpha_2);
115 
116  //update the projectors of GHC
117  velocity_problem->updateProjector(alphas);
118 
119  //TASKS UPDATE
120 
121  main_task->setTargetVelocity(xd_star);
122  elbow_task->setTargetVelocity(xd_star_elbow);
123  regularization_task->setE(0.00001*Eigen::MatrixXd::Identity(14,14)); //here 0.00001 is the weight of regularization task
124  regularization_task->setf(Eigen::VectorXd::Zero(14));
125 
126  velocity_problem->update(m->opt.timestep);
127 
128  if (velocity_problem->solutionFound())
129  {
130  sendJointVelocity(velocity_problem->getJointVelocityCommand());
131  }
132 }
133 
134 };
135 
136 int main(int argc, const char** argv) {
137  MujocoQontrol mujoco_qontrol;
138  Qontrol::Log::Logger::parseArgv(argc, argv);
139 
140  mjvCamera cam;
141  mjv_defaultCamera(&cam);
142 
143  mjvOption opt;
144  mjv_defaultOption(&opt);
145 
146  mjvPerturb pert;
147  mjv_defaultPerturb(&pert);
148 
149  // simulate object encapsulates the UI
150  auto sim = std::make_unique<mj::Simulate>(
151  std::make_unique<mj::GlfwAdapter>(),
152  &cam, &opt, &pert, /* is_passive = */ false
153  );
154 
155  std::string robot = argv[1];
156  std::string mujoco_scene = "./resources/"+robot+"/scene.xml";
157  mujoco_qontrol.resource_path = "./resources/"+robot+"/";
158 
159  // start physics thread
160  std::thread physicsthreadhandle( &MujocoQontrol::PhysicsThread, mujoco_qontrol, sim.get(), mujoco_scene.c_str());
161 
162  // start simulation UI loop (blocking call)
163  sim->RenderLoop();
164  physicsthreadhandle.join();
165 
166  return 0;
167 }

Explanation of the code

Declaration

First we declare all the objects that will be used to define our problem.

0 std::shared_ptr<Qontrol::Model::RobotModel<Qontrol::ModelImpl::PINOCCHIO>> model;

We use pinocchio for our model library.

26 std::shared_ptr<Qontrol::JointVelocityProblem> velocity_problem;

The output of our qp controller is at the joint velocity level.

27 std::shared_ptr<Qontrol::Task::CartesianVelocity<Qontrol::ControlOutput::JointVelocity>> main_task;

We then declare tree tasks that will be updated every milliseconds.

The main task is expressed as a Cartesian Velocity task.

28 std::shared_ptr<Qontrol::Task::CartesianVelocity<Qontrol::ControlOutput::JointVelocity>> elbow_task;

We add the secondary task to control the elbow along y axis.

29 std::shared_ptr<Qontrol::Task::GenericTask> regularization_task;

And we add a regularisation task (also at the torque level).

Initialization

40 void initController( ) override
41 {
42  model =
43  Model::RobotModel<ModelImpl::PINOCCHIO>::loadModelFromFile(resource_path+"robot.urdf");

During initialization we instantiate the model with the robot urdf.

We initialize the problem by giving it the model. By default, the qpmad library is used.

44 
45  const int ndof = model->getNrOfDegreesOfFreedom();
46 
47  velocity_problem = std::make_shared<Qontrol::JointVelocityProblem>(model,ResolutionStrategy::Generalized);
48  main_task = velocity_problem->task_set->add<Task::CartesianVelocity>("MainTask");
49  elbow_task = velocity_problem->task_set->add<Task::CartesianVelocity>("CommunicationTask");
50  Eigen::MatrixXd selection_matrix = Eigen::MatrixXd::Zero(6,6);
51  selection_matrix(1,1) = 1.0; //y axis control only
52  elbow_task->setControledFrameName("panda_link4");
53  elbow_task->setReferenceFrame(ReferenceFrame::LOCAL_WORLD_ALIGNED);
54  elbow_task->setSelectionMatrix(selection_matrix);
55  regularization_task = velocity_problem->task_set->add("RegularisationTask",14,14,1e-5);

We then fill the task set of velocity_problem with the main task, the elbow task and the regularisation task. We define a controlled frame for each task. By default it is the end effector of the robot. Additionnaly, it is possible to define the reference frame considered (local,world, local_world_aligned). The default value is LOCAL. Finally, if the cartesian task dimension is lower than 6, a selection matrix can be defined. Each tasks is given a name and a relative weight \( \omega \). This weight is not considered when we use the Generalized approach.

56 
57  auto joint_configuration_constraint = velocity_problem->constraint_set->add<Constraint::JointConfiguration>("JointConfigurationConstraint");
58  auto joint_velocity_constraint = velocity_problem->constraint_set->add<Constraint::JointVelocity>("JointVelocityConstraint");

We then define the constraint set of velocity_problem. Constraints of the robot are already pre-implemented and can be added as shown in this example.

59 
60  velocity_problem->init();

Here we define that we are not using the default Weighting resolution strategy. It MUST be called after the tasks and constraints definition.

Update

72 void updateController() override
73 {
74  while (!initialized)
75  {
76  // init_pose = model->getFramePose(model->getTipFrameName());
77  std::cout << "Waiting for initialization" << std::endl;
78  std::this_thread::sleep_for(std::chrono::milliseconds(100));
79  }
80 
81  const int ndof = model->getNrOfDegreesOfFreedom();
82 
83  for (int i=0; i<ndof ; ++i)
84  {
85  robot_state.joint_position[i] = d->qpos[i];
86  robot_state.joint_velocity[i] = d->qvel[i];
87  }
88  model->setRobotState(robot_state);
89 
90  traj->update();

The update function is called every milliseconds. At the beginning of each update we fill the new robot state according to the simulated robot.

We also define the Cartesian goal for the end effector.

91  pinocchio::SE3 traj_pose(traj->pose.matrix());
92 
93  pinocchio::SE3 current_pose(model->getFramePose(model->getTipFrameName()).matrix());

We then compute the desired Cartesian acceleration using a simple PD controller. Pinocchio is used to compute the error between the desired Cartesian pose and the current Cartesian pose. This is done by the log6 function. The p_gains and d_gains variables are the gains of the PD controller.

94  const pinocchio::SE3 tipMdes = current_pose.actInv(traj_pose);
95  auto err = pinocchio::log6(tipMdes).toVector();
96  Eigen::Matrix<double,6,1> p_gains;
97  p_gains << 10,10,10,10,10,10;
98  Eigen::Matrix<double,6,1> xd_star = p_gains.cwiseProduct(err);
99 
100  double y_des_elbow =0.15;
101  t+=m->opt.timestep;
102  if(sin(0.5*t)<0){
103  y_des_elbow = -0.15;
104  }
105  double current_y_elbow_pose = model->getFramePose("panda_link4").matrix()(1,3);
106  double error_elbow_y = y_des_elbow-current_y_elbow_pose;
107  Eigen::VectorXd xd_star_elbow = Eigen::VectorXd::Zero(6);
108  xd_star_elbow[1]= 10.0 * error_elbow_y - 10.0*model->getFrameVelocity("panda_link4").matrix()(1,3);

Similarly to the previous desired Cartesian acceleration computation, we compute the desired acceleration of the elbow along the y axis. Here the reference is either 0.15m, either -0.15m depending of the simulation time.

109 
110  Eigen::MatrixXd alpha_1 = Eigen::MatrixXd::Zero(7,7); //here absolute priority to main task
111  Eigen::MatrixXd alpha_2 = Eigen::MatrixXd::Identity(7,7); //activation of the elbow task but should not impact the main task
112  alpha_2(6,6)=0.0;
113  std::vector<Eigen::MatrixXd> alphas;
114  alphas.push_back(alpha_1);
115  alphas.push_back(alpha_2);
116 
117  //update the projectors of GHC
118  velocity_problem->updateProjector(alphas);

Generalized Hierarchical Control is based on the projection P of the tasks on the other tasks' nullspace. In order to compute the overall projection P, we need to create a vector of \(\alpha_i\) matrices defined such that:

\(\alpha_i = diag(\alpha_{i1} I_{m_1}, \ldots, \alpha_{ij} I_{m_j}, \ldots, \alpha_{i_{n_t}} I_{m_{n_t}})\)

where \(\alpha_i\) is a diagonal matrix, the main diagonal blocks of which are square matrices: \(\alpha_{ij} I_{m_j}\) . \(I_{m_j}\) is the \(m_j\) x \(m_j\) identity matrix, and \(\alpha_{ij} \in [0, 1]\). By convention, the coefficient \(\alpha_{ij}\) indicates the priority of task j with respect to task i.

  • \(\alpha_{ij} = 0 \) corresponds to the case where task j has strict lower priority with respect to task i.
  • \(0 < \alpha_{ij} < 1\) corresponds to a soft (non-strict) priority between the two tasks: the greater the value of \(\alpha_{ij}\) , the higher the importance level of task j with respect to task i.
  • \(\alpha_{ij} = 1 \) corresponds to the case where task j has a strict higher priority with respect to task i.

There is a particular case induced by the proposed formulation and corresponding to the influence of task i on itself. Even though not intuitive, this self-influence has to be interpreted in terms of task existence, modulated by \(\alpha_{ii}\) . If \(\alpha_{ii} = 1\) then task i is projected into its own null-space, i.e. it is basically canceled out. Decreasing \(\alpha_{ii}\) continuously to 0 is a simple and elegant way to introduce the task in the set of tasks. Conversely, increasing \(\alpha_{ii}\) continuously from 0 to 1 provides with a proper task deletion procedure.

The updateProjector method update the projector with the alphas. Note that alphas values can be modified over time to smoothly change the hierarchy between the tasks.

119 
120  //TASKS UPDATE
121 
122  main_task->setTargetVelocity(xd_star);
123  elbow_task->setTargetVelocity(xd_star_elbow);
124  regularization_task->setE(0.00001*Eigen::MatrixXd::Identity(14,14)); //here 0.00001 is the weight of regularization task
125  regularization_task->setf(Eigen::VectorXd::Zero(14));

Finally, we set the E and f for each task, including the regularization task. Unlike the other tasks,the regularization task is weighted. In this example, the weight is added in the E matrix.

126 
127  velocity_problem->update(m->opt.timestep);
128 
129  if (velocity_problem->solutionFound())
130  {
131  sendJointVelocity(velocity_problem->getJointVelocityCommand());
132  }
133 }
134 
135 };

Once we updated the necassary tasks and constraints we can update the whole problem. If a solution to the problem exist we can then get it and send it to the simulated robot.

Main function

136 
137 int main(int argc, const char** argv) {
138  MujocoQontrol mujoco_qontrol;
139  Qontrol::Log::Logger::parseArgv(argc, argv);
140 
141  mjvCamera cam;
142  mjv_defaultCamera(&cam);
143 
144  mjvOption opt;
145  mjv_defaultOption(&opt);
146 
147  mjvPerturb pert;
148  mjv_defaultPerturb(&pert);
149 
150  // simulate object encapsulates the UI
151  auto sim = std::make_unique<mj::Simulate>(
152  std::make_unique<mj::GlfwAdapter>(),
153  &cam, &opt, &pert, /* is_passive = */ false
154  );
155 
156  std::string robot = argv[1];
157  std::string mujoco_scene = "./resources/"+robot+"/scene.xml";
158  mujoco_qontrol.resource_path = "./resources/"+robot+"/";
159 
160  // start physics thread
161  std::thread physicsthreadhandle( &MujocoQontrol::PhysicsThread, mujoco_qontrol, sim.get(), mujoco_scene.c_str());
162 
163  // start simulation UI loop (blocking call)
164  sim->RenderLoop();
165  physicsthreadhandle.join();
166 
167  return 0;

The main function function fetches the robot name given in argv and starts the Mujoco simulation.

Qontrol::RobotState
Robot state.
Definition: GenericModel.hpp:35
Qontrol::Constraint::JointVelocity
Implemtentation of a joint velocity constraint.
Definition: JointVelocity.hpp:35
Qontrol::Task::CartesianVelocity
Implementation of a Cartesian velocity task.
Definition: CartesianVelocity.hpp:35
Qontrol::Model::RobotModel
Decalaration of a template specialization for the model library.
Definition: GenericModel.hpp:488
Qontrol::Constraint::JointConfiguration
Implemtentation of a joint configuration constraint.
Definition: JointConfiguration.hpp:35