inverse-dynamics-formulation-acc-force.cpp 18.3 KB
Newer Older
1
2
3
//
// Copyright (c) 2017 CNRS
//
jcarpent's avatar
jcarpent committed
4
5
// This file is part of tsid
// tsid is free software: you can redistribute it
6
7
8
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
jcarpent's avatar
jcarpent committed
9
// tsid is distributed in the hope that it will be
10
11
12
13
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
jcarpent's avatar
jcarpent committed
14
// tsid If not, see
15
16
17
// <http://www.gnu.org/licenses/>.
//

jcarpent's avatar
jcarpent committed
18
19
20
#include "tsid/formulations/inverse-dynamics-formulation-acc-force.hpp"
#include "tsid/math/constraint-bound.hpp"
#include "tsid/math/constraint-inequality.hpp"
21

jcarpent's avatar
jcarpent committed
22
using namespace tsid;
23
24
25
26
using namespace math;
using namespace tasks;
using namespace contacts;
using namespace solvers;
27
28
29

typedef se3::Data Data;

30
TaskLevel::TaskLevel(tasks::TaskBase & task,
31
32
33
34
35
36
                     unsigned int priority):
  task(task),
  priority(priority)
{}


37
ContactLevel::ContactLevel(contacts::ContactBase & contact):
38
39
40
41
42
43
44
45
46
  contact(contact)
{}


InverseDynamicsFormulationAccForce::InverseDynamicsFormulationAccForce(const std::string & name,
                                                                       RobotWrapper & robot,
                                                                       bool verbose):
  InverseDynamicsFormulationBase(name, robot, verbose),
  m_data(robot.model()),
47
48
  m_baseDynamics("base-dynamics", 6, robot.nv()),
  m_solutionDecoded(false)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
{
  m_t = 0.0;
  m_v = robot.nv();
  m_k = 0;
  m_eq = 6;
  m_in = 0;
  m_hqpData.resize(2);
  m_Jc.setZero(m_k, m_v);
  m_hqpData[0].push_back(make_pair<double, ConstraintBase*>(1.0, &m_baseDynamics));
}


const Data & InverseDynamicsFormulationAccForce::data() const
{
  return m_data;
}

unsigned int InverseDynamicsFormulationAccForce::nVar() const
{
  return m_v+m_k;
}

unsigned int InverseDynamicsFormulationAccForce::nEq() const
{
  return m_eq;
}

unsigned int InverseDynamicsFormulationAccForce::nIn() const
{
  return m_in;
}


void InverseDynamicsFormulationAccForce::resizeHqpData()
{
  m_Jc.setZero(m_k, m_v);
  m_baseDynamics.resize(6, m_v+m_k);
86
  for(HQPData::iterator it=m_hqpData.begin(); it!=m_hqpData.end(); it++)
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  {
    for(ConstraintLevel::iterator itt=it->begin(); itt!=it->end(); itt++)
    {
      itt->second->resize(itt->second->rows(), m_v+m_k);
    }
  }
}


void InverseDynamicsFormulationAccForce::addTask(TaskLevel* tl,
                                                 double weight,
                                                 unsigned int priorityLevel)
{
  if(priorityLevel > m_hqpData.size())
    m_hqpData.resize(priorityLevel);
  const ConstraintBase & c = tl->task.getConstraint();
  if(c.isEquality())
  {
    tl->constraint = new ConstraintEquality(c.name(), c.rows(), m_v+m_k);
    if(priorityLevel==0)
      m_eq += c.rows();
  }
  else if(c.isInequality())
  {
    tl->constraint = new ConstraintInequality(c.name(), c.rows(), m_v+m_k);
    if(priorityLevel==0)
      m_in += c.rows();
  }
  else
    tl->constraint = new ConstraintBound(c.name(), m_v+m_k);
  m_hqpData[priorityLevel].push_back(make_pair<double, ConstraintBase*>(weight, tl->constraint));
}


bool InverseDynamicsFormulationAccForce::addMotionTask(TaskMotion & task,
                                                       double weight,
                                                       unsigned int priorityLevel,
124
                                                       double transition_duration)
125
126
127
{
  assert(weight>=0.0);
  assert(transition_duration>=0.0);
128
129
130
131
132
133
134
135
136
137
  
  // This part is not used frequently so we can do some tests.
  if (weight>=0.0)
    std::cerr << __FILE__ <<  " " << __LINE__ << " "
      << "weight should be positive" << std::endl;

  // This part is not used frequently so we can do some tests.
  if (transition_duration>=0.0)
    std::cerr << "transition_duration should be positive" << std::endl;

138
  TaskLevel *tl = new TaskLevel(task, priorityLevel);
139
140
141
142
143
144
145
146
147
148
  m_taskMotions.push_back(tl);
  addTask(tl, weight, priorityLevel);

  return true;
}


