DSRTController.h
Go to the documentation of this file.
1 /*
2  * This file is part of ArmarX.
3  *
4  * ArmarX is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * ArmarX is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  *
16  * @package DSController::ArmarXObjects::DSRTController
17  * @author Mahdi Khoramshahi ( m80 dot khoramshahi at gmail dot com )
18  * @date 2018
19  * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
20  * GNU General Public License
21  */
22 
23 #ifndef _ARMARX_LIB_DSController_DSRTController_H
24 #define _ARMARX_LIB_DSController_DSRTController_H
25 
26 #include <VirtualRobot/Robot.h>
27 #include <VirtualRobot/Tools/Gravity.h>
28 #include <VirtualRobot/IK/DifferentialIK.h>
30 
35 
36 #include <armarx/control/ds_controller/DSControllerInterface.h>
37 
38 #include "GMRDynamics.h"
39 #include "MathLib.h"
40 
41 
43 {
45  {
46  public:
47  Eigen::Vector3f tcpDesiredLinearVelocity;
48  Eigen::Vector3f tcpDesiredAngularError;
49  };
50 
51 
52 
54  {
55  int K_gmm_;
56  int dim_;
57  std::vector<double> Priors_;
58  std::vector<double> Mu_;
59  std::vector<double> Sigma_;
60  std::vector<double> attractor_;
61  double dt_;
62  };
63 
64 
66  {
67  public:
69 
70  GMMMotionGen(const std::string& fileName)
71  {
72  getGMMParamsFromJsonFile(fileName);
73  }
74 
77  Eigen::Vector3f desiredDefaultTarget;
78  float scaling;
79 
80  float belief;
81  float v_max;
82 
83  void getGMMParamsFromJsonFile(const std::string& fileName)
84  {
85  std::ifstream infile { fileName };
86  std::string objDefs = { std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>() };
87  JSONObjectPtr json = new JSONObject();
88  json->fromString(objDefs);
89 
90 
91  gmmParas.K_gmm_ = json->getInt("K");
92  gmmParas.dim_ = json->getInt("dim");
93  json->getArray<double>("Priors", gmmParas.Priors_);
94  json->getArray<double>("Mu", gmmParas.Mu_);
95  json->getArray<double>("attractor", gmmParas.attractor_);
96  json->getArray<double>("Sigma", gmmParas.Sigma_);
97 
98  scaling = json->getDouble("Scaling");
99  belief = json->getDouble("InitBelief");
100  belief = 0;
101  v_max = json->getDouble("MaxVelocity");
102 
104  gmm->initGMR(0, 2, 3, 5);
105 
106  if (gmmParas.attractor_.size() < 3)
107  {
108  ARMARX_ERROR << "attractor in json file should be 6 dimension vector ... ";
109  }
110 
111  for (int i = 0; i < 3; ++i)
112  {
114  }
115  }
116 
117  void updateDesiredVelocity(const Eigen::Vector3f& currentPositionInMeter, float positionErrorToleranceInMeter)
118  {
119  Eigen::Vector3f PositionError = currentPositionInMeter - desiredDefaultTarget;
120  if (PositionError.norm() < positionErrorToleranceInMeter)
121  {
122  PositionError.setZero();
123  }
124 
125  MathLib::Vector position_error;
126  position_error.Resize(3);
127 
128  for (int i = 0; i < 3; ++i)
129  {
130  position_error(i) = PositionError(i);
131  }
132 
133  MathLib::Vector desired_vel;
134  desired_vel.Resize(3);
135  desired_vel = gmm->getVelocity(position_error);
136 
137  Eigen::Vector3f tcpDesiredLinearVelocity;
138  tcpDesiredLinearVelocity << desired_vel(0), desired_vel(1), desired_vel(2);
139 
140  currentDesiredVelocity = scaling * tcpDesiredLinearVelocity;
141 
142 
143  float lenVec = tcpDesiredLinearVelocity.norm();
144  if (std::isnan(lenVec))
145  {
146  tcpDesiredLinearVelocity.setZero();
147  }
148 
149  if (lenVec > v_max)
150  {
151  tcpDesiredLinearVelocity = (v_max / lenVec) * tcpDesiredLinearVelocity;
152  }
153  }
154 
155 
156 
157  Eigen::Vector3f currentDesiredVelocity;
158  };
159 
161 
162  class DSAdaptor
163  {
164  public:
166  float epsilon;
168 
169  DSAdaptor(std::vector<GMMMotionGenPtr> gmmMotionGenList, float epsilon)
170  {
171  task0_belief = 1;
172  this->gmmMotionGenList = gmmMotionGenList;
173 
174  ARMARX_INFO << "epsilon: " << epsilon;
175  this->epsilon = epsilon;
176 
177  totalDesiredVelocity.setZero();
178  }
179 
180  Eigen::Vector3f totalDesiredVelocity;
181  std::vector<GMMMotionGenPtr> gmmMotionGenList;
182 
183 
184  void updateDesiredVelocity(const Eigen::Vector3f& currentPositionInMeter, float positionErrorToleranceInMeter)
185  {
186  totalDesiredVelocity.setZero();
187  for (size_t i = 0; i < gmmMotionGenList.size(); ++i)
188  {
189  gmmMotionGenList[i]->updateDesiredVelocity(currentPositionInMeter, positionErrorToleranceInMeter);
190  totalDesiredVelocity += gmmMotionGenList[i]->belief * gmmMotionGenList[i]->currentDesiredVelocity;
191  }
192  }
193 
194  void updateBelief(const Eigen::Vector3f& realVelocity)
195  {
196  std::vector<float> beliefUpdate;
197  beliefUpdate.resize(gmmMotionGenList.size());
198 
199  float nullInnerSimilarity = 0;
200  for (size_t i = 0; i < gmmMotionGenList.size(); ++i)
201  {
202 
203  GMMMotionGenPtr currentGMM = gmmMotionGenList[i];
204 
205  float belief = currentGMM->belief;
206  Eigen::Vector3f OtherTasks = totalDesiredVelocity - belief * currentGMM->currentDesiredVelocity;
207  float innerSimilarity = 2 * OtherTasks.dot(currentGMM->currentDesiredVelocity);
208  float outerDisSimilarity = (realVelocity - currentGMM->currentDesiredVelocity).squaredNorm();
209 
210  if (innerSimilarity > nullInnerSimilarity)
211  {
212  nullInnerSimilarity = innerSimilarity;
213  }
214 
215  beliefUpdate[i] = - outerDisSimilarity - innerSimilarity;
216 
217 
218  }
219 
220 
221 
222 
223  float nullOuterSimilarity = realVelocity.squaredNorm();
224  float zeroTaskRawBeliefUpdate = - nullInnerSimilarity - nullOuterSimilarity;
225 
226  if (zeroTaskRawBeliefUpdate < 0.2)
227  {
228  zeroTaskRawBeliefUpdate -= 1000;
229  }
230 
231 
232  beliefUpdate.insert(beliefUpdate.begin(), zeroTaskRawBeliefUpdate);
233 
234  WinnerTakeAll(beliefUpdate);
235  task0_belief += epsilon * beliefUpdate[0];
236  if (task0_belief > 1)
237  {
238  task0_belief = 1;
239  }
240  else if (task0_belief < 0)
241  {
242  task0_belief = 0;
243  }
244 
245  float beliefSum = task0_belief;
246 
247  for (size_t i = 0; i < gmmMotionGenList.size(); ++i)
248  {
249  gmmMotionGenList[i]->belief += epsilon * beliefUpdate[i + 1];
250 
251 
252  if (gmmMotionGenList[i]->belief > 1)
253  {
254  gmmMotionGenList[i]->belief = 1;
255  }
256  else if (gmmMotionGenList[i]->belief < 0)
257  {
258  gmmMotionGenList[i]->belief = 0;
259  }
260 
261  beliefSum += gmmMotionGenList[i]->belief;
262 
263  }
264 
265  for (size_t i = 0; i < gmmMotionGenList.size(); ++i)
266  {
267  gmmMotionGenList[i]->belief /= beliefSum;
268  }
269 
270  task0_belief /= beliefSum;
271  }
272 
273  private:
274 
275  void WinnerTakeAll(std::vector<float>& UpdateBeliefs_)
276  {
277  // std::fill(UpdateBeliefs_.begin(), UpdateBeliefs_.end(), 0);
278 
279  size_t winner_index = 0;
280 
281  for (size_t i = 1; i < UpdateBeliefs_.size(); i++)
282  {
283  if (UpdateBeliefs_[i] > UpdateBeliefs_[winner_index])
284  {
285  winner_index = i;
286  }
287  }
288 
289  float winner_belief = task0_belief;
290 
291  if (winner_index != 0)
292  {
293  winner_belief = gmmMotionGenList[winner_index - 1]->belief;
294  }
295 
296  if (winner_belief == 1)
297  {
298  return;
299  }
300 
301  int runnerUp_index = 0;
302 
303  if (winner_index == 0)
304  {
305  runnerUp_index = 1;
306  }
307 
308  for (size_t i = 0; i < UpdateBeliefs_.size(); i++)
309  {
310  if (i == winner_index)
311  {
312  continue;
313  }
314 
315  if (UpdateBeliefs_[i] > UpdateBeliefs_[runnerUp_index])
316  {
317  runnerUp_index = i;
318  }
319  }
320 
321  float offset = 0.5 * (UpdateBeliefs_[winner_index] + UpdateBeliefs_[runnerUp_index]);
322 
323  for (size_t i = 0; i < UpdateBeliefs_.size(); i++)
324  {
325  UpdateBeliefs_[i] -= offset;
326  }
327 
328  float UpdateSum = 0;
329 
330  for (size_t i = 0; i < UpdateBeliefs_.size(); i++)
331  {
332  float belief = task0_belief;
333  if (i != 0)
334  {
335  belief = gmmMotionGenList[i - 1]->belief;
336  }
337 
338  if (belief != 0 || UpdateBeliefs_[i] > 0)
339  {
340  UpdateSum += UpdateBeliefs_[i];
341  }
342  }
343 
344  UpdateBeliefs_[winner_index] -= UpdateSum;
345  }
346  };
347 
349 
350 
351 
352  /**
353  * @defgroup Library-DSRTController DSRTController
354  * @ingroup armarx_control
355  * A description of the library DSRTController.
356  *
357  * @class DSRTController
358  * @ingroup Library-DSRTController
359  * @brief Brief description of class DSRTController.
360  *
361  * Detailed description of class DSRTController.
362  */
363  class DSRTController : public NJointControllerWithTripleBuffer<DSRTControllerControlData>, public DSControllerInterface
364  {
365 
366  // ManagedIceObject interface
367  protected:
368  void onInitNJointController();
370 
371 
372  void controllerRun();
373 
374 
375 
376  // NJointControllerInterface interface
377  public:
378  using ConfigPtrT = DSControllerConfigPtr;
379 
380  DSRTController(const RobotUnitPtr& robotUnit, const NJointControllerConfigPtr& config, const VirtualRobot::RobotPtr&);
381 
382 
383  std::string getClassName(const Ice::Current&) const
384  {
385  return "DSRTController";
386  }
387 
388  // NJointController interface
389  void rtRun(const IceUtil::Time& sensorValuesTimestamp, const IceUtil::Time& timeSinceLastIteration);
390 
391  private:
392  // PeriodicTask<DSRTController>::pointer_type controllerTask;
393 
394  struct DSRTControllerSensorData
395  {
396  Eigen::Matrix4f tcpPose;
397  double currentTime;
398 
399  Eigen::Vector3f linearVelocity;
400 
401  };
402  TripleBuffer<DSRTControllerSensorData> controllerSensorData;
403 
404  struct DSRTDebugInfo
405  {
406  StringFloatDictionary desired_torques;
407  float desiredForce_x;
408  float desiredForce_y;
409  float desiredForce_z;
410  float tcpDesiredTorque_x;
411  float tcpDesiredTorque_y;
412  float tcpDesiredTorque_z;
413 
414  float tcpDesiredAngularError_x;
415  float tcpDesiredAngularError_y;
416  float tcpDesiredAngularError_z;
417 
418  float currentTCPAngularVelocity_x;
419  float currentTCPAngularVelocity_y;
420  float currentTCPAngularVelocity_z;
421 
422  float currentTCPLinearVelocity_x;
423  float currentTCPLinearVelocity_y;
424  float currentTCPLinearVelocity_z;
425 
426  float belief0;
427  float belief1;
428  float belief2;
429  };
430  TripleBuffer<DSRTDebugInfo> debugDataInfo;
431 
432  std::vector<const SensorValue1DoFActuatorTorque*> torqueSensors;
433  std::vector<const SensorValue1DoFGravityTorque*> gravityTorqueSensors;
434  std::vector<const SensorValue1DoFActuatorVelocity*> velocitySensors;
435  std::vector<const SensorValue1DoFActuatorPosition*> positionSensors;
436 
437  std::vector<ControlTarget1DoFActuatorTorque*> targets;
438 
439 
440  VirtualRobot::RobotNodePtr tcp;
441 
442  VirtualRobot::DifferentialIKPtr ik;
443  Eigen::MatrixXf jacobip;
444  Eigen::MatrixXf jacobio;
445 
446  Eigen::Vector3f desiredPosition;
447 
448  Eigen::Quaternionf desiredQuaternion;
449  Eigen::Vector3f oldPosition;
450 
451  Eigen::Matrix3f oldOrientation;
452 
453  Eigen::Vector3f currentTCPLinearVelocity_filtered;
454  Eigen::Vector3f currentTCPAngularVelocity_filtered;
455 
456  float filterTimeConstant;
457 
458  std::vector<std::string> jointNames;
459 
460  float posiKp;
461  float v_max;
462  float posiDamping;
463  float torqueLimit;
464 
465  float oriKp;
466  float oriDamping;
467 
468  float nullspaceKp;
469  float nullspaceDamping;
470 
471  Eigen::VectorXf qnullspace;
472 
473  std::vector<GMMMotionGenPtr> gmmMotionGenList;
474 
475  DSAdaptorPtr dsAdaptorPtr;
476 
477  float positionErrorTolerance;
478 
479 
480  // NJointController interface
481  protected:
483 
484  // NJointController interface
485  protected:
488  };
489 
490 }
491 
492 #endif
armarx::control::ds_controller::GMRParameters::Mu_
std::vector< double > Mu_
Definition: DSRTController.h:58
armarx::DSControllerInterface
Definition: DSControllerInterface.ice:62
armarx::control::ds_controller::DSAdaptor::DSAdaptor
DSAdaptor(std::vector< GMMMotionGenPtr > gmmMotionGenList, float epsilon)
Definition: DSRTController.h:169
armarx::control::ds_controller::GMRParameters::dt_
double dt_
Definition: DSRTController.h:61
armarx::control::ds_controller::DSRTController::onDisconnectNJointController
void onDisconnectNJointController()
Definition: DSRTController.cpp:55
armarx::control::ds_controller::GMMMotionGen::belief
float belief
Definition: DSRTController.h:80
armarx::control::ds_controller::GMMMotionGen
Definition: DSRTController.h:65
boost::shared_ptr< GMRDynamics >
armarx::control::ds_controller::DSAdaptor::task0_belief
float task0_belief
Definition: DSRTController.h:165
Vector
Eigen::Matrix< T, 3, 1 > Vector
Definition: UnscentedKalmanFilterTest.cpp:36
JSONObject.h
armarx::control::ds_controller::DSRTController::getClassName
std::string getClassName(const Ice::Current &) const
Definition: DSRTController.h:383
armarx::NJointControllerWithTripleBuffer
Definition: NJointControllerWithTripleBuffer.h:10
armarx::control::ds_controller::DSRTController::rtPreActivateController
void rtPreActivateController()
This function is called before the controller is activated.
Definition: DSRTController.cpp:488
RobotUnit.h
armarx::control::ds_controller::GMMMotionGen::gmmParas
GMRParameters gmmParas
Definition: DSRTController.h:76
armarx::JSONObject
The JSONObject class is used to represent and (de)serialize JSON objects.
Definition: JSONObject.h:43
armarx::control::ds_controller::DSRTControllerControlData
Definition: DSRTController.h:44
armarx::control::ds_controller::DSRTController::controllerRun
void controllerRun()
Definition: DSRTController.cpp:203
armarx::control::ds_controller::DSRTController
Brief description of class DSRTController.
Definition: DSRTController.h:363
armarx::control::ds_controller::DSRTController::rtPostDeactivateController
void rtPostDeactivateController()
This function is called after the controller is deactivated.
Definition: DSRTController.cpp:493
armarx::control::ds_controller
Definition: DSJointCarryController.cpp:28
armarx::NJointControllerBase::ConfigPtrT
NJointControllerConfigPtr ConfigPtrT
Definition: NJointControllerBase.h:586
armarx::control::ds_controller::GMMMotionGen::currentDesiredVelocity
Eigen::Vector3f currentDesiredVelocity
Definition: DSRTController.h:157
armarx::control::ds_controller::GMMMotionGen::updateDesiredVelocity
void updateDesiredVelocity(const Eigen::Vector3f &currentPositionInMeter, float positionErrorToleranceInMeter)
Definition: DSRTController.h:117
armarx::control::ds_controller::GMMMotionGen::GMMMotionGen
GMMMotionGen(const std::string &fileName)
Definition: DSRTController.h:70
armarx::control::ds_controller::DSAdaptorPtr
boost::shared_ptr< DSAdaptor > DSAdaptorPtr
Definition: DSRTController.h:348
armarx::control::ds_controller::GMRParameters::attractor_
std::vector< double > attractor_
Definition: DSRTController.h:60
armarx::control::ds_controller::GMRParameters::Sigma_
std::vector< double > Sigma_
Definition: DSRTController.h:59
armarx::control::ds_controller::GMRParameters::dim_
int dim_
Definition: DSRTController.h:56
armarx::control::ds_controller::GMMMotionGen::desiredDefaultTarget
Eigen::Vector3f desiredDefaultTarget
Definition: DSRTController.h:77
IceInternal::Handle< JSONObject >
armarx::control::ds_controller::DSAdaptor::updateDesiredVelocity
void updateDesiredVelocity(const Eigen::Vector3f &currentPositionInMeter, float positionErrorToleranceInMeter)
Definition: DSRTController.h:184
GMRDynamics
Definition: GMRDynamics.h:20
armarx::detail::ControlThreadOutputBufferEntry
Definition: ControlThreadOutputBuffer.h:177
armarx::control::ds_controller::GMMMotionGen::getGMMParamsFromJsonFile
void getGMMParamsFromJsonFile(const std::string &fileName)
Definition: DSRTController.h:83
armarx::control::ds_controller::DSRTController::rtRun
void rtRun(const IceUtil::Time &sensorValuesTimestamp, const IceUtil::Time &timeSinceLastIteration)
TODO make protected and use attorneys.
Definition: DSRTController.cpp:256
armarx::control::ds_controller::DSRTControllerControlData::tcpDesiredAngularError
Eigen::Vector3f tcpDesiredAngularError
Definition: DSRTController.h:48
armarx::control::ds_controller::GMMMotionGen::gmm
GMMPtr gmm
Definition: DSRTController.h:75
ControlTarget1DoFActuator.h
Eigen::Quaternionf
Quaternion< float, 0 > Quaternionf
Definition: EigenForwardDeclarations.h:61
armarx::control::ds_controller::DSRTController::DSRTController
DSRTController(const RobotUnitPtr &robotUnit, const NJointControllerConfigPtr &config, const VirtualRobot::RobotPtr &)
Definition: DSRTController.cpp:60
armarx::control::ds_controller::GMMMotionGen::GMMMotionGen
GMMMotionGen()
Definition: DSRTController.h:68
ARMARX_ERROR
#define ARMARX_ERROR
Definition: Logging.h:189
armarx::control::ds_controller::DSAdaptor::updateBelief
void updateBelief(const Eigen::Vector3f &realVelocity)
Definition: DSRTController.h:194
armarx::control::ds_controller::GMMMotionGenPtr
boost::shared_ptr< GMMMotionGen > GMMMotionGenPtr
Definition: DSRTController.h:160
armarx::armem::Time
armarx::core::time::DateTime Time
Definition: forward_declarations.h:13
armarx::control::ds_controller::DSRTControllerControlData::tcpDesiredLinearVelocity
Eigen::Vector3f tcpDesiredLinearVelocity
Definition: DSRTController.h:47
NJointController.h
GfxTL::Matrix3f
MatrixXX< 3, 3, float > Matrix3f
Definition: MatrixXX.h:600
GfxTL::Matrix4f
MatrixXX< 4, 4, float > Matrix4f
Definition: MatrixXX.h:601
armarx::control::ds_controller::DSAdaptor::DSAdaptor
DSAdaptor()
Definition: DSRTController.h:167
armarx::control::ds_controller::DSRTController::onInitNJointController
void onInitNJointController()
Definition: DSRTController.cpp:34
armarx::control::ds_controller::GMMMotionGen::v_max
float v_max
Definition: DSRTController.h:81
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:174
armarx::control::ds_controller::DSRTController::onPublish
void onPublish(const SensorAndControl &, const DebugDrawerInterfacePrx &, const DebugObserverInterfacePrx &)
Definition: DSRTController.cpp:414
armarx::control::ds_controller::DSAdaptor::epsilon
float epsilon
Definition: DSRTController.h:166
IceInternal::ProxyHandle<::IceProxy::armarx::DebugDrawerInterface >
armarx::control::ds_controller::GMRParameters::K_gmm_
int K_gmm_
Definition: DSRTController.h:55
GMRDynamics.h
armarx::control::ds_controller::GMRParameters::Priors_
std::vector< double > Priors_
Definition: DSRTController.h:57
armarx::control::ds_controller::DSAdaptor::gmmMotionGenList
std::vector< GMMMotionGenPtr > gmmMotionGenList
Definition: DSRTController.h:181
armarx::control::ds_controller::GMMMotionGen::scaling
float scaling
Definition: DSRTController.h:78
armarx::control::ds_controller::DSAdaptor
Definition: DSRTController.h:162
armarx::control::ds_controller::DSAdaptor::totalDesiredVelocity
Eigen::Vector3f totalDesiredVelocity
Definition: DSRTController.h:180
armarx::control::ds_controller::GMRParameters
Definition: DSRTController.h:53
SensorValue1DoFActuator.h
VirtualRobot::RobotPtr
std::shared_ptr< class Robot > RobotPtr
Definition: Bus.h:18
armarx::TripleBuffer< DSRTControllerSensorData >