GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: src/pg.cpp Lines: 324 963 33.6 %
Date: 2023-06-05 08:59:09 Branches: 619 2278 27.2 %

Line Branch Exec Source
1
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
 * Copyright Projet JRL-Japan, 2008
3
 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4
 *
5
 * File:      PatternGenerator.cpp
6
 * Project:   SOT
7
 * Author:    Olivier Stasse
8
 *
9
 * Version control
10
 * ===============
11
 *
12
 *  $Id$
13
 *
14
 * Description
15
 * ============
16
 *
17
 *
18
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
19
20
/* Local Variables:  */
21
/* mode: c++         */
22
/* comment-column: 0            */
23
/* visual-fill-column-width: 80 */
24
/* indent-tabs-mode: nil */
25
/* End:                         */
26
27
// #define VP_DEBUG
28
// #define VP_DEBUG_MODE 45
29
#include <pinocchio/fwd.hpp>
30
// pin first
31
#include <boost/property_tree/ptree.hpp>
32
#include <boost/property_tree/xml_parser.hpp>
33
#include <sot/core/debug.hh>
34
#include <sot/core/robot-utils.hh>
35
#include <sstream>
36
#include <stdexcept>
37
38
#ifdef VP_DEBUG
39
class sotPG__INIT {
40
 public:
41
  sotPG__INIT(void) { dynamicgraph::sot::DebugTrace::openFile(); }
42
};
43
sotPG__INIT sotPG_initiator;
44
#endif  // #ifdef VP_DEBUG
45
46
#include <dynamic-graph/all-commands.h>
47
#include <dynamic-graph/factory.h>
48
#include <sot/pattern-generator/pg.h>
49
50
#include <boost/property_tree/ptree.hpp>
51
#include <boost/property_tree/xml_parser.hpp>
52
#include <sot/core/matrix-geometry.hh>
53
54
#include "pinocchio/algorithm/joint-configuration.hpp"
55
#include "pinocchio/algorithm/model.hpp"
56
#include "pinocchio/parsers/srdf.hpp"
57
#include "pinocchio/parsers/urdf.hpp"
58
59
using namespace std;
60
namespace dynamicgraph {
61
namespace sot {
62
63
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(PatternGenerator, "PatternGenerator");
64
65
1
PatternGenerator::PatternGenerator(const std::string &name)
66
    : Entity(name),
67
      m_PGI(0),
68
      m_PreviewControlParametersFile(),
69
      m_urdfFile(""),
70
      m_srdfFile(""),
71
      m_xmlRankFile(""),
72
      m_soleWidth(0),
73
      m_init(false),
74
      m_InitPositionByRealState(true),
75
      firstSINTERN(
76
          boost::bind(&PatternGenerator::InitOneStepOfControl, this, _1, _2),
77
2
          sotNOSIGNAL, "PatternGenerator(" + name + ")::intern(dummy)::init")
78
79
      ,
80
      OneStepOfControlS(
81
          boost::bind(&PatternGenerator::OneStepOfControl, this, _1, _2),
82
1
          firstSINTERN << jointPositionSIN,
83
2
          "PatternGenerator(" + name + ")::onestepofcontrol")
84
85
      ,
86
      m_dataInProcess(0),
87
      m_rightFootContact(true)  // It is assumed that the robot is standing.
88
      ,
89
      m_leftFootContact(true),
90
      jointPositionSIN(
91
2
          NULL, "PatternGenerator(" + name + ")::input(vector)::position")
92
93
      ,
94
      motorControlJointPositionSIN(
95
2
          NULL, "PatternGenerator(" + name + ")::input(vector)::motorcontrol")
96
97
      ,
98
      ZMPPreviousControllerSIN(NULL,
99
2
                               "PatternGenerator(" + name +
100
                                   ")::input(vector)::zmppreviouscontroller")
101
102
      ,
103
      ZMPRefSOUT(boost::bind(&PatternGenerator::getZMPRef, this, _1, _2),
104
                 OneStepOfControlS,
105
2
                 "PatternGenerator(" + name + ")::output(vector)::zmpref")
106
107
      ,
108
      CoMRefSOUT(boost::bind(&PatternGenerator::getCoMRef, this, _1, _2),
109
                 OneStepOfControlS,
110
2
                 "PatternGenerator(" + name + ")::output(vector)::comref")
111
112
      ,
113
      dCoMRefSOUT(boost::bind(&PatternGenerator::getdCoMRef, this, _1, _2),
114
                  OneStepOfControlS,
115
2
                  "PatternGenerator(" + name + ")::output(vector)::dcomref")
116
117
      ,
118
      ddCoMRefSOUT(boost::bind(&PatternGenerator::getddCoMRef, this, _1, _2),
119
                   OneStepOfControlS,
120
2
                   "PatternGenerator(" + name + ")::output(vector)::ddcomref")
121
122
      ,
123
2
      comSIN(NULL, "PatternGenerator(" + name + ")::input(vector)::com")
124
125
      ,
126
      comStateSIN(NULL,
127
2
                  "PatternGenerator(" + name + ")::input(vector)::comStateSIN")
128
129
      ,
130
2
      zmpSIN(NULL, "PatternGenerator(" + name + ")::input(vector)::zmpSIN")
131
132
      ,
133
2
      forceSIN(NULL, "PatternGenerator(" + name + ")::input(vector)::forceSIN")
134
135
      ,
136
      forceSOUT(boost::bind(&PatternGenerator::getExternalForces, this, _1, _2),
137
                OneStepOfControlS,
138
2
                "PatternGenerator(" + name + ")::output(vector)::forceSOUT")
139
140
      ,
141
      velocitydesSIN(
142
2
          NULL, "PatternGenerator(" + name + ")::input(vector)::velocitydes")
143
144
      ,
145
2
      triggerSIN(NULL, "PatternGenerator(" + name + ")::input(bool)::trigger")
146
147
      ,
148
      LeftFootCurrentPosSIN(
149
2
          NULL, "PatternGenerator(" + name +
150
                    ")::input(homogeneousmatrix)::leftfootcurrentpos")
151
152
      ,
153
      RightFootCurrentPosSIN(
154
2
          NULL, "PatternGenerator(" + name +
155
                    ")::input(homogeneousmatrix)::rightfootcurrentpos")
156
157
      ,
158
      LeftFootRefSOUT(
159
          boost::bind(&PatternGenerator::getLeftFootRef, this, _1, _2),
160
          OneStepOfControlS,
161
2
          "PatternGenerator(" + name +
162
              ")::output(homogeneousmatrix)::leftfootref")
163
164
      ,
165
      RightFootRefSOUT(
166
          boost::bind(&PatternGenerator::getRightFootRef, this, _1, _2),
167
          OneStepOfControlS,
168
2
          "PatternGenerator(" + name +
169
              ")::output(homogeneousmatrix)::rightfootref")
170
171
      ,
172
      dotLeftFootRefSOUT(
173
          boost::bind(&PatternGenerator::getdotLeftFootRef, this, _1, _2),
174
          OneStepOfControlS,
175
2
          "PatternGenerator(" + name +
176
              ")::output(homogeneousmatrix)::dotleftfootref")
177
178
      ,
179
      dotRightFootRefSOUT(
180
          boost::bind(&PatternGenerator::getdotRightFootRef, this, _1, _2),
181
          OneStepOfControlS,
182
2
          "PatternGenerator(" + name +
183
              ")::output(homogeneousmatrix)::dotrightfootref")
184
185
      ,
186
      FlyingFootRefSOUT(
187
          boost::bind(&PatternGenerator::getFlyingFootRef, this, _1, _2),
188
          OneStepOfControlS,
189
2
          "PatternGenerator(" + name +
190
              ")::output(homogeneousmatrix)::flyingfootref")
191
192
      ,
193
      SupportFootSOUT(
194
          boost::bind(&PatternGenerator::getSupportFoot, this, _1, _2),
195
          OneStepOfControlS,
196
2
          "PatternGenerator(" + name + ")::output(uint)::SupportFoot"),
197
      jointWalkingErrorPositionSOUT(
198
          boost::bind(&PatternGenerator::getjointWalkingErrorPosition, this, _1,
199
                      _2),
200
          OneStepOfControlS,
201
2
          "PatternGenerator(" + name +
202
              ")::output(vector)::walkingerrorposition")
203
204
      ,
205
      comattitudeSOUT(
206
          boost::bind(&PatternGenerator::getComAttitude, this, _1, _2),
207
          OneStepOfControlS,
208
2
          "sotPatternGenerator(" + name + ")::output(vectorRPY)::comattitude")
209
210
      ,
211
      dcomattitudeSOUT(
212
          boost::bind(&PatternGenerator::getdComAttitude, this, _1, _2),
213
          OneStepOfControlS,
214
2
          "sotPatternGenerator(" + name + ")::output(vectorRPY)::dcomattitude")
215
216
      ,
217
      ddcomattitudeSOUT(
218
          boost::bind(&PatternGenerator::getddComAttitude, this, _1, _2),
219
          OneStepOfControlS,
220
2
          "sotPatternGenerator(" + name + ")::output(vectorRPY)::ddcomattitude")
221
222
      ,
223
      waistattitudeSOUT(
224
          boost::bind(&PatternGenerator::getWaistAttitude, this, _1, _2),
225
          OneStepOfControlS,
226
2
          "PatternGenerator(" + name + ")::output(vectorRPY)::waistattitude")
227
228
      ,
229
      waistattitudeabsoluteSOUT(
230
          boost::bind(&PatternGenerator::getWaistAttitudeAbsolute, this, _1,
231
                      _2),
232
          OneStepOfControlS,
233
2
          "PatternGenerator(" + name +
234
              ")::output(vectorRPY)::waistattitudeabsolute")
235
236
      ,
237
      waistattitudematrixabsoluteSOUT(
238
          boost::bind(&PatternGenerator::getWaistAttitudeMatrixAbsolute, this,
239
                      _1, _2),
240
          OneStepOfControlS,
241
2
          "PatternGenerator(" + name +
242
              ")::output(homogeneousmatrix)::waistattitudematrixabsolute")
243
244
      ,
245
      waistpositionSOUT(
246
          boost::bind(&PatternGenerator::getWaistPosition, this, _1, _2),
247
          OneStepOfControlS,
248
2
          "PatternGenerator(" + name + ")::output(vector)::waistposition")
249
250
      ,
251
      waistpositionabsoluteSOUT(
252
          boost::bind(&PatternGenerator::getWaistPositionAbsolute, this, _1,
253
                      _2),
254
          OneStepOfControlS,
255
2
          "PatternGenerator(" + name +
256
              ")::output(vector)::waistpositionabsolute")
257
258
      ,
259
      dataInProcessSOUT(
260
          boost::bind(&PatternGenerator::getDataInProcess, this, _1, _2),
261
          OneStepOfControlS,
262
2
          "PatternGenerator(" + name + ")::output(bool)::inprocess")
263
264
      ,
265
      InitZMPRefSOUT(
266
          boost::bind(&PatternGenerator::getInitZMPRef, this, _1, _2),
267
          OneStepOfControlS,
268
2
          "PatternGenerator(" + name + ")::output(vector)::initzmpref")
269
270
      ,
271
      InitCoMRefSOUT(
272
          boost::bind(&PatternGenerator::getInitCoMRef, this, _1, _2),
273
          OneStepOfControlS,
274
2
          "PatternGenerator(" + name + ")::output(matrix)::initcomref")
275
276
      ,
277
      InitWaistPosRefSOUT(
278
          boost::bind(&PatternGenerator::getInitWaistPosRef, this, _1, _2),
279
          OneStepOfControlS,
280
2
          "PatternGenerator(" + name + ")::output(vector)::initwaistposref")
281
282
      ,
283
      InitWaistAttRefSOUT(
284
          boost::bind(&PatternGenerator::getInitWaistAttRef, this, _1, _2),
285
          OneStepOfControlS,
286
2
          "PatternGenerator(" + name + ")::output(vectorRPY)::initwaistattref")
287
288
      ,
289
      InitLeftFootRefSOUT(
290
          boost::bind(&PatternGenerator::getInitLeftFootRef, this, _1, _2),
291
          OneStepOfControlS,
292
2
          "PatternGenerator(" + name +
293
              ")::output(homogeneousmatrix)::initleftfootref")
294
295
      ,
296
      InitRightFootRefSOUT(
297
          boost::bind(&PatternGenerator::getInitRightFootRef, this, _1, _2),
298
          OneStepOfControlS,
299
2
          "PatternGenerator(" + name +
300
              ")::output(homogeneousmatrix)::initrightfootref")
301
302
      ,
303
      leftFootContactSOUT(
304
          boost::bind(&PatternGenerator::getLeftFootContact, this, _1, _2),
305
          OneStepOfControlS,
306
2
          "PatternGenerator(" + name + ")::output(bool)::leftfootcontact")
307
308
      ,
309
      rightFootContactSOUT(
310
          boost::bind(&PatternGenerator::getRightFootContact, this, _1, _2),
311
          OneStepOfControlS,
312
2
          "PatternGenerator(" + name + ")::output(bool)::rightfootcontact"),
313
      contactPhaseSOUT(
314
          boost::bind(&PatternGenerator::getContactPhase, this, _1, _2),
315
          OneStepOfControlS,
316
















































































































85
          "PatternGenerator(" + name + ")::output(int)::contactphase")
317
318
{
319
1
  m_MotionSinceInstanciationToThisSequence.setIdentity();
320
321
1
  m_LocalTime = 0;
322
1
  m_count = 0;
323
1
  m_TimeStep = 0.005;
324
1
  m_ContactPhase = DOUBLE_SUPPORT_PHASE;
325
1
  m_forceFeedBack = false;
326
1
  m_feedBackControl = false;
327
328
1
  m_ZMPRefPos.resize(4);
329
1
  m_ZMPRefPos.fill(0.0);
330
1
  m_ZMPRefPos(3) = 1.0;
331
1
  m_COMRefPos.resize(3);
332
1
  m_COMRefPos.fill(0.0);
333
1
  m_PrevSamplingCOMRefPos.resize(3);
334
1
  m_PrevSamplingCOMRefPos.fill(0.0);
335
1
  m_NextSamplingCOMRefPos.resize(3);
336
1
  m_NextSamplingCOMRefPos.fill(0.0);
337
1
  m_ZMPPrevious.resize(4);
338
1
  m_ZMPPrevious(3) = 1.0;
339
1
  m_dCOMRefPos.resize(3);
340
1
  m_dCOMRefPos.fill(0.0);
341
1
  m_PrevSamplingdCOMRefPos.resize(3);
342
1
  m_PrevSamplingdCOMRefPos.fill(0.0);
343
1
  m_NextSamplingdCOMRefPos.resize(3);
344
1
  m_NextSamplingdCOMRefPos.fill(0.0);
345
1
  m_ddCOMRefPos.resize(3);
346
1
  m_ddCOMRefPos.fill(0.0);
347
1
  m_PrevSamplingddCOMRefPos.resize(3);
348
1
  m_PrevSamplingddCOMRefPos.fill(0.0);
349
1
  m_NextSamplingddCOMRefPos.resize(3);
350
1
  m_NextSamplingddCOMRefPos.fill(0.0);
351
1
  m_InitZMPRefPos.resize(3);
352
1
  m_InitZMPRefPos.fill(0);
353
1
  m_InitCOMRefPos.resize(3);
354
1
  m_InitCOMRefPos.fill(0);
355
1
  m_InitWaistRefPos.resize(3);
356
1
  m_InitWaistRefPos.fill(0);
357
1
  m_InitWaistRefAtt.resize(3);
358
1
  m_InitWaistRefAtt.fill(0);
359
1
  m_dComAttitude.resize(3);
360
1
  m_dComAttitude.fill(0);
361
1
  m_ddComAttitude.resize(3);
362
1
  m_ddComAttitude.fill(0);
363
1
  m_VelocityReference.resize(3);
364
1
  m_VelocityReference.fill(0.0);
365
1
  m_trigger = false;
366
1
  m_WaistAttitude.resize(3);
367
1
  m_WaistAttitude.fill(0);
368
1
  m_ComAttitude.resize(3);
369
1
  m_ComAttitude.fill(0);
370
1
  m_WaistPosition.resize(3);
371
1
  m_WaistPosition.fill(0);
372
1
  m_WaistAttitudeAbsolute.resize(3);
373
1
  m_WaistAttitudeAbsolute.fill(0);
374
1
  m_PrevSamplingWaistAttAbs.resize(3);
375
1
  m_PrevSamplingWaistAttAbs.fill(0);
376
1
  m_NextSamplingWaistAttAbs.resize(3);
377
1
  m_NextSamplingWaistAttAbs.fill(0);
378
1
  m_WaistPositionAbsolute.resize(3);
379
1
  m_WaistPositionAbsolute.fill(0);
380
381
1
  m_WaistAttitudeMatrixAbsolute.setIdentity();
382
1
  m_LeftFootPosition.setIdentity();
383
1
  m_RightFootPosition.setIdentity();
384
385
1
  m_dotLeftFootPosition.setIdentity();
386
1
  m_dotRightFootPosition.setIdentity();
387
388
1
  m_InitLeftFootPosition.setIdentity();
389
1
  m_InitRightFootPosition.setIdentity();
390
1
  m_FlyingFootPosition.setIdentity();
391
392
1
  m_k_Waist_kp1.setIdentity();
393
394
1
  m_SupportFoot = 1;  // Means that we do not know which support foot it is.
395
1
  m_ReferenceFrame = WORLD_FRAME;
396
397
  sotDEBUGIN(5);
398
399
1
  firstSINTERN.setDependencyType(TimeDependency<int>::BOOL_DEPENDENT);
400
  // TODO: here, the 'setConstant' destroy the pointer toward
401
  // function initOneStepOfControl. By calling firstSINTERN(t), whatever t,
402
  // nothing will happen (well, it will just return 0).
403
  // To initialize firstSINTERN (without destroying the pointer), use
404
  // firstSINTERN.setReady() instead.
405
  // TODO: Remove the next line: // firstSINTERN.setConstant(0);
406
1
  firstSINTERN.setReady(true);
407
408
  // OneStepOfControlS.setDependencyType(TimeDependency<int>::ALWAYS_READY);
409
  //  OneStepOfControlS.setConstant(0);
410
411
1
  OneStepOfControlS.addDependency(LeftFootCurrentPosSIN);
412
1
  OneStepOfControlS.addDependency(RightFootCurrentPosSIN);
413
1
  OneStepOfControlS.addDependency(velocitydesSIN);
414
1
  OneStepOfControlS.addDependency(triggerSIN);
415
1
  OneStepOfControlS.addDependency(firstSINTERN);
416
1
  OneStepOfControlS.addDependency(motorControlJointPositionSIN);
417
1
  OneStepOfControlS.addDependency(comSIN);
418
1
  OneStepOfControlS.addDependency(comStateSIN);
419
1
  OneStepOfControlS.addDependency(zmpSIN);
420
1
  OneStepOfControlS.addDependency(forceSIN);
421
422
  // For debug, register OSOC (not relevant for normal use).
423

1
  signalRegistration(OneStepOfControlS);
424
425

1
  signalRegistration(dataInProcessSOUT);
426
427
2
  signalRegistration(jointPositionSIN << motorControlJointPositionSIN
428

1
                                      << ZMPPreviousControllerSIN << ZMPRefSOUT
429

1
                                      << CoMRefSOUT << dCoMRefSOUT
430

1
                                      << ddCoMRefSOUT);
431
432


1
  signalRegistration(comStateSIN << zmpSIN << forceSIN << forceSOUT);
433
434

2
  signalRegistration(comSIN << velocitydesSIN << triggerSIN
435

1
                            << LeftFootCurrentPosSIN << RightFootCurrentPosSIN
436

1
                            << LeftFootRefSOUT << RightFootRefSOUT);
437
438
2
  signalRegistration(SupportFootSOUT << jointWalkingErrorPositionSOUT
439

1
                                     << comattitudeSOUT << dcomattitudeSOUT
440

1
                                     << ddcomattitudeSOUT << waistattitudeSOUT
441

1
                                     << waistattitudematrixabsoluteSOUT);
442
443
2
  signalRegistration(waistpositionSOUT << waistattitudeabsoluteSOUT
444

1
                                       << waistpositionabsoluteSOUT);
445
446

1
  signalRegistration(dotLeftFootRefSOUT << dotRightFootRefSOUT);
447
448

2
  signalRegistration(InitZMPRefSOUT << InitCoMRefSOUT << InitWaistPosRefSOUT
449
1
                                    << InitWaistAttRefSOUT
450
1
                                    << InitLeftFootRefSOUT
451

1
                                    << InitRightFootRefSOUT);
452
453
2
  signalRegistration(leftFootContactSOUT << rightFootContactSOUT
454

1
                                         << contactPhaseSOUT);
455
456
1
  initCommands();
457
458
  // init filter for force signals "to be removed"
459
1
  m_bufferForce.clear();
460
1
  std::vector<double>::size_type n = 10;
461
1
  double sum = 0, tmp = 0;
462
1
  m_filterWindow.resize((std::vector<double>::size_type)(n + 1));
463
12
  for (std::vector<double>::size_type i = 0; i < n + 1; i++) {
464
11
    tmp = sin((M_PI * i) / n);
465
11
    m_filterWindow[i] = tmp * tmp;
466
  }
467
468
12
  for (std::vector<double>::size_type i = 0; i < n + 1; i++)
469
11
    sum += m_filterWindow[i];
470
471
12
  for (std::vector<double>::size_type i = 0; i < n + 1; i++)
472
11
    m_filterWindow[i] /= sum;
473
474
1
  m_initForce.resize(6);
475
1
  m_currentForces.resize(6);
476
  // dataInProcessSOUT.setReference( &m_dataInProcess );
477
  // m_wrml2urdfIndex.clear();
478
479
  sotDEBUGOUT(5);
480
1
}
481
482
bool PatternGenerator::InitState(void) {
483
  sotDEBUGIN(5);
484
  // TODO
485
  // Instead of (0) ie .access(0), it could be rather used:
486
  // .accessCopy()
487
  // Instead of copy value (ml::Vector pos) it could be rather
488
  // used reference (const ml::Vector & post)
489
  Vector res;
490
  Eigen::Matrix<double, 6, 1> lWaistPosition;
491
  if (m_InitPositionByRealState) {
492
    const Vector &pos = jointPositionSIN(m_LocalTime);
493
494
    lWaistPosition.resize(6);
495
    for (unsigned int i = 0; i < 6; ++i) {
496
      lWaistPosition(i) = pos(i);
497
    }
498
    //  m_ZMPPrevious[2] =m_AnkleSoilDistance;
499
    // Changed the reference frame.
500
501
    res.resize(pos.size() - 6);
502
503
    for (unsigned i = 0; i < res.size(); i++) res(i) = pos(i + 6);
504
505
    Vector lZMPPrevious = ZMPPreviousControllerSIN(m_LocalTime);
506
    for (unsigned int i = 0; i < 3; i++) m_ZMPPrevious[i] = lZMPPrevious(i);
507
  } else {
508
    res = motorControlJointPositionSIN(m_LocalTime);
509
    // for(unsigned i=0;i<res.size();i++)
510
    // res(m_wrml2urdfIndex[i]) = res(i);
511
  }
512
513
  Vector com = comSIN(m_LocalTime);
514
515
  m_JointErrorValuesForWalking.resize(res.size());
516
517
  sotDEBUG(5) << "m_LocalTime:" << m_LocalTime << endl;
518
  sotDEBUG(5) << "Joint Values:" << res << endl;
519
520
  try {
521
    Eigen::VectorXd bres;
522
    bres.resize(res.size());
523
    for (int i = 0; i < res.size(); i++) bres(i) = res(i);
524
    m_PGI->SetCurrentJointValues(bres);
525
526
    // Evaluate current position of the COM, ZMP and feet
527
    // according to the state of the robot.
528
    PatternGeneratorJRL::COMState lStartingCOMState;
529
    Eigen::Vector3d lStartingZMPPosition;
530
531
    m_PGI->EvaluateStartingState(lStartingCOMState, lStartingZMPPosition,
532
                                 lWaistPosition, m_InitLeftFootAbsPos,
533
                                 m_InitRightFootAbsPos);
534
535
    // Put inside sotHomogeneous representation
536
    m_InitCOMRefPos(0) = lStartingCOMState.x[0];
537
    m_InitCOMRefPos(1) = lStartingCOMState.y[0];
538
    m_InitCOMRefPos(2) = lStartingCOMState.z[0];
539
540
    m_InitZMPRefPos(0) = lStartingCOMState.x[0];
541
    m_InitZMPRefPos(1) = lStartingCOMState.y[0];
542
    m_InitZMPRefPos(2) = 0;
543
544
    if (m_InitPositionByRealState) {
545
      m_ZMPPrevious[0] = lStartingCOMState.x[0];
546
      m_ZMPPrevious[1] = lStartingCOMState.y[0];
547
      m_ZMPPrevious[2] = 0;
548
    }
549
    sotDEBUG(5) << "InitZMPRefPos :" << m_InitZMPRefPos << endl;
550
551
    m_InitWaistRefPos(0) = m_WaistPositionAbsolute(0) = lWaistPosition(0);
552
    m_InitWaistRefPos(1) = m_WaistPositionAbsolute(1) = lWaistPosition(1);
553
    m_InitWaistRefPos(2) = m_WaistPositionAbsolute(2) = lWaistPosition(2);
554
555
    m_InitWaistRefAtt(0) = m_WaistAttitudeAbsolute(0) = lWaistPosition(3);
556
    m_InitWaistRefAtt(1) = m_WaistAttitudeAbsolute(1) = lWaistPosition(4);
557
    m_InitWaistRefAtt(2) = m_WaistAttitudeAbsolute(2) = lWaistPosition(5);
558
559
    FromAbsoluteFootPosToDotHomogeneous(
560
        m_InitRightFootAbsPos, m_InitRightFootPosition, m_dotRightFootPosition);
561
    FromAbsoluteFootPosToDotHomogeneous(
562
        m_InitLeftFootAbsPos, m_InitLeftFootPosition, m_dotLeftFootPosition);
563
564
    Eigen::Matrix<double, 4, 1> newtmp, oldtmp;
565
    oldtmp(0) = m_InitCOMRefPos(0);
566
    oldtmp(1) = m_InitCOMRefPos(1);
567
    oldtmp(2) = m_InitCOMRefPos(2);
568
    oldtmp(3) = 1.0;
569
    newtmp = m_MotionSinceInstanciationToThisSequence * oldtmp;
570
    m_InitCOMRefPos(0) = newtmp(0);
571
    m_InitCOMRefPos(1) = newtmp(1);
572
    m_InitCOMRefPos(2) = newtmp(2);
573
574
    oldtmp(0) = m_InitZMPRefPos(0);
575
    oldtmp(1) = m_InitZMPRefPos(1);
576
    oldtmp(2) = m_InitZMPRefPos(2);
577
    newtmp = m_MotionSinceInstanciationToThisSequence * oldtmp;
578
    m_InitZMPRefPos(0) = newtmp(0);
579
    m_InitZMPRefPos(1) = newtmp(1);
580
    m_InitZMPRefPos(2) = newtmp(2);
581
582
    if (!m_InitPositionByRealState) {
583
      MatrixHomogeneous invInitLeftFootRef;
584
      invInitLeftFootRef = m_InitLeftFootPosition.inverse();
585
      m_k_Waist_kp1 = m_k_Waist_kp1 * invInitLeftFootRef;
586
      m_MotionSinceInstanciationToThisSequence =
587
          m_MotionSinceInstanciationToThisSequence * m_k_Waist_kp1;
588
    }
589
590
    m_k_Waist_kp1 = m_InitLeftFootPosition;
591
592
    m_InitLeftFootPosition =
593
        m_MotionSinceInstanciationToThisSequence * m_InitLeftFootPosition;
594
    m_InitRightFootPosition =
595
        m_MotionSinceInstanciationToThisSequence * m_InitRightFootPosition;
596
597
    m_LeftFootPosition = m_InitLeftFootPosition;
598
    m_RightFootPosition = m_InitRightFootPosition;
599
600
  } catch (...) {
601
    SOT_THROW ExceptionPatternGenerator(
602
        ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,
603
        "Error while setting the current joint values of the WPG.");
604
    return false;
605
  }
606
607
  m_InitPositionByRealState = false;
608
  sotDEBUGOUT(5);
609
  return true;
610
}
611
612
1
bool PatternGenerator::buildReducedModel(void) {
613
  // Name of the parameter
614
2
  const std::string lparameter_name("/robot_description");
615
616
  // Model of the robot inside a string.
617
2
  std::string lrobot_description;
618
619
  // Reading the parameter.
620
2
  std::string model_name("robot");
621
622
  // Search for the robot util related to robot_name.
623
2
  sot::RobotUtilShrPtr aRobotUtil = sot::getRobotUtil(model_name);
624
625
  // If does not exist then it is created.
626

1
  if (aRobotUtil.get() == sot::RefVoidRobotUtil().get()) {
627
    ostringstream oss;
628
    oss << __FILE__ << " PatternGenerator::buildModel "
629
        << "The robot with name " << model_name << " was not found !";
630
    throw std::invalid_argument(oss.str());
631
    return false;
632
  }
633
634
  try {
635
    // Then build a complete robot model.
636
1
    lrobot_description = aRobotUtil->get_parameter<string>(lparameter_name);
637
  } catch (...) {
638
    SOT_THROW ExceptionPatternGenerator(
639
        ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,
640
        "Error while getting parameter " + lparameter_name + " for the WPG.");
641
    return false;
642
  }
643
644
2
  pinocchio::Model lrobotModel;
645
  pinocchio::urdf::buildModelFromXML(
646

1
      lrobot_description, pinocchio::JointModelFreeFlyer(), lrobotModel);
647
648
  // Then extract a reduced model
649
2
  Eigen::VectorXd q_neutral = neutral(lrobotModel);
650
2
  ExtractJointMimics an_extract_joint_mimics(lrobot_description);
651
652
  const std::vector<std::string> &list_of_joints_to_lock_by_name =
653
1
      an_extract_joint_mimics.get_mimic_joints();
654
655
2
  std::ostringstream oss;
656

1
  oss << "Size of mimic joints: " << lrobotModel.nq << " "
657


1
      << list_of_joints_to_lock_by_name.size() << " " << q_neutral.size();
658

1
  sendMsg(oss.str(), MSG_TYPE_INFO);
659
660
1
  std::vector<pinocchio::JointIndex> list_of_joints_to_lock_by_id;
661

13
  for (auto it : list_of_joints_to_lock_by_name) {
662
12
    const std::string &joint_name = it;
663
664

12
    if (lrobotModel.existJointName(joint_name)) {
665
      // do not consider joint that are not in the model
666
12
      list_of_joints_to_lock_by_id.push_back(
667

12
          lrobotModel.getJointId(joint_name));
668
    } else
669
      std::cout << "joint_name not found: " << joint_name << std::endl;
670
  }
671
672
1
  if (list_of_joints_to_lock_by_id.size() == 0)
673
    m_robotModel = pinocchio::buildReducedModel(
674
        lrobotModel, list_of_joints_to_lock_by_id, q_neutral);
675
  else
676
1
    m_robotModel = lrobotModel;
677
678

1
  m_robotData = new pinocchio::Data(m_robotModel);
679
680
1
  return true;
681
}
682
683
1
bool PatternGenerator::addComplementaryFrames() {
684
  // Reading the parameter.
685
2
  std::string model_name("robot");
686
687
  // Search for the robot util related to robot_name.
688
2
  sot::RobotUtilShrPtr aRobotUtil = sot::getRobotUtil(model_name);
689
690
  std::vector<std::string> lparameter_names = {
691
      "/pg/remap/l_ankle", "/pg/remap/r_ankle", "/pg/remap/l_wrist",
692



10
      "/pg/remap/r_wrist", "/pg/remap/body",    "/pg/remap/torso"};
693
694
  std::vector<std::string> lframe_remapped = {"l_ankle", "r_ankle", "l_wrist",
695



10
                                              "r_wrist", "BODY",    "torso"};
696
697
1
  auto it_frame_remap = lframe_remapped.begin();
698

7
  for (auto it_param_name : lparameter_names) {
699
6
    std::string lbody_name;
700
6
    lbody_name = aRobotUtil->get_parameter<string>(it_param_name);
701

6
    if (m_robotModel.existFrame(lbody_name)) {
702
6
      pinocchio::Model::Index idx = m_robotModel.getFrameId(lbody_name);
703
6
      m_robotModel.frames[idx].name = *it_frame_remap;
704
    } else {
705
      SOT_THROW ExceptionPatternGenerator(
706
          ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,
707
          "Error for parameter " + it_param_name + " body name " + lbody_name +
708
              " doest no exist");
709
      return false;
710
    }
711
6
    it_frame_remap++;
712
  }
713
714
1
  return true;
715
}
716
717
2
void PatternGenerator::readFootParameters(std::string &rootFootPath,
718
                                          pg::PRFoot &aFoot) {
719
  // Reading the parameter.
720
4
  std::string model_name("robot");
721
722
  // Search for the robot util related to robot_name.
723
4
  sot::RobotUtilShrPtr aRobotUtil = sot::getRobotUtil(model_name);
724
725
2
  std::string pathname = rootFootPath + "/size/height";
726
2
  aFoot.soleHeight = aRobotUtil->get_parameter<double>(pathname);
727
2
  pathname = rootFootPath + "/size/width";
728
2
  aFoot.soleWidth = aRobotUtil->get_parameter<double>(pathname);
729
2
  pathname = rootFootPath + "/size/depth";
730
2
  aFoot.soleDepth = aRobotUtil->get_parameter<double>(pathname);
731
732
2
  pathname = rootFootPath + "/anklePosition/x";
733

2
  aFoot.anklePosition(0) = aRobotUtil->get_parameter<double>(pathname);
734
2
  pathname = rootFootPath + "/anklePosition/y";
735

2
  aFoot.anklePosition(1) = aRobotUtil->get_parameter<double>(pathname);
736
2
  pathname = rootFootPath + "/anklePosition/z";
737

2
  aFoot.anklePosition(2) = aRobotUtil->get_parameter<double>(pathname);
738
2
}
739
740
1
bool PatternGenerator::buildPGI(void) {
741
1
  bool ok = true;
742
743
  // Build the reduced model of the robot
744
1
  buildReducedModel();
745
1
  addComplementaryFrames();
746
747
  // Creating the humanoid robot.
748

1
  m_PR = new pg::PinocchioRobot();
749
1
  m_PR->initializeRobotModelAndData(&m_robotModel, m_robotData);
750
751
  // Read xml/srdf stream
752
  using boost::property_tree::ptree;
753
1
  ptree pt;
754
  try {
755
    // Initialize the Right Foot
756
1
    pg::PRFoot aFoot;
757
758
    // First find the joint to which the r_ankle body is related
759

1
    pinocchio::FrameIndex ra = m_robotModel.getFrameId("r_ankle");
760
1
    aFoot.associatedAnkle = m_robotModel.frames.at(ra).parent;
761
762
    // Then populates the PRFoot structure with the property tree.
763
1
    std::string path = "/robot/specificities/feet/right";
764
1
    readFootParameters(path, aFoot);
765
766
    // Initialize internal state of the right foot.
767

1
    m_PR->initializeRightFoot(aFoot);
768
769
    // Initialize the Left Foot
770
    // First find the joint to which the l_ankle body is related
771

1
    pinocchio::FrameIndex la = m_robotModel.getFrameId("l_ankle");
772
1
    aFoot.associatedAnkle = m_robotModel.frames.at(la).parent;
773
774
    // Then populates the PRFoot structure with the property tree.
775
1
    path = "/robot/specificities/feet/left";
776
1
    readFootParameters(path, aFoot);
777
778
    // Initialize internal state of the left foot.
779

1
    m_PR->initializeLeftFoot(aFoot);
780
781
  } catch (...) {
782
    cerr << "problem while setting the feet informations. File corrupted?"
783
         << endl;
784
    ok = false;
785
  }
786
787
1
  if (m_PR != 0) {
788
1
    pg::PRFoot *rightFoot = m_PR->rightFoot();
789
1
    if (rightFoot != 0) {
790
1
      Eigen::Vector3d AnkleInFoot;
791
1
      AnkleInFoot = rightFoot->anklePosition;
792
1
      m_AnkleSoilDistance = fabs(AnkleInFoot(2));
793
    } else
794
      ok = false;
795
  } else
796
    ok = false;
797
798
1
  if (!ok) {
799
    SOT_THROW ExceptionPatternGenerator(
800
        ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,
801
        "Error while creating humanoid robot dynamical model.",
802
        "(PG creation process for object %s).", getName().c_str());
803
  }
804
  try {
805
1
    m_PGI = PatternGeneratorJRL::patternGeneratorInterfaceFactory(m_PR);
806
  }
807
808
  catch (...) {
809
    SOT_THROW ExceptionPatternGenerator(
810
        ExceptionPatternGenerator::PATTERN_GENERATOR_JRL,
811
        "Error while allocating the Pattern Generator.",
812
        "(PG creation process for object %s).", getName().c_str());
813
  }
814
1
  m_init = true;
815
2
  return false;
816
}
817
818
2
PatternGenerator::~PatternGenerator(void) {
819
  sotDEBUGIN(25);
820
2
  if (0 != m_PR) {
821
2
    delete m_PR;
822
2
    m_PR = 0;
823
  }
824
2
  if (0 != m_PGI) {
825
2
    delete m_PGI;
826
2
    m_PGI = 0;
827
  }
828
2
  if (0 != m_robotData) {
829
2
    delete m_robotData;
830
2
    m_robotData = 0;
831
  }
832
  sotDEBUGOUT(25);
833
2
  return;
834
}
835
836
/* --- CONFIG ---------------------------------------------------------- */
837
/* --- CONFIG ---------------------------------------------------------- */
838
/* --- CONFIG ---------------------------------------------------------- */
839
/* --- CONFIG ---------------------------------------------------------- */
840
void PatternGenerator::setParamPreviewFile(const std::string &filename) {
841
  m_PreviewControlParametersFile = filename;
842
}
843
844
void PatternGenerator::setURDFFile(const std::string &filename) {
845
  m_urdfFile = filename;
846
}
847
void PatternGenerator::setSRDFFile(const std::string &filename) {
848
  m_srdfFile = filename;
849
}
850
void PatternGenerator::setXmlRankFile(const std::string &filename) {
851
  m_xmlRankFile = filename;
852
}
853
void PatternGenerator::addJointMapping(const std::string &link,
854
                                       const std::string &repName) {
855
  specialJoints_[link] = repName;
856
}
857
858
/* --- COMPUTE --------------------------------------------------------- */
859
/* --- COMPUTE --------------------------------------------------------- */
860
/* --- COMPUTE --------------------------------------------------------- */
861
862
Vector &PatternGenerator::getZMPRef(Vector &ZMPRefval, int time) {
863
  sotDEBUGIN(5);
864
865
  OneStepOfControlS(time);
866
867
  ZMPRefval.resize(3);
868
  ZMPRefval(0) = m_ZMPRefPos(0);
869
  ZMPRefval(1) = m_ZMPRefPos(1);
870
  ZMPRefval(2) = m_ZMPRefPos(2);
871
  sotDEBUG(5) << "ZMPRefPos transmitted" << m_ZMPRefPos << " " << ZMPRefval
872
              << endl;
873
874
  sotDEBUGOUT(5);
875
  return ZMPRefval;
876
}
877
878
Vector &PatternGenerator::getCoMRef(Vector &CoMRefval, int time) {
879
  sotDEBUGIN(25);
880
881
  OneStepOfControlS(time);
882
  CoMRefval = m_COMRefPos;
883
884
  sotDEBUGOUT(25);
885
  return CoMRefval;
886
}
887
888
Vector &PatternGenerator::getdCoMRef(Vector &CoMRefval, int time) {
889
  sotDEBUGIN(25);
890
891
  OneStepOfControlS(time);
892
  CoMRefval = m_dCOMRefPos;
893
894
  sotDEBUGOUT(25);
895
  return CoMRefval;
896
}
897
898
Vector &PatternGenerator::getddCoMRef(Vector &CoMRefval, int time) {
899
  sotDEBUGIN(25);
900
901
  OneStepOfControlS(time);
902
  CoMRefval = m_ddCOMRefPos;
903
904
  sotDEBUGOUT(25);
905
  return CoMRefval;
906
}
907
908
Vector &PatternGenerator::getExternalForces(Vector &forces, int time) {
909
  sotDEBUGIN(25);
910
911
  OneStepOfControlS(time);
912
  forces = m_currentForces;
913
914
  sotDEBUGOUT(25);
915
  return forces;
916
}
917
918
Vector &PatternGenerator::getInitZMPRef(Vector &InitZMPRefval, int /*time*/) {
919
  sotDEBUGIN(25);
920
921
  sotDEBUG(25) << "InitZMPRefPos transmitted" << m_InitZMPRefPos << " "
922
               << InitZMPRefval << std::endl;
923
  InitZMPRefval.resize(3);
924
  InitZMPRefval(0) = m_InitZMPRefPos(0);
925
  InitZMPRefval(1) = m_InitZMPRefPos(1);
926
  InitZMPRefval(2) = m_InitZMPRefPos(2);
927
928
  sotDEBUGOUT(25);
929
  return InitZMPRefval;
930
}
931
932
Vector &PatternGenerator::getInitCoMRef(Vector &InitCoMRefval, int /*time*/) {
933
  sotDEBUGIN(25);
934
935
  InitCoMRefval.resize(3);
936
  InitCoMRefval(0) = m_InitCOMRefPos(0);
937
  InitCoMRefval(1) = m_InitCOMRefPos(1);
938
  InitCoMRefval(2) = m_InitCOMRefPos(2);
939
940
  sotDEBUGOUT(25);
941
  return InitCoMRefval;
942
}
943
944
Vector &PatternGenerator::getInitWaistPosRef(Vector &InitWaistRefval,
945
                                             int /*time*/) {
946
  sotDEBUGIN(25);
947
948
  InitWaistRefval = m_InitWaistRefPos;
949
950
  sotDEBUGOUT(25);
951
  return InitWaistRefval;
952
}
953
VectorRollPitchYaw &PatternGenerator::getInitWaistAttRef(
954
    VectorRollPitchYaw &InitWaistRefval, int /*time*/) {
955
  sotDEBUGIN(25);
956
957
  for (unsigned int i = 0; i < 3; ++i)
958
    InitWaistRefval(i) = m_InitWaistRefAtt(i);
959
960
  sotDEBUGOUT(25);
961
  return InitWaistRefval;
962
}
963
964
MatrixHomogeneous &PatternGenerator::getLeftFootRef(
965
    MatrixHomogeneous &LeftFootRefVal, int time) {
966
  sotDEBUGIN(25);
967
968
  OneStepOfControlS(time);
969
  LeftFootRefVal = m_LeftFootPosition;
970
  sotDEBUGOUT(25);
971
  return LeftFootRefVal;
972
}
973
974
MatrixHomogeneous &PatternGenerator::getRightFootRef(
975
    MatrixHomogeneous &RightFootRefval, int time) {
976
  sotDEBUGIN(25);
977
978
  OneStepOfControlS(time);
979
980
  RightFootRefval = m_RightFootPosition;
981
  sotDEBUGOUT(25);
982
  return RightFootRefval;
983
}
984
MatrixHomogeneous &PatternGenerator::getdotLeftFootRef(
985
    MatrixHomogeneous &LeftFootRefVal, int time) {
986
  sotDEBUGIN(25);
987
988
  OneStepOfControlS(time);
989
  LeftFootRefVal = m_dotLeftFootPosition;
990
  sotDEBUGOUT(25);
991
  return LeftFootRefVal;
992
}
993
MatrixHomogeneous &PatternGenerator::getdotRightFootRef(
994
    MatrixHomogeneous &RightFootRefval, int time) {
995
  sotDEBUGIN(25);
996
997
  OneStepOfControlS(time);
998
999
  RightFootRefval = m_dotRightFootPosition;
1000
  sotDEBUGOUT(25);
1001
  return RightFootRefval;
1002
}
1003
1004
MatrixHomogeneous &PatternGenerator::getInitLeftFootRef(
1005
    MatrixHomogeneous &LeftFootRefVal, int /*time*/) {
1006
  sotDEBUGIN(25);
1007
1008
  LeftFootRefVal = m_InitLeftFootPosition;
1009
  sotDEBUGOUT(25);
1010
  return LeftFootRefVal;
1011
}
1012
MatrixHomogeneous &PatternGenerator::getInitRightFootRef(
1013
    MatrixHomogeneous &RightFootRefval, int /*time*/) {
1014
  sotDEBUGIN(25);
1015
1016
  RightFootRefval = m_InitRightFootPosition;
1017
  sotDEBUGOUT(25);
1018
  return RightFootRefval;
1019
}
1020
1021
MatrixHomogeneous &PatternGenerator::getFlyingFootRef(
1022
    MatrixHomogeneous &FlyingFootRefval, int time) {
1023
  sotDEBUGIN(25);
1024
  OneStepOfControlS(time);
1025
  FlyingFootRefval = m_FlyingFootPosition;
1026
  sotDEBUGOUT(25);
1027
  return FlyingFootRefval;
1028
}
1029
1030
bool &PatternGenerator ::getLeftFootContact(bool &res, int time) {
1031
  sotDEBUGIN(25);
1032
  OneStepOfControlS(time);
1033
  res = m_leftFootContact;
1034
  sotDEBUGOUT(25);
1035
  return res;
1036
}
1037
1038
bool &PatternGenerator ::getRightFootContact(bool &res, int time) {
1039
  sotDEBUGIN(25);
1040
  OneStepOfControlS(time);
1041
  res = m_rightFootContact;
1042
  sotDEBUGOUT(25);
1043
  return res;
1044
}
1045
1046
int &PatternGenerator ::getContactPhase(int &res, int time) {
1047
  sotDEBUGIN(25);
1048
  OneStepOfControlS(time);
1049
  res = m_ContactPhase;
1050
  sotDEBUGOUT(25);
1051
  return res;
1052
}
1053
1054
int &PatternGenerator::InitOneStepOfControl(int &dummy, int /*time*/) {
1055
  sotDEBUGIN(15);
1056
  // TODO: modified first to avoid the loop.
1057
  firstSINTERN.setReady(false);
1058
  //  buildModel();
1059
  // Todo: modified the order of the calls
1060
  // OneStepOfControlS(time);
1061
  sotDEBUGIN(15);
1062
  return dummy;
1063
}
1064
1065
void PatternGenerator::getAbsoluteWaistPosAttHomogeneousMatrix(
1066
    MatrixHomogeneous &aWaistMH) {
1067
  const double cr = cos(m_WaistAttitudeAbsolute(0));  // ROLL
1068
  const double sr = sin(m_WaistAttitudeAbsolute(0));
1069
  const double cp = cos(m_WaistAttitudeAbsolute(1));  // PITCH
1070
  const double sp = sin(m_WaistAttitudeAbsolute(1));
1071
  const double cy = cos(m_WaistAttitudeAbsolute(2));  // YAW
1072
  const double sy = sin(m_WaistAttitudeAbsolute(2));
1073
1074
  aWaistMH.matrix().setZero();
1075
1076
  aWaistMH(0, 0) = cy * cp;
1077
  aWaistMH(0, 1) = cy * sp * sr - sy * cr;
1078
  aWaistMH(0, 2) = cy * sp * cr + sy * sr;
1079
  aWaistMH(0, 3) = m_WaistPositionAbsolute(0);
1080
1081
  aWaistMH(1, 0) = sy * cp;
1082
  aWaistMH(1, 1) = sy * sp * sr + cy * cr;
1083
  aWaistMH(1, 2) = sy * sp * cr - cy * sr;
1084
  aWaistMH(1, 3) = m_WaistPositionAbsolute(1);
1085
1086
  aWaistMH(2, 0) = -sp;
1087
  aWaistMH(2, 1) = cp * sr;
1088
  aWaistMH(2, 2) = cp * cr;
1089
  aWaistMH(2, 3) = m_WaistPositionAbsolute(2);
1090
1091
  aWaistMH(3, 3) = 1.0;
1092
}
1093
1094
void PatternGenerator::FromAbsoluteFootPosToDotHomogeneous(
1095
    pg::FootAbsolutePosition aFootPosition, MatrixHomogeneous &aFootMH,
1096
    MatrixHomogeneous &adotFootMH) {
1097
  MatrixRotation dRot, Twist, Rot;
1098
  adotFootMH.setIdentity();
1099
  FromAbsoluteFootPosToHomogeneous(aFootPosition, aFootMH);
1100
1101
  for (unsigned int i = 0; i < 3; i++)
1102
    for (unsigned int j = 0; j < 3; j++) Rot(i, j) = aFootMH(i, j);
1103
1104
  Twist(0, 0) = 0.0;
1105
  Twist(0, 1) = -aFootPosition.dtheta;
1106
  Twist(0, 2) = aFootPosition.domega;
1107
  Twist(1, 0) = aFootPosition.dtheta;
1108
  Twist(1, 1) = 0.0;
1109
  Twist(1, 2) = aFootPosition.domega2;
1110
  Twist(2, 0) = -aFootPosition.domega;
1111
  Twist(2, 1) = -aFootPosition.domega2;
1112
  Twist(2, 2) = 0.0;
1113
1114
  dRot = Twist * Rot;
1115
1116
  for (unsigned int i = 0; i < 3; i++)
1117
    for (unsigned int j = 0; j < 3; j++) adotFootMH(i, j) = dRot(i, j);
1118
1119
  adotFootMH(0, 3) = aFootPosition.dx;
1120
  adotFootMH(1, 3) = aFootPosition.dy;
1121
  adotFootMH(2, 3) = aFootPosition.dz;
1122
}
1123
1124
void PatternGenerator::FromAbsoluteFootPosToHomogeneous(
1125
    pg::FootAbsolutePosition aFootPosition, MatrixHomogeneous &aFootMH) {
1126
  double c, s, co, so;
1127
  c = cos(aFootPosition.theta * M_PI / 180.0);
1128
  s = sin(aFootPosition.theta * M_PI / 180.0);
1129
1130
  co = cos(aFootPosition.omega * M_PI / 180.0);
1131
  so = sin(aFootPosition.omega * M_PI / 180.0);
1132
1133
  aFootMH(0, 0) = c * co;
1134
  aFootMH(0, 1) = -s;
1135
  aFootMH(0, 2) = c * so;
1136
  aFootMH(1, 0) = s * co;
1137
  aFootMH(1, 1) = c;
1138
  aFootMH(1, 2) = s * so;
1139
  aFootMH(2, 0) = -so;
1140
  aFootMH(2, 1) = 0;
1141
  aFootMH(2, 2) = co;
1142
  aFootMH(3, 0) = 0;
1143
  aFootMH(3, 1) = 0;
1144
  aFootMH(3, 2) = 0;
1145
1146
  aFootMH(0, 3) = aFootPosition.x + m_AnkleSoilDistance * so;
1147
  aFootMH(1, 3) = aFootPosition.y;
1148
  aFootMH(2, 3) = aFootPosition.z + m_AnkleSoilDistance * co;
1149
  aFootMH(3, 3) = 1.0;
1150
}
1151
1152
void PatternGenerator::SubsamplingFootPos(
1153
    pg::FootAbsolutePosition &PrevFootPosition,
1154
    pg::FootAbsolutePosition &NextFootPosition,
1155
    MatrixHomogeneous &FootPositionOut, MatrixHomogeneous &dotFootPositionOut,
1156
    unsigned int &count) {
1157
  pg::FootAbsolutePosition lFootPosition;
1158
1159
  lFootPosition.x =
1160
      PrevFootPosition.x +
1161
      (NextFootPosition.x - PrevFootPosition.x) * (double)(count % 5) / 5.0;
1162
  lFootPosition.y =
1163
      PrevFootPosition.y +
1164
      (NextFootPosition.y - PrevFootPosition.y) * (double)(count % 5) / 5.0;
1165
  lFootPosition.z =
1166
      PrevFootPosition.z +
1167
      (NextFootPosition.z - PrevFootPosition.z) * (double)(count % 5) / 5.0;
1168
  lFootPosition.theta = PrevFootPosition.theta +
1169
                        (NextFootPosition.theta - PrevFootPosition.theta) *
1170
                            (double)(count % 5) / 5.0;
1171
  lFootPosition.omega = PrevFootPosition.omega +
1172
                        (NextFootPosition.omega - PrevFootPosition.omega) *
1173
                            (double)(count % 5) / 5.0;
1174
  lFootPosition.omega2 = PrevFootPosition.omega2 +
1175
                         (NextFootPosition.omega2 - PrevFootPosition.omega2) *
1176
                             (double)(count % 5) / 5.0;
1177
1178
  /* Fill in the homogeneous matrix using the world reference frame*/
1179
  FromAbsoluteFootPosToDotHomogeneous(lFootPosition, FootPositionOut,
1180
                                      dotFootPositionOut);
1181
}
1182
1183
void PatternGenerator::SubsamplingVector(dynamicgraph::Vector &PrevPosition,
1184
                                         dynamicgraph::Vector &NextPosition,
1185
                                         dynamicgraph::Vector &PositionOut,
1186
                                         unsigned int &count) {
1187
  for (unsigned int i = 0; i < 3; i++) {
1188
    PositionOut(i) = PrevPosition(i) + (NextPosition(i) - PrevPosition(i)) *
1189
                                           (double)(count % 5) / 5.0;
1190
  }
1191
}
1192
1193
void PatternGenerator::CopyFootPosition(
1194
    pg::FootAbsolutePosition &FootPositionIn,
1195
    pg::FootAbsolutePosition &FootPositionOut) {
1196
  FootPositionOut.x = FootPositionIn.x;
1197
  FootPositionOut.y = FootPositionIn.y;
1198
  FootPositionOut.z = FootPositionIn.z;
1199
  FootPositionOut.theta = FootPositionIn.theta;
1200
  FootPositionOut.omega = FootPositionIn.omega;
1201
  FootPositionOut.omega2 = FootPositionIn.omega2;
1202
}
1203
1204
int &PatternGenerator::OneStepOfControl(int &dummy, int time) {
1205
  m_LocalTime = time;
1206
  int lSupportFoot;  // Local support foot.
1207
  // Default value
1208
  m_JointErrorValuesForWalking.fill(0.0);
1209
  const dynamicgraph::Vector::Index robotSize =
1210
      m_JointErrorValuesForWalking.size() + 6;
1211
1212
  try {
1213
    for (unsigned int i = 0; i < 3; i++) m_ZMPRefPos(i) = m_ZMPPrevious[i];
1214
  } catch (...) {
1215
    m_ZMPRefPos(0) = m_ZMPRefPos(1) = m_ZMPRefPos(2) = 0.0;
1216
    m_ZMPRefPos(3) = 1.0;
1217
  };
1218
  //  m_WaistAttitudeAbsolute.fill(0);
1219
  //  m_WaistPositionAbsolute.fill(0);
1220
1221
  try {
1222
    m_LeftFootPosition = LeftFootCurrentPosSIN(time);
1223
    m_RightFootPosition = RightFootCurrentPosSIN(time);
1224
  } catch (...) {
1225
  };
1226
1227
  try {
1228
    m_VelocityReference = velocitydesSIN(time);
1229
  } catch (...) {
1230
  };
1231
1232
  try {
1233
    m_trigger = triggerSIN(time);
1234
  } catch (...) {
1235
  };
1236
1237
  sotDEBUG(25) << "LeftFootCurrentPos:  " << m_LeftFootPosition << endl;
1238
  sotDEBUG(25) << "RightFootCurrentPos:  " << m_RightFootPosition << endl;
1239
1240
  sotDEBUGIN(15);
1241
1242
  if (m_PGI != 0 and m_trigger) {
1243
    // TODO: Calling firstSINTERN may cause an infinite loop
1244
    // since the function initonestepofcontrol calls without
1245
    // control this actual function. 'Hopefully', the function
1246
    // pointer of firstSINTERN has been earlier destroyed
1247
    // by setconstant(0).
1248
    firstSINTERN(time);
1249
    Vector CurrentState = motorControlJointPositionSIN(time);
1250
    assert(CurrentState.size() == robotSize);
1251
1252
    /*! \brief Absolute Position for the left and right feet. */
1253
    pg::FootAbsolutePosition lLeftFootPosition, lRightFootPosition;
1254
    lLeftFootPosition.x = 0.0;
1255
    lLeftFootPosition.y = 0.0;
1256
    lLeftFootPosition.z = 0.0;
1257
    lRightFootPosition.x = 0.0;
1258
    lRightFootPosition.y = 0.0;
1259
    lRightFootPosition.z = 0.0;
1260
    /*! \brief Absolute position of the reference CoM. */
1261
1262
    pg::COMState lCOMRefState;
1263
    sotDEBUG(45) << "mc = " << CurrentState << std::endl;
1264
1265
    Eigen::VectorXd CurrentConfiguration(robotSize);
1266
    Eigen::VectorXd CurrentVelocity(robotSize);
1267
    Eigen::VectorXd CurrentAcceleration(robotSize);
1268
    Eigen::VectorXd ZMPTarget(3);
1269
    ZMPTarget.setZero();
1270
1271
    sotDEBUG(25) << "Before One Step of control " << lCOMRefState.x[0] << " "
1272
                 << lCOMRefState.y[0] << " " << lCOMRefState.z[0] << endl;
1273
    sotDEBUG(4) << " VelocityReference " << m_VelocityReference << endl;
1274
1275
    m_PGI->setVelocityReference(m_VelocityReference(0), m_VelocityReference(1),
1276
                                m_VelocityReference(2));
1277
1278
    try {
1279
      if (m_feedBackControl) {
1280
        Eigen::Vector3d curCoMState;
1281
        Eigen::Vector3d curZMP;
1282
1283
        curCoMState = comStateSIN(time);
1284
        curZMP = zmpSIN(time);
1285
1286
        lCOMRefState.x[0] = curCoMState(0);
1287
        lCOMRefState.y[0] = curCoMState(1);
1288
        lCOMRefState.z[0] = curCoMState(2);
1289
        lCOMRefState.x[2] =
1290
            (lCOMRefState.x[0] - curZMP(0)) * 9.81 / lCOMRefState.z[0];
1291
        lCOMRefState.y[2] =
1292
            (lCOMRefState.y[0] - curZMP(1)) * 9.81 / lCOMRefState.z[0];
1293
        lCOMRefState.z[2] = 0.0;
1294
1295
        //          for (unsigned i=0 ; i<3 ; ++i)
1296
        //            lCOMRefState.x[i] = curCoMState(i) ;
1297
        //          for (unsigned i=0 ; i<3 ; ++i)
1298
        //            lCOMRefState.y[i] = curCoMState(i+3) ;
1299
        //          for (unsigned i=0 ; i<3 ; ++i)
1300
        //            lCOMRefState.z[i] = curCoMState(i+6) ;
1301
1302
        //          ZMPTarget(0) = lCOMRefState.x[0]
1303
        // -lCOMRefState.x[2]*lCOMRefState.z[0]/9.81 ;
1304
        //          ZMPTarget(1) = lCOMRefState.y[0]-
1305
        //  lCOMRefState.y[2]*lCOMRefState.z[0]/9.81 ;
1306
        //          ZMPTarget(2) = 0.0;
1307
        // to be fixed considering the support foot
1308
      }
1309
    } catch (...) {
1310
      cout << "problems with signals reading" << endl;
1311
      useFeedBackSignals(false);
1312
    };
1313
1314
    try {
1315
      if (m_forceFeedBack) {
1316
        Vector extForce(3);
1317
        extForce = forceSIN(time);
1318
        if (time < 50 * 0.005) {
1319
          m_initForce = extForce;
1320
        }
1321
        extForce -= m_initForce;
1322
        unsigned int n = 321;
1323
        if (m_bufferForce.size() < n - 1) {
1324
          m_bufferForce.push_back(extForce);
1325
        } else {
1326
          m_bufferForce.push_back(extForce);
1327
          double ltmp1(0.0), ltmp2(0.0), ltmp3(0.0);
1328
          for (unsigned int k = 0; k < m_filterWindow.size(); k++) {
1329
            ltmp1 += m_filterWindow[k] * m_bufferForce[n - 1 - k](0);
1330
            ltmp2 += m_filterWindow[k] * m_bufferForce[n - 1 - k](1);
1331
            ltmp3 += m_filterWindow[k] * m_bufferForce[n - 1 - k](2);
1332
          }
1333
          extForce(0) = ltmp1;
1334
          extForce(1) = ltmp2;
1335
          extForce(2) = ltmp3;
1336
          m_bufferForce.pop_front();
1337
        }
1338
        double threshold = 7.0;
1339
        double thresholdy = 4.0;
1340
        if (extForce(0) > threshold) extForce(0) = threshold;
1341
        if (extForce(0) < -threshold) extForce(0) = -threshold;
1342
1343
        if (extForce(1) > thresholdy) extForce(1) = thresholdy;
1344
        if (extForce(1) < -thresholdy) extForce(1) = -thresholdy;
1345
1346
        if (extForce(2) > threshold) extForce(2) = threshold;
1347
        if (extForce(2) < -threshold) extForce(2) = -threshold;
1348
1349
        if ((extForce(0) * extForce(0) + extForce(1) * extForce(1)) < 100) {
1350
          extForce(0) = 0.0;
1351
          extForce(1) = 0.0;
1352
        }
1353
        m_currentForces = extForce;
1354
        ostringstream oss("");
1355
        // oss << ":perturbationforce " << extForce(0) << " "
1356
        // << extForce(1) << " " << extForce(2);
1357
        oss << ":perturbationforce " << -m_currentForces(1) << " "
1358
            << /*m_currentForces(0)*/ 0.0 << " " << m_currentForces(2);
1359
        // cout << oss.str() << endl ;
1360
        pgCommandLine(oss.str());
1361
      }
1362
    } catch (...) {
1363
      // cout << "problems with force signals reading" << endl;
1364
    };
1365
1366
    if (m_count % 5 == 0) {
1367
      if (m_count > 1)  // Change of previous state
1368
      {
1369
        for (unsigned int i = 0; i < 3; i++) {
1370
          m_PrevSamplingCOMRefPos(i) = m_NextSamplingCOMRefPos(i);
1371
          m_PrevSamplingdCOMRefPos(i) = m_NextSamplingdCOMRefPos(i);
1372
          m_PrevSamplingddCOMRefPos(i) = m_NextSamplingddCOMRefPos(i);
1373
          m_PrevSamplingWaistAttAbs(i) = m_NextSamplingWaistAttAbs(i);
1374
        }
1375
        CopyFootPosition(m_NextSamplingLeftFootAbsPos,
1376
                         m_PrevSamplingLeftFootAbsPos);
1377
        CopyFootPosition(m_NextSamplingRightFootAbsPos,
1378
                         m_PrevSamplingRightFootAbsPos);
1379
      } else {
1380
        for (unsigned int i = 0; i < 3; i++) {
1381
          m_PrevSamplingCOMRefPos(i) = m_InitCOMRefPos(i);
1382
          m_PrevSamplingdCOMRefPos(i) = 0.0;
1383
          m_PrevSamplingddCOMRefPos(i) = 0.0;
1384
          m_PrevSamplingWaistAttAbs(i) = m_InitWaistRefAtt(i);
1385
        }
1386
        CopyFootPosition(m_InitLeftFootAbsPos, m_PrevSamplingLeftFootAbsPos);
1387
        CopyFootPosition(m_InitRightFootAbsPos, m_PrevSamplingRightFootAbsPos);
1388
      }
1389
      // Test if the pattern value has some value to provide.
1390
      if (m_PGI->RunOneStepOfTheControlLoop(
1391
              CurrentConfiguration, CurrentVelocity, CurrentAcceleration,
1392
              ZMPTarget, lCOMRefState, lLeftFootPosition, lRightFootPosition)) {
1393
        sotDEBUG(25) << "After One Step of control " << endl
1394
                     << "CurrentState:" << CurrentState << endl
1395
                     << "CurrentConfiguration:" << CurrentConfiguration << endl;
1396
1397
        m_ZMPRefPos(0) = ZMPTarget[0];
1398
        m_ZMPRefPos(1) = ZMPTarget[1];
1399
        m_ZMPRefPos(2) = ZMPTarget[2];
1400
        m_ZMPRefPos(3) = 1.0;
1401
        sotDEBUG(2) << "ZMPTarget returned by the PG: " << m_ZMPRefPos << endl;
1402
        for (int i = 0; i < 3; i++) {
1403
          m_WaistPositionAbsolute(i) = CurrentConfiguration(i);
1404
          m_WaistAttitudeAbsolute(i) = CurrentConfiguration(i + 3);
1405
        }
1406
1407
        getAbsoluteWaistPosAttHomogeneousMatrix(m_WaistAttitudeMatrixAbsolute);
1408
1409
        m_COMRefPos(0) = lCOMRefState.x[0];
1410
        m_COMRefPos(1) = lCOMRefState.y[0];
1411
        m_COMRefPos(2) = lCOMRefState.z[0];
1412
        sotDEBUG(2) << "COMRefPos returned by the PG: " << m_COMRefPos << endl;
1413
1414
        m_dCOMRefPos(0) = lCOMRefState.x[1];
1415
        m_dCOMRefPos(1) = lCOMRefState.y[1];
1416
        m_dCOMRefPos(2) = lCOMRefState.z[1];
1417
1418
        m_ddCOMRefPos(0) = lCOMRefState.x[2];
1419
        m_ddCOMRefPos(1) = lCOMRefState.y[2];
1420
        m_ddCOMRefPos(2) = lCOMRefState.z[2];
1421
1422
        m_ComAttitude(0) = lCOMRefState.roll[0];
1423
        m_ComAttitude(1) = lCOMRefState.pitch[0];
1424
        m_ComAttitude(2) = lCOMRefState.yaw[0];
1425
1426
        m_dComAttitude(0) = lCOMRefState.roll[1];
1427
        m_dComAttitude(1) = lCOMRefState.pitch[1];
1428
        m_dComAttitude(2) = lCOMRefState.yaw[1];
1429
1430
        m_ddComAttitude(0) = lCOMRefState.roll[2];
1431
        m_ddComAttitude(1) = lCOMRefState.pitch[2];
1432
        m_ddComAttitude(2) = lCOMRefState.yaw[2];
1433
1434
        sotDEBUG(2) << "dCOMRefPos returned by the PG: " << m_dCOMRefPos
1435
                    << endl;
1436
        sotDEBUG(2) << "CurrentState.size()" << CurrentState.size() << endl;
1437
        sotDEBUG(2) << "CurrentConfiguration.size()"
1438
                    << CurrentConfiguration.size() << endl;
1439
        sotDEBUG(2) << "m_JointErrorValuesForWalking.size(): "
1440
                    << m_JointErrorValuesForWalking.size() << endl;
1441
1442
        // In this setting we assume that there is a
1443
        // proper mapping between
1444
        // CurrentState and CurrentConfiguration.
1445
        Vector::Index SizeCurrentState = CurrentState.size();
1446
        Vector::Index SizeCurrentConfiguration =
1447
            CurrentConfiguration.size() - 6;
1448
        Vector::Index MinSize =
1449
            std::min(SizeCurrentState, SizeCurrentConfiguration);
1450
1451
        if (m_JointErrorValuesForWalking.size() >= MinSize) {
1452
          for (unsigned int li = 0; li < MinSize; li++)
1453
            m_JointErrorValuesForWalking(li) =
1454
                (CurrentConfiguration(li + 6) - CurrentState(li)) / m_TimeStep;
1455
        } else {
1456
          std::cout << "The state of the robot and the one "
1457
                    << "return by the WPG are different" << std::endl;
1458
          sotDEBUG(25) << "Size not coherent between "
1459
                       << "CurrentState and "
1460
                       << "m_JointErrorValuesForWalking: "
1461
                       << CurrentState.size() << " "
1462
                       << m_JointErrorValuesForWalking.size() << " " << endl;
1463
        }
1464
        sotDEBUG(2) << "Juste after updating "
1465
                    << "m_JointErrorValuesForWalking" << endl;
1466
1467
        sotDEBUG(1) << "lLeftFootPosition : " << lLeftFootPosition.x << " "
1468
                    << lLeftFootPosition.y << " " << lLeftFootPosition.z << " "
1469
                    << lLeftFootPosition.theta << endl;
1470
1471
        sotDEBUG(1) << "lRightFootPosition : " << lRightFootPosition.x << " "
1472
                    << lRightFootPosition.y << " " << lRightFootPosition.z
1473
                    << " " << lRightFootPosition.theta << endl;
1474
1475
        sotDEBUG(25) << "lCOMPosition : " << lCOMRefState.x[0] << " "
1476
                     << lCOMRefState.y[0] << " " << lCOMRefState.z[0] << endl;
1477
1478
        // Set Next position ---------------------------------------------
1479
        for (unsigned int i = 0; i < 3; i++) {
1480
          m_NextSamplingCOMRefPos(i) = m_COMRefPos(i);
1481
          m_NextSamplingdCOMRefPos(i) = m_dCOMRefPos(i);
1482
          m_NextSamplingddCOMRefPos(i) = m_ddCOMRefPos(i);
1483
          m_NextSamplingWaistAttAbs(i) = m_WaistAttitudeAbsolute(i);
1484
        }
1485
1486
        CopyFootPosition(lRightFootPosition, m_NextSamplingRightFootAbsPos);
1487
        CopyFootPosition(lLeftFootPosition, m_NextSamplingLeftFootAbsPos);
1488
      } else {
1489
        sotDEBUG(1) << "Error while compute one step of PG." << m_dataInProcess
1490
                    << std::endl;
1491
        // TODO: SOT_THROW
1492
        if (m_dataInProcess == 1) {
1493
          MatrixHomogeneous invInitLeftFootRef, Diff;
1494
          invInitLeftFootRef = m_InitLeftFootPosition.inverse();
1495
          Diff = invInitLeftFootRef * m_LeftFootPosition;
1496
1497
          m_k_Waist_kp1 = m_k_Waist_kp1 * Diff;
1498
        }
1499
        m_dataInProcess = 0;
1500
      }
1501
      sotDEBUG(25) << "After computing error " << m_JointErrorValuesForWalking
1502
                   << endl;
1503
    }
1504
    // Subsampling
1505
1506
    SubsamplingVector(m_PrevSamplingCOMRefPos, m_NextSamplingCOMRefPos,
1507
                      m_COMRefPos, m_count);
1508
    SubsamplingVector(m_PrevSamplingdCOMRefPos, m_NextSamplingdCOMRefPos,
1509
                      m_dCOMRefPos, m_count);
1510
    SubsamplingVector(m_PrevSamplingddCOMRefPos, m_NextSamplingddCOMRefPos,
1511
                      m_ddCOMRefPos, m_count);
1512
    SubsamplingVector(m_PrevSamplingWaistAttAbs, m_NextSamplingWaistAttAbs,
1513
                      m_WaistAttitudeAbsolute, m_count);
1514
    SubsamplingFootPos(m_PrevSamplingRightFootAbsPos,
1515
                       m_NextSamplingRightFootAbsPos, m_RightFootPosition,
1516
                       m_dotRightFootPosition, m_count);
1517
    SubsamplingFootPos(m_PrevSamplingLeftFootAbsPos,
1518
                       m_NextSamplingLeftFootAbsPos, m_LeftFootPosition,
1519
                       m_dotLeftFootPosition, m_count);
1520
1521
    getAbsoluteWaistPosAttHomogeneousMatrix(m_WaistAttitudeMatrixAbsolute);
1522
    // end added lines for test on waist
1523
1524
    m_count++;
1525
1526
    Eigen::Matrix<double, 4, 1> newRefPos, oldRefPos;
1527
    oldRefPos(0) = m_COMRefPos(0);
1528
    oldRefPos(1) = m_COMRefPos(1);
1529
    oldRefPos(2) = m_COMRefPos(2);
1530
    oldRefPos(3) = 1.0;
1531
    newRefPos = m_MotionSinceInstanciationToThisSequence * oldRefPos;
1532
    m_COMRefPos(0) = newRefPos(0);
1533
    m_COMRefPos(1) = newRefPos(1);
1534
    m_COMRefPos(2) = newRefPos(2);
1535
1536
    oldRefPos(0) = m_ZMPRefPos(0);
1537
    oldRefPos(1) = m_ZMPRefPos(1);
1538
    oldRefPos(2) = m_ZMPRefPos(2);
1539
    oldRefPos(3) = 1.0;
1540
    newRefPos = m_MotionSinceInstanciationToThisSequence * oldRefPos;
1541
    m_ZMPRefPos(0) = newRefPos(0);
1542
    m_ZMPRefPos(1) = newRefPos(1);
1543
    m_ZMPRefPos(2) = newRefPos(2);
1544
1545
    /* We assume that the left foot is always the origin
1546
       of the new frame. */
1547
    m_LeftFootPosition =
1548
        m_MotionSinceInstanciationToThisSequence * m_LeftFootPosition;
1549
    m_RightFootPosition =
1550
        m_MotionSinceInstanciationToThisSequence * m_RightFootPosition;
1551
1552
    sotDEBUG(25) << "lLeftFootPosition.stepType: " << lLeftFootPosition.stepType
1553
                 << " lRightFootPosition.stepType: "
1554
                 << lRightFootPosition.stepType << endl;
1555
1556
    // Find the support foot feet.
1557
    // If stepType = -1 -> single support phase on the dedicated foot
1558
    // If stepType = 10 -> double support phase (both feet should have
1559
    // stepType=10) If stepType = 11 -> double support phase between 2 single
1560
    // support phases for Kajita Algorithm
1561
    if ((lLeftFootPosition.stepType == 10) ||
1562
        (lRightFootPosition.stepType == 10) ||
1563
        (lLeftFootPosition.stepType == 11) ||
1564
        (lRightFootPosition.stepType == 11)) {
1565
      m_leftFootContact = true;
1566
      m_rightFootContact = true;
1567
      m_ContactPhase = DOUBLE_SUPPORT_PHASE;
1568
    }
1569
1570
    if (lLeftFootPosition.stepType == -1) {
1571
      lSupportFoot = 1;
1572
      m_leftFootContact = true;
1573
      // It is almost certain that when there is single support on a foot
1574
      // the other one cannot be in simple support (neither in double support)
1575
      // This if is certainly always true -> to be checked
1576
      if (lRightFootPosition.stepType != -1) {
1577
        m_rightFootContact = false;
1578
        m_ContactPhase = LEFT_SUPPORT_PHASE;
1579
      }
1580
    } else if (lRightFootPosition.stepType == -1) {
1581
      lSupportFoot = 0;
1582
      m_rightFootContact = true;
1583
      // It is almost certain that when there is single support on a foot
1584
      // the other one cannot be in simple support (neither in double support)
1585
      // This if is certainly always true -> to be checked
1586
      if (lLeftFootPosition.stepType != -1) {
1587
        m_leftFootContact = false;
1588
        m_ContactPhase = RIGHT_SUPPORT_PHASE;
1589
      }
1590
    } else
1591
    /* m_LeftFootPosition.z ==m_RightFootPosition.z
1592
       We keep the previous support foot half the time
1593
       of the double support phase..
1594
       */
1595
    {
1596
      lSupportFoot = m_SupportFoot;
1597
    }
1598
1599
    /* Update the class related member. */
1600
    m_SupportFoot = lSupportFoot;
1601
1602
    // Waist
1603
    // ----------------------------------------------------------------------
1604
1605
    if ((m_ReferenceFrame == EGOCENTERED_FRAME) ||
1606
        (m_ReferenceFrame == LEFT_FOOT_CENTERED_FRAME) ||
1607
        (m_ReferenceFrame == WAIST_CENTERED_FRAME)) {
1608
      sotDEBUG(25) << "Inside egocentered frame " << endl;
1609
      MatrixHomogeneous PoseOrigin, iPoseOrigin, WaistPoseAbsolute;
1610
1611
      getAbsoluteWaistPosAttHomogeneousMatrix(WaistPoseAbsolute);
1612
1613
      if (m_ReferenceFrame == EGOCENTERED_FRAME) {
1614
        if (m_SupportFoot == 1)
1615
          PoseOrigin = m_LeftFootPosition;
1616
        else
1617
          PoseOrigin = m_RightFootPosition;
1618
      } else if (m_ReferenceFrame == LEFT_FOOT_CENTERED_FRAME) {
1619
        PoseOrigin = m_LeftFootPosition;
1620
      } else if (m_ReferenceFrame == WAIST_CENTERED_FRAME) {
1621
        PoseOrigin = WaistPoseAbsolute;
1622
      }
1623
      iPoseOrigin = PoseOrigin.inverse();
1624
1625
      sotDEBUG(25) << "Old ComRef:  " << m_COMRefPos << endl;
1626
      sotDEBUG(25) << "Old LeftFootRef:  " << m_LeftFootPosition << endl;
1627
      sotDEBUG(25) << "Old RightFootRef:  " << m_RightFootPosition << endl;
1628
      sotDEBUG(25) << "Old PoseOrigin:  " << PoseOrigin << endl;
1629
1630
      Eigen::Matrix<double, 4, 1> lVZMPRefPos, lV2ZMPRefPos;
1631
      Eigen::Matrix<double, 4, 1> lVCOMRefPos, lV2COMRefPos;
1632
1633
      for (unsigned int li = 0; li < 3; li++) {
1634
        lVZMPRefPos(li) = m_ZMPRefPos(li);
1635
        lVCOMRefPos(li) = m_COMRefPos(li);
1636
      }
1637
      lVZMPRefPos(3) = lVCOMRefPos(3) = 1.0;
1638
1639
      // We do not touch to ZMP.
1640
      lV2ZMPRefPos = iPoseOrigin * (WaistPoseAbsolute * lVZMPRefPos);
1641
1642
      // Put the CoM reference pos in the Pos
1643
      // Origin reference frame.
1644
      lV2COMRefPos = iPoseOrigin * lVCOMRefPos;
1645
1646
      MatrixHomogeneous lMLeftFootPosition = m_LeftFootPosition;
1647
      MatrixHomogeneous lMRightFootPosition = m_RightFootPosition;
1648
1649
      m_LeftFootPosition = iPoseOrigin * lMLeftFootPosition;
1650
      m_RightFootPosition = iPoseOrigin * lMRightFootPosition;
1651
1652
      for (unsigned int i = 0; i < 3; i++) {
1653
        m_ZMPRefPos(i) = lV2ZMPRefPos(i);
1654
        m_COMRefPos(i) = lV2COMRefPos(i);
1655
      }
1656
1657
      WaistPoseAbsolute = iPoseOrigin * WaistPoseAbsolute;
1658
1659
      MatrixRotation newWaistRot;
1660
      newWaistRot = WaistPoseAbsolute.linear();
1661
      VectorRollPitchYaw newWaistRPY;
1662
      newWaistRPY = (newWaistRot.eulerAngles(2, 1, 0)).reverse();
1663
      m_WaistAttitude = newWaistRPY;
1664
1665
      m_WaistPosition = WaistPoseAbsolute.translation();
1666
1667
      m_WaistAttitudeMatrixAbsolute = WaistPoseAbsolute;
1668
1669
      sotDEBUG(25) << "ComRef:  " << m_COMRefPos << endl;
1670
      sotDEBUG(25) << "iPoseOrigin:  " << iPoseOrigin << endl;
1671
    }
1672
    sotDEBUG(25) << "After egocentered frame " << endl;
1673
1674
    sotDEBUG(25) << "ComRef:  " << m_COMRefPos << endl;
1675
    sotDEBUG(25) << "LeftFootRef:  " << m_LeftFootPosition << endl;
1676
    sotDEBUG(25) << "RightFootRef:  " << m_RightFootPosition << endl;
1677
    sotDEBUG(25) << "ZMPRefPos:  " << m_ZMPRefPos << endl;
1678
    sotDEBUG(25) << "m_MotionSinceInstanciationToThisSequence"
1679
                 << m_MotionSinceInstanciationToThisSequence << std::endl;
1680
1681
    for (unsigned int i = 0; i < 3; i++) {
1682
      m_ZMPPrevious[i] = m_ZMPRefPos(i);
1683
    }
1684
1685
    m_dataInProcess = 1;
1686
1687
  } else if (!m_trigger) {
1688
    for (unsigned int i = 0; i < 3; i++) {
1689
      m_COMRefPos(i) = m_InitCOMRefPos(i);
1690
      m_ZMPRefPos(i) = m_InitZMPRefPos(i);
1691
    }
1692
    m_RightFootPosition = m_InitRightFootPosition;
1693
    m_LeftFootPosition = m_InitLeftFootPosition;
1694
  } else {
1695
    m_COMRefPos = comSIN.access(time);
1696
    m_ZMPRefPos(0) = m_COMRefPos(0);
1697
    m_ZMPRefPos(1) = m_COMRefPos(1);
1698
    m_ZMPRefPos(2) = 0.0;
1699
    m_ZMPRefPos(3) = 1.0;
1700
  }
1701
1702
  sotDEBUG(25) << "LeftFootRef:  " << m_LeftFootPosition << endl;
1703
  sotDEBUG(25) << "RightFootRef:  " << m_RightFootPosition << endl;
1704
  sotDEBUG(25) << "COMRef:  " << m_COMRefPos << endl;
1705
1706
  sotDEBUGOUT(15);
1707
  return dummy;
1708
}
1709
1710
/* --- PARAMS ------------------------------------------------ */
1711
/* --- PARAMS ------------------------------------------------ */
1712
1713
1
void PatternGenerator::initCommands(void) {
1714
  using namespace command;
1715

1
  addCommand("setURDFpath",
1716
1
             makeCommandVoid1(*this, &PatternGenerator::setURDFFile,
1717

2
                              docCommandVoid1("Set URDF directory+name.",
1718
                                              "string (path name)")));
1719

1
  addCommand("setSRDFpath",
1720
1
             makeCommandVoid1(*this, &PatternGenerator::setSRDFFile,
1721

2
                              docCommandVoid1("Set SRDF directory+name.",
1722
                                              "string (file name)")));
1723
1724

1
  addCommand(
1725
      "setXmlRank",
1726
1
      makeCommandVoid1(*this, &PatternGenerator::setXmlRankFile,
1727

2
                       docCommandVoid1("Set XML rank file directory+name.",
1728
                                       "string (file name)")));
1729
1730
  std::string docstring =
1731
      "    \n"
1732
      "    Set foot parameters\n"
1733
      "      Input:\n"
1734
      "        - a floating point number: the sole length,\n"
1735
      "        - a floating point number: the sole width,\n"
1736
1
      "    \n";
1737

1
  addCommand(
1738
      "setSoleParameters",
1739
1
      makeCommandVoid2(*this, &PatternGenerator::setSoleParameters, docstring));
1740
1741

1
  addCommand("addJointMapping",
1742
1
             makeCommandVoid2(*this, &PatternGenerator::addJointMapping,
1743

2
                              docCommandVoid1("Map link names.",
1744
                                              "string (link name)"
1745
                                              "string (rep name)")));
1746
1747

1
  addCommand("setParamPreview",
1748
1
             makeCommandVoid1(*this, &PatternGenerator::setParamPreviewFile,
1749

2
                              docCommandVoid1("Set [guess what!] file",
1750
                                              "string (path/filename)")));
1751
1752
  // for the setFiles, need to implement the makeCmdVoid5... later
1753
  // displayfiles... later too
1754

1
  addCommand(
1755
      "buildModel",
1756
1
      makeCommandVoid0(
1757
          *this, (void(PatternGenerator::*)(void)) & PatternGenerator::buildPGI,
1758

2
          docCommandVoid0("From the files, parse and build the robot model and"
1759
                          " the Walking Pattern Generator.")));
1760

1
  addCommand(
1761
      "initState",
1762
1
      makeCommandVoid0(
1763
          *this,
1764
          (void(PatternGenerator::*)(void)) & PatternGenerator::InitState,
1765

2
          docCommandVoid0("From q and model, compute the initial geometry.")));
1766
1767

1
  addCommand(
1768
      "frameReference",
1769
1
      makeCommandVoid1(
1770
          *this, &PatternGenerator::setReferenceFromString,
1771

2
          docCommandVoid1("Set the reference.",
1772
                          "string among "
1773
                          "World|Egocentered|LeftFootcentered|Waistcentered")));
1774
1775

1
  addCommand("getTimeStep",
1776
1
             makeDirectGetter(*this, &m_TimeStep,
1777

2
                              docDirectGetter("timestep", "double")));
1778
1779

1
  addCommand("setTimeStep",
1780
1
             makeDirectSetter(*this, &m_TimeStep,
1781

2
                              docDirectSetter("timestep", "double")));
1782
1783

1
  addCommand("getInitByRealState",
1784
1
             makeDirectGetter(*this, &m_InitPositionByRealState,
1785

2
                              docDirectGetter("initByRealState", "bool")));
1786
1787

1
  addCommand("setInitByRealState",
1788
1
             makeDirectSetter(*this, &m_InitPositionByRealState,
1789

2
                              docDirectSetter("initByRealState", "bool")));
1790
1791

1
  addCommand(
1792
      "addOnLineStep",
1793
1
      makeCommandVoid3(*this, &PatternGenerator::addOnLineStep,
1794


2
                       docCommandVoid3("Add a step on line.", "double (x)",
1795
                                       "double (y)", "double (theta)")));
1796
1797

1
  addCommand(
1798
      "addStep",
1799
1
      makeCommandVoid3(*this, &PatternGenerator::addOnLineStep,
1800


2
                       docCommandVoid3("Add a step in the stack.", "double (x)",
1801
                                       "double (y)", "double (theta)")));
1802
1803

1
  addCommand(
1804
      "parseCmd",
1805
1
      makeCommandVoid1(
1806
          *this, &PatternGenerator::pgCommandLine,
1807

2
          docCommandVoid1("Send the command line to the internal pg object.",
1808
                          "string (command line)")));
1809
1810

1
  addCommand(
1811
      "feedBackControl",
1812
1
      makeCommandVoid1(
1813
          *this, &PatternGenerator::useFeedBackSignals,
1814

2
          docCommandVoid1("Enable or disable the use of the CoMfullState "
1815
                          "Signal inside the pg.",
1816
                          "string (true or false)")));
1817
1818

1
  addCommand(
1819
      "dynamicFilter",
1820
1
      makeCommandVoid1(
1821
          *this, &PatternGenerator::useDynamicFilter,
1822

2
          docCommandVoid1("Enable or disable the use of the CoMfullState "
1823
                          "Signal inside the pg.",
1824
                          "string (true or false)")));
1825
1826
  // Change next step : todo (deal with FootAbsolutePosition...).
1827
1828

1
  addCommand(
1829
      "debug",
1830
1
      makeCommandVoid0(
1831
          *this, (void(PatternGenerator::*)(void)) & PatternGenerator::debug,
1832

2
          docCommandVoid0("Launch a debug command.")));
1833
1
}
1834
1835
void PatternGenerator::debug(void) {
1836
  std::cout << "t = " << dataInProcessSOUT.getTime() << std::endl;
1837
  std::cout << "deptype = " << dataInProcessSOUT.dependencyType << std::endl;
1838
  std::cout << "child = " << dataInProcessSOUT.updateFromAllChildren
1839
            << std::endl;
1840
  std::cout << "last = " << dataInProcessSOUT.lastAskForUpdate << std::endl;
1841
1842
  std::cout << "inprocess = " << dataInProcessSOUT.needUpdate(40) << std::endl;
1843
  std::cout << "onestep = " << OneStepOfControlS.needUpdate(40) << std::endl;
1844
1845
  dataInProcessSOUT.Signal<unsigned int, int>::access(1);
1846
}
1847
1848
void PatternGenerator::addOnLineStep(const double &x, const double &y,
1849
                                     const double &th) {
1850
  assert(m_PGI != 0);
1851
  m_PGI->AddOnLineStep(x, y, th);
1852
}
1853
void PatternGenerator::addStep(const double &x, const double &y,
1854
                               const double &th) {
1855
  assert(m_PGI != 0);
1856
  m_PGI->AddStepInStack(x, y, th);
1857
}
1858
12
void PatternGenerator::pgCommandLine(const std::string &cmdline) {
1859
12
  assert(m_PGI != 0);
1860
24
  std::istringstream cmdArgs(cmdline);
1861
12
  m_PGI->ParseCmd(cmdArgs);
1862
12
}
1863
1864
void PatternGenerator::useFeedBackSignals(const bool &feedBack) {
1865
  m_feedBackControl = feedBack;
1866
  string cmdBool = feedBack ? "true" : "false";
1867
  assert(m_PGI != 0);
1868
  std::istringstream cmdArgs(":feedBackControl " + cmdBool);
1869
  m_PGI->ParseCmd(cmdArgs);
1870
}
1871
1872
void PatternGenerator::useDynamicFilter(const bool &dynamicFilter) {
1873
  m_feedBackControl = dynamicFilter;
1874
  string cmdBool = dynamicFilter ? "true" : "false";
1875
  assert(m_PGI != 0);
1876
  std::istringstream cmdArgs(":useDynamicFilter " + cmdBool);
1877
  m_PGI->ParseCmd(cmdArgs);
1878
}
1879
1880
int PatternGenerator::stringToReferenceEnum(const std::string &FrameReference) {
1881
  if (FrameReference == "World")
1882
    return WORLD_FRAME;
1883
  else if (FrameReference == "Egocentered")
1884
    return EGOCENTERED_FRAME;
1885
  else if (FrameReference == "LeftFootcentered")
1886
    return LEFT_FOOT_CENTERED_FRAME;
1887
  else if (FrameReference == "Waistcentered")
1888
    return WAIST_CENTERED_FRAME;
1889
  assert(false &&
1890
         "String name should be in the list "
1891
         "World|Egocentered|LeftFootcentered|Waistcentered");
1892
  return 0;
1893
}
1894
1895
void PatternGenerator::setReferenceFromString(const std::string &str) {
1896
  m_ReferenceFrame = stringToReferenceEnum(str);
1897
}
1898
1899
Vector &PatternGenerator::getjointWalkingErrorPosition(Vector &res, int time) {
1900
  sotDEBUGIN(5);
1901
  OneStepOfControlS(time);
1902
  res = m_JointErrorValuesForWalking;
1903
  sotDEBUGOUT(5);
1904
1905
  return res;
1906
}
1907
1908
int &PatternGenerator::getSupportFoot(int &res, int /*time*/) {
1909
  res = m_SupportFoot;
1910
  return res;
1911
}
1912
1913
VectorRollPitchYaw &PatternGenerator::getWaistAttitude(VectorRollPitchYaw &res,
1914
                                                       int time) {
1915
  sotDEBUGIN(5);
1916
  OneStepOfControlS(time);
1917
  for (unsigned int i = 0; i < 3; ++i) {
1918
    res(i) = m_WaistAttitude(i);
1919
  }
1920
  sotDEBUG(5) << "WaistAttitude: " << m_WaistAttitude << endl;
1921
  sotDEBUGOUT(5);
1922
  return res;
1923
}
1924
1925
dynamicgraph::Vector &PatternGenerator::getdComAttitude(
1926
    dynamicgraph::Vector &res, int time) {
1927
  sotDEBUGIN(5);
1928
  OneStepOfControlS(time);
1929
  res.resize(3);
1930
  for (unsigned int i = 0; i < 3; ++i) {
1931
    res(i) = m_dComAttitude(i);
1932
  }
1933
  sotDEBUG(5) << "ComAttitude: " << m_dComAttitude << endl;
1934
  sotDEBUGOUT(5);
1935
  return res;
1936
}
1937
1938
dynamicgraph::Vector &PatternGenerator::getddComAttitude(
1939
    dynamicgraph::Vector &res, int time) {
1940
  sotDEBUGIN(5);
1941
  OneStepOfControlS(time);
1942
  res.resize(3);
1943
  for (unsigned int i = 0; i < 3; ++i) {
1944
    res(i) = m_ddComAttitude(i);
1945
  }
1946
  sotDEBUG(5) << "ComAttitude: " << m_ddComAttitude << endl;
1947
  sotDEBUGOUT(5);
1948
  return res;
1949
}
1950
1951
dynamicgraph::Vector &PatternGenerator::getComAttitude(
1952
    dynamicgraph::Vector &res, int time) {
1953
  sotDEBUGIN(5);
1954
  OneStepOfControlS(time);
1955
  res.resize(3);
1956
  for (unsigned int i = 0; i < 3; ++i) {
1957
    res(i) = m_ComAttitude(i);
1958
  }
1959
  sotDEBUG(5) << "ComAttitude: " << m_ComAttitude << endl;
1960
  sotDEBUGOUT(5);
1961
  return res;
1962
}
1963
1964
VectorRollPitchYaw &PatternGenerator::getWaistAttitudeAbsolute(
1965
    VectorRollPitchYaw &res, int time) {
1966
  sotDEBUGIN(5);
1967
  OneStepOfControlS(time);
1968
  sotDEBUG(15) << "I survived one step of control" << std::endl;
1969
  for (unsigned int i = 0; i < 3; ++i) {
1970
    res(i) = m_WaistAttitudeAbsolute(i);
1971
  }
1972
  sotDEBUG(5) << "WaistAttitude: " << m_WaistAttitudeAbsolute << endl;
1973
  sotDEBUGOUT(5);
1974
  return res;
1975
}
1976
1977
MatrixHomogeneous &PatternGenerator::getWaistAttitudeMatrixAbsolute(
1978
    MatrixHomogeneous &res, int time) {
1979
  sotDEBUGIN(5);
1980
  OneStepOfControlS(time);
1981
  res = m_WaistAttitudeMatrixAbsolute;
1982
  sotDEBUGOUT(5);
1983
  return res;
1984
}
1985
1986
Vector &PatternGenerator::getWaistPosition(Vector &res, int time) {
1987
  sotDEBUGIN(5);
1988
  OneStepOfControlS(time);
1989
  res = m_WaistPosition;
1990
  sotDEBUG(5) << "WaistPosition: " << m_WaistPosition << endl;
1991
  sotDEBUGOUT(5);
1992
  return res;
1993
}
1994
Vector &PatternGenerator::getWaistPositionAbsolute(Vector &res, int time) {
1995
  sotDEBUGIN(5);
1996
  OneStepOfControlS(time);
1997
  res = m_WaistPositionAbsolute;
1998
  /* ARGH ! ->  res(2) =0*/
1999
  sotDEBUG(5) << "WaistPosition: " << m_WaistPositionAbsolute << endl;
2000
  sotDEBUGOUT(5);
2001
  return res;
2002
}
2003
2004
unsigned &PatternGenerator::getDataInProcess(unsigned &res, int time) {
2005
  sotDEBUGIN(5);
2006
  OneStepOfControlS(time);
2007
  res = m_dataInProcess;
2008
  sotDEBUG(5) << "DataInProcess: " << m_dataInProcess << endl;
2009
  sotDEBUGOUT(5);
2010
  return res;
2011
}
2012
2013
void PatternGenerator::setSoleParameters(const double &inSoleLength,
2014
                                         const double &inSoleWidth) {
2015
  m_soleLength = inSoleLength;
2016
  m_soleWidth = inSoleWidth;
2017
}
2018
}  // namespace sot
2019
}  // namespace dynamicgraph