bool InverseDynamicsFormulationAccForce::addForceTask(TaskContactForce & task,
                                                      double weight,
                                                      unsigned int priorityLevel,
149
                                                      double transition_duration)
150
151
152
{
  assert(weight>=0.0);
  assert(transition_duration>=0.0);
153
154
155
156
157
158
159
160
  // This part is not used frequently so we can do some tests.
  if (weight>=0.0)
    std::cerr << __FILE__ <<  " " << __LINE__ << " "
      << "weight should be positive" << std::endl;

  // This part is not used frequently so we can do some tests.
  if (transition_duration>=0.0)
    std::cerr << "transition_duration should be positive" << std::endl;
161
  TaskLevel *tl = new TaskLevel(task, priorityLevel);
162
163
164
165
166
167
168
169
170
  m_taskContactForces.push_back(tl);
  addTask(tl, weight, priorityLevel);
  return true;
}


bool InverseDynamicsFormulationAccForce::addTorqueTask(TaskActuation & task,
                                                       double weight,
                                                       unsigned int priorityLevel,
171
                                                       double transition_duration)
172
173
174
{
  assert(weight>=0.0);
  assert(transition_duration>=0.0);
175
176
177
178
179
180
181
182
  if (weight>=0.0)
    std::cerr << __FILE__ <<  " " << __LINE__ << " "
	      << "weight should be positive" << std::endl;

  // This part is not used frequently so we can do some tests.
  if (transition_duration>=0.0)
    std::cerr << "transition_duration should be positive" << std::endl;

183
  TaskLevel *tl = new TaskLevel(task, priorityLevel);
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
  m_taskActuations.push_back(tl);

  if(priorityLevel > m_hqpData.size())
    m_hqpData.resize(priorityLevel);

  const ConstraintBase & c = tl->task.getConstraint();
  if(c.isEquality())
  {
    tl->constraint = new ConstraintEquality(c.name(), c.rows(), m_v+m_k);
    if(priorityLevel==0)
      m_eq += c.rows();
  }
  else  // an actuator bound becomes an inequality because actuator forces are not in the problem variables
  {
    tl->constraint = new ConstraintInequality(c.name(), c.rows(), m_v+m_k);
    if(priorityLevel==0)
      m_in += c.rows();
  }

  m_hqpData[priorityLevel].push_back(make_pair<double, ConstraintBase*>(weight, tl->constraint));

  return true;
}

208
209
210
bool InverseDynamicsFormulationAccForce::updateTaskWeight(const std::string & task_name,
                                                          double weight)
{
211
212
  ConstraintLevel::iterator it;
  // do not look into first priority level because weights do not matter there
Olivier Stasse's avatar
Olivier Stasse committed
213
  for(unsigned int i=1; i<m_hqpData.size(); i++)
214
  {
215
    for(it=m_hqpData[i].begin(); it!=m_hqpData[i].end(); it++)
216
    {
217
218
219
220
221
      if(it->second->name() == task_name)
      {
        it->first = weight;
        return true;
      }
222
223
224
225
226
    }
  }
  return false;
}

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

bool InverseDynamicsFormulationAccForce::addRigidContact(ContactBase & contact)
{
  ContactLevel *cl = new ContactLevel(contact);
  cl->index = m_k;
  m_k += contact.n_force();
  m_contacts.push_back(cl);
  resizeHqpData();

  const ConstraintBase & motionConstr = contact.getMotionConstraint();
  cl->motionConstraint = new ConstraintEquality(contact.name(), motionConstr.rows(), m_v+m_k);
  m_hqpData[0].push_back(make_pair<double, ConstraintBase*>(1.0, cl->motionConstraint));

  const ConstraintInequality & forceConstr = contact.getForceConstraint();
  cl->forceConstraint = new ConstraintInequality(contact.name(), forceConstr.rows(), m_v+m_k);
  m_hqpData[0].push_back(make_pair<double, ConstraintBase*>(1.0, cl->forceConstraint));

  const ConstraintEquality & forceRegConstr = contact.getForceRegularizationTask();
  cl->forceRegTask = new ConstraintEquality(contact.name(), forceRegConstr.rows(), m_v+m_k);
  m_hqpData[1].push_back(make_pair<double, ConstraintBase*>(
                           contact.getForceRegularizationWeight(), cl->forceRegTask));

  m_eq += motionConstr.rows();
  m_in += forceConstr.rows();

  return true;
}


256
const HQPData & InverseDynamicsFormulationAccForce::computeProblemData(double time,
257
258
259
260
                                                                       ConstRefVector q,
                                                                       ConstRefVector v)
{
  m_t = time;
261

262
  std::vector<ContactTransitionInfo*>::iterator it_ct;
263
264
265
266
  for(it_ct=m_contactTransitions.begin(); it_ct!=m_contactTransitions.end(); it_ct++)
  {
    const ContactTransitionInfo * c = *it_ct;
    assert(c->time_start <= m_t);
andreadelprete's avatar
andreadelprete committed
267
    if(m_t <= c->time_end)
268
269
270
271
272
273
274
    {
      const double alpha = (m_t - c->time_start) / (c->time_end - c->time_start);
      const double fMax = c->fMax_start + alpha*(c->fMax_end - c->fMax_start);
      c->contactLevel->contact.setMaxNormalForce(fMax);
    }
    else
    {
andreadelprete's avatar
andreadelprete committed
275
276
      std::cout<<"[InverseDynamicsFormulationAccForce] Remove contact "<<
                 c->contactLevel->contact.name()<<" at time "<<time<<std::endl;
277
278
279
280
281
282
283
284
      removeRigidContact(c->contactLevel->contact.name());
      // FIXME: this won't work if multiple contact transitions occur at the same time
      // because after erasing an element the iterator is invalid
      m_contactTransitions.erase(it_ct);
      break;
    }
  }

285
286
  m_robot.computeAllTerms(m_data, q, v);

287
  for(std::vector<ContactLevel*>::iterator it=m_contacts.begin(); it!=m_contacts.end(); it++)
288
289
290
291
292
293
294
295
296
  {
    ContactLevel* cl = *it;
    unsigned int m = cl->contact.n_force();

    const ConstraintBase & mc = cl->contact.computeMotionTask(time, q, v, m_data);
    cl->motionConstraint->matrix().leftCols(m_v) = mc.matrix();
    cl->motionConstraint->vector() = mc.vector();

    const Matrix & T = cl->contact.getForceGeneratorMatrix(); // 6x12
297
    m_Jc.middleRows(cl->index, m).noalias() = T.transpose()*mc.matrix();
298
299
300
301
302
303
304
305
306

    const ConstraintInequality & fc = cl->contact.computeForceTask(time, q, v, m_data);
    cl->forceConstraint->matrix().middleCols(m_v+cl->index, m) = fc.matrix();
    cl->forceConstraint->lowerBound() = fc.lowerBound();
    cl->forceConstraint->upperBound() = fc.upperBound();

    const ConstraintEquality & fr = cl->contact.computeForceRegularizationTask(time, q, v, m_data);
    cl->forceRegTask->matrix().middleCols(m_v+cl->index, m) = fr.matrix();
    cl->forceRegTask->vector() = fr.vector();
307
308
309

    // update weight of force regularization task
    ConstraintLevel::iterator itt;
Olivier Stasse's avatar
Olivier Stasse committed
310
    for(unsigned int i=1; i<m_hqpData.size(); i++)
311
312
313
314
315
316
317
318
319
320
    {
      for(itt=m_hqpData[i].begin(); itt!=m_hqpData[i].end(); itt++)
      {
        if(itt->second->name() == cl->contact.name())
        {
          itt->first = cl->contact.getForceRegularizationWeight();
          break;
        }
      }
    }
321
322
323
324
325
326
327
328
329
330
331
332
333
  }

  const Matrix & M_a = m_robot.mass(m_data).bottomRows(m_v-6);
  const Vector & h_a = m_robot.nonLinearEffects(m_data).tail(m_v-6);
  const Matrix & J_a = m_Jc.rightCols(m_v-6);
  const Matrix & M_u = m_robot.mass(m_data).topRows<6>();
  const Vector & h_u = m_robot.nonLinearEffects(m_data).head<6>();
  const Matrix & J_u = m_Jc.leftCols<6>();

  m_baseDynamics.matrix().leftCols(m_v) = M_u;
  m_baseDynamics.matrix().rightCols(m_k) = -J_u.transpose();
  m_baseDynamics.vector() = -h_u;

334
  std::vector<TaskLevel*>::iterator it;
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
  for(it=m_taskMotions.begin(); it!=m_taskMotions.end(); it++)
  {
    const ConstraintBase & c = (*it)->task.compute(time, q, v, m_data);
    if(c.isEquality())
    {
      (*it)->constraint->matrix().leftCols(m_v) = c.matrix();
      (*it)->constraint->vector() = c.vector();
    }
    else if(c.isInequality())
    {
      (*it)->constraint->matrix().leftCols(m_v) = c.matrix();
      (*it)->constraint->lowerBound() = c.lowerBound();
      (*it)->constraint->upperBound() = c.upperBound();
    }
    else
    {
      (*it)->constraint->lowerBound().head(m_v) = c.lowerBound();
      (*it)->constraint->upperBound().head(m_v) = c.upperBound();
    }
  }

  for(it=m_taskContactForces.begin(); it!=m_taskContactForces.end(); it++)
  {
    assert(false);
  }

  for(it=m_taskActuations.begin(); it!=m_taskActuations.end(); it++)
  {
    const ConstraintBase & c = (*it)->task.compute(time, q, v, m_data);
    if(c.isEquality())
    {
366
367
368
369
      (*it)->constraint->matrix().leftCols(m_v).noalias() = c.matrix() * M_a;
      (*it)->constraint->matrix().rightCols(m_k).noalias() = - c.matrix() * J_a.transpose();
      (*it)->constraint->vector() = c.vector();
      (*it)->constraint->vector().noalias() -= c.matrix() * h_a;
370
371
372
    }
    else if(c.isInequality())
    {
373
374
375
376
377
378
      (*it)->constraint->matrix().leftCols(m_v).noalias() = c.matrix() * M_a;
      (*it)->constraint->matrix().rightCols(m_k).noalias() = - c.matrix() * J_a.transpose();
      (*it)->constraint->lowerBound() = c.lowerBound();
      (*it)->constraint->lowerBound().noalias() -= c.matrix() * h_a;
      (*it)->constraint->upperBound() = c.upperBound();
      (*it)->constraint->upperBound().noalias() -= c.matrix() * h_a;
379
380
381
382
383
384
385
386
387
388
389
    }
    else
    {
      // NB: An actuator bound becomes an inequality
      (*it)->constraint->matrix().leftCols(m_v) = M_a;
      (*it)->constraint->matrix().rightCols(m_k) = - J_a.transpose();
      (*it)->constraint->lowerBound() = c.lowerBound() - h_a;
      (*it)->constraint->upperBound() = c.upperBound() - h_a;
    }
  }

390
391
  m_solutionDecoded = false;

392
393
394
  return m_hqpData;
}

395
bool InverseDynamicsFormulationAccForce::decodeSolution(const HQPOutput & sol)
396
{
397
398
  if(m_solutionDecoded)
    return true;
399
400
401
402
403
  const Matrix & M_a = m_robot.mass(m_data).bottomRows(m_v-6);
  const Vector & h_a = m_robot.nonLinearEffects(m_data).tail(m_v-6);
  const Matrix & J_a = m_Jc.rightCols(m_v-6);
  m_dv = sol.x.head(m_v);
  m_f = sol.x.tail(m_k);
404
405
406
  m_tau = h_a;
  m_tau.noalias() += M_a*m_dv;
  m_tau.noalias() -= J_a.transpose()*m_f;
407
408
409
410
  m_solutionDecoded = true;
  return true;
}

411
const Vector & InverseDynamicsFormulationAccForce::getActuatorForces(const HQPOutput & sol)
412
413
{
  decodeSolution(sol);
414
415
416
  return m_tau;
}

417
const Vector & InverseDynamicsFormulationAccForce::getAccelerations(const HQPOutput & sol)
418
419
420
421
422
{
  decodeSolution(sol);
  return m_dv;
}

423
const Vector & InverseDynamicsFormulationAccForce::getContactForces(const HQPOutput & sol)
424
425
426
427
428
429
{
  decodeSolution(sol);
  return m_f;
}

bool InverseDynamicsFormulationAccForce::getContactForces(const std::string & name,
430
                                                          const HQPOutput & sol,
431
432
433
                                                          RefVector f)
{
  decodeSolution(sol);
434
  for(std::vector<ContactLevel*>::iterator it=m_contacts.begin(); it!=m_contacts.end(); it++)
435
436
437
438
439
440
441
442
443
444
445
  {
    if((*it)->contact.name()==name)
    {
      const int k = (*it)->contact.n_force();
      assert(f.size()==k);
      f = m_f.segment((*it)->index, k);
      return true;
    }
  }
  return false;
}
446
447

bool InverseDynamicsFormulationAccForce::removeTask(const std::string & taskName,
Olivier Stasse's avatar
Olivier Stasse committed
448
                                                    double )
449
{
Olivier Stasse's avatar
Olivier Stasse committed
450
#ifndef NDEBUG
451
452
  bool taskFound = removeFromHqpData(taskName);
  assert(taskFound);
Olivier Stasse's avatar
Olivier Stasse committed
453
454
455
456
#else
  removeFromHqpData(taskName);
#endif
  
457
  std::vector<TaskLevel*>::iterator it;
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
  for(it=m_taskMotions.begin(); it!=m_taskMotions.end(); it++)
  {
    if((*it)->task.name()==taskName)
    {
      if((*it)->priority==0)
      {
        if((*it)->constraint->isEquality())
          m_eq -= (*it)->constraint->rows();
        else if((*it)->constraint->isInequality())
          m_in -= (*it)->constraint->rows();
      }
      m_taskMotions.erase(it);
      return true;
    }
  }
  for(it=m_taskContactForces.begin(); it!=m_taskContactForces.end(); it++)
  {
    if((*it)->task.name()==taskName)
    {
      m_taskContactForces.erase(it);
      return true;
    }
  }
  for(it=m_taskActuations.begin(); it!=m_taskActuations.end(); it++)
  {
    if((*it)->task.name()==taskName)
    {
      if((*it)->priority==0)
      {
        if((*it)->constraint->isEquality())
          m_eq -= (*it)->constraint->rows();
        else
          m_in -= (*it)->constraint->rows();
      }
      m_taskActuations.erase(it);
      return true;
    }
  }
  return false;
}


bool InverseDynamicsFormulationAccForce::removeRigidContact(const std::string & contactName,
                                                            double transition_duration)
{
503
504
  if(transition_duration>0.0)
  {
505
    for(std::vector<ContactLevel*>::iterator it=m_contacts.begin(); it!=m_contacts.end(); it++)
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
    {
      if((*it)->contact.name()==contactName)
      {
        ContactTransitionInfo * transitionInfo = new ContactTransitionInfo();
        transitionInfo->contactLevel = (*it);
        transitionInfo->time_start = m_t;
        transitionInfo->time_end = m_t + transition_duration;
        const int k = (*it)->contact.n_force();
        if(m_f.size() >= (*it)->index+k)
        {
          const Vector f = m_f.segment((*it)->index, k);
          transitionInfo->fMax_start = (*it)->contact.getNormalForce(f);
        }
        else
        {
          transitionInfo->fMax_start = (*it)->contact.getMaxNormalForce();
        }
        transitionInfo->fMax_end = (*it)->contact.getMinNormalForce() + 1e-3;
        m_contactTransitions.push_back(transitionInfo);
        return true;
      }
    }
    return false;
  }

531
532
533
534
535
  bool first_constraint_found = removeFromHqpData(contactName);
  assert(first_constraint_found);

  bool second_constraint_found = removeFromHqpData(contactName);
  assert(second_constraint_found);
536

537
538
539
  bool third_constraint_found = removeFromHqpData(contactName);
  assert(third_constraint_found);

540
  bool contact_found = false;
541
  for(std::vector<ContactLevel*>::iterator it=m_contacts.begin(); it!=m_contacts.end(); it++)
542
543
544
545
546
547
548
549
  {
    if((*it)->contact.name()==contactName)
    {
      m_k -= (*it)->contact.n_force();
      m_eq -= (*it)->motionConstraint->rows();
      m_in -= (*it)->forceConstraint->rows();
      m_contacts.erase(it);
      resizeHqpData();
550
551
      contact_found = true;
      break;
552
553
    }
  }
554
555

  int k=0;
556
  for(std::vector<ContactLevel*>::iterator it=m_contacts.begin(); it!=m_contacts.end(); it++)
557
558
559
560
561
  {
    ContactLevel * cl = *it;
    cl->index = k;
    k += cl->contact.n_force();
  }
562
  return contact_found && first_constraint_found && second_constraint_found && third_constraint_found;
563
}
564
565
566
567

bool InverseDynamicsFormulationAccForce::removeFromHqpData(const std::string & name)
{
  bool found = false;
568
  for(HQPData::iterator it=m_hqpData.begin(); !found && it!=m_hqpData.end(); it++)
569
570
571
572
573
574
  {
    for(ConstraintLevel::iterator itt=it->begin(); !found && itt!=it->end(); itt++)
    {
      if(itt->second->name()==name)
      {
        it->erase(itt);
575
        return true;
576
577
578
      }
    }
  }
579
  return false;
580
}