File: HumanLegJointLimitConstraint.cpp

package info (click to toggle)
dart 6.13.2%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 56,948 kB
  • sloc: cpp: 274,310; python: 3,973; xml: 1,272; sh: 404; makefile: 31
file content (458 lines) | stat: -rw-r--r-- 14,141 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
86
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * Copyright (c) 2011-2018, The DART development contributors
 * All rights reserved.
 *
 * The list of contributors can be found at:
 *   https://github.com/dartsim/dart/blob/master/LICENSE
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "HumanLegJointLimitConstraint.hpp"

#include <iostream>

#include <dart/external/odelcpsolver/lcp.h>

#include <dart/common/Console.hpp>
#include <dart/dynamics/BodyNode.hpp>
#include <dart/dynamics/Joint.hpp>
#include <dart/dynamics/Skeleton.hpp>

#define DART_ERROR_ALLOWANCE 0.0
#define DART_ERP 0.01
#define DART_MAX_ERV 1e+1
#define DART_CFM 1e-9

using namespace dart;
using namespace tiny_dnn;
using namespace tiny_dnn::activation;
using namespace tiny_dnn::layers;

double HumanLegJointLimitConstraint::mErrorAllowance = DART_ERROR_ALLOWANCE;
double HumanLegJointLimitConstraint::mErrorReductionParameter = DART_ERP;
double HumanLegJointLimitConstraint::mMaxErrorReductionVelocity = DART_MAX_ERV;
double HumanLegJointLimitConstraint::mConstraintForceMixing = DART_CFM;

//==============================================================================
HumanLegJointLimitConstraint::HumanLegJointLimitConstraint(
    dynamics::Joint* hipjoint,
    dynamics::Joint* _kneejoint,
    dynamics::Joint* _anklejoint,
    bool isMirror)
  : ConstraintBase(),
    mHipJoint(hipjoint),
    mKneeJoint(_kneejoint),
    mAnkleJoint(_anklejoint),
    mThighNode(hipjoint->getChildBodyNode()),
    mLowerLegNode(_kneejoint->getChildBodyNode()),
    mFootNode(_anklejoint->getChildBodyNode()),
    mIsMirror(isMirror),
    mAppliedImpulseIndex(0)
{
  assert(mHipJoint);
  assert(mKneeJoint);
  assert(mAnkleJoint);
  assert(mThighNode);
  assert(mLowerLegNode);
  assert(mFootNode);

  assert(mHipJoint->getNumDofs() == 3);
  assert(mKneeJoint->getNumDofs() == 1);
  assert(mAnkleJoint->getNumDofs() == 2);

  assert(mThighNode->getSkeleton() == mLowerLegNode->getSkeleton());
  assert(mLowerLegNode->getSkeleton() == mFootNode->getSkeleton());
  assert(mKneeJoint->getParentBodyNode() == mThighNode);
  assert(mAnkleJoint->getParentBodyNode() == mLowerLegNode);

  mLifeTime = 0;
  mActive = false;

  // load neural net weights from external file
  mNet.load(DART_DATA_PATH "/humanJointLimits/neuralnets/net-lleg");
}

//==============================================================================
void HumanLegJointLimitConstraint::setErrorAllowance(double allowance)
{
  // Clamp error reduction parameter if it is out of the range
  if (allowance < 0.0)
  {
    dtwarn << "Error reduction parameter[" << allowance
           << "] is lower than 0.0. "
           << "It is set to 0.0." << std::endl;
    mErrorAllowance = 0.0;
  }

  mErrorAllowance = allowance;
}

//==============================================================================
double HumanLegJointLimitConstraint::getErrorAllowance()
{
  return mErrorAllowance;
}

//==============================================================================
void HumanLegJointLimitConstraint::setErrorReductionParameter(double erp)
{
  // Clamp error reduction parameter if it is out of the range [0, 1]
  if (erp < 0.0)
  {
    dtwarn << "Error reduction parameter[" << erp << "] is lower than 0.0. "
           << "It is set to 0.0." << std::endl;
    mErrorReductionParameter = 0.0;
  }
  if (erp > 1.0)
  {
    dtwarn << "Error reduction parameter[" << erp << "] is greater than 1.0. "
           << "It is set to 1.0." << std::endl;
    mErrorReductionParameter = 1.0;
  }

  mErrorReductionParameter = erp;
}

//==============================================================================
double HumanLegJointLimitConstraint::getErrorReductionParameter()
{
  return mErrorReductionParameter;
}

//==============================================================================
void HumanLegJointLimitConstraint::setMaxErrorReductionVelocity(double erv)
{
  // Clamp maximum error reduction velocity if it is out of the range
  if (erv < 0.0)
  {
    dtwarn << "Maximum error reduction velocity[" << erv
           << "] is lower than 0.0. "
           << "It is set to 0.0." << std::endl;
    mMaxErrorReductionVelocity = 0.0;
  }

  mMaxErrorReductionVelocity = erv;
}

//==============================================================================
double HumanLegJointLimitConstraint::getMaxErrorReductionVelocity()
{
  return mMaxErrorReductionVelocity;
}

//==============================================================================
void HumanLegJointLimitConstraint::setConstraintForceMixing(double cfm)
{
  // Clamp constraint force mixing parameter if it is out of the range
  if (cfm < 1e-9)
  {
    dtwarn << "Constraint force mixing parameter[" << cfm
           << "] is lower than 1e-9. "
           << "It is set to 1e-9." << std::endl;
    mConstraintForceMixing = 1e-9;
  }
  if (cfm > 1.0)
  {
    dtwarn << "Constraint force mixing parameter[" << cfm
           << "] is greater than 1.0. "
           << "It is set to 1.0." << std::endl;
    mConstraintForceMixing = 1.0;
  }

  mConstraintForceMixing = cfm;
}

//==============================================================================
double HumanLegJointLimitConstraint::getConstraintForceMixing()
{
  return mConstraintForceMixing;
}

//==============================================================================
void HumanLegJointLimitConstraint::update()
{
  const auto pi2 = math::constantsd::two_pi();

  double qz = mHipJoint->getPosition(0);
  double qx = mHipJoint->getPosition(1);
  double qy = mHipJoint->getPosition(2);
  double qe = mKneeJoint->getPosition(0);
  double hx = mAnkleJoint->getPosition(0);
  double hy = mAnkleJoint->getPosition(1);

  double qz_d = mHipJoint->getVelocity(0);
  double qx_d = mHipJoint->getVelocity(1);
  double qy_d = mHipJoint->getVelocity(2);
  double qe_d = mKneeJoint->getVelocity(0);
  double hx_d = mAnkleJoint->getVelocity(0);
  double hy_d = mAnkleJoint->getVelocity(1);

  // if isMirror (right-lrg), set up a mirrored euler joint for hip
  // i.e. pass the mirrored config to NN
  if (mIsMirror)
  {
    qz = -qz;
    qy = -qy;
  }

  double qsin[8] = {cos(qz),
                    sin(qz),
                    cos(qx),
                    sin(qx),
                    cos(qy + pi2),
                    cos(qe),
                    cos(hx + pi2),
                    cos(hy + pi2)};
  vec_t input;
  input.assign(qsin, qsin + 8);
  vec_t pred_vec = mNet.predict(input);
  double C = *(pred_vec.begin());

  mViolation = C - 0.5;

  // if not active, no variable matters, no need to update
  mActive = false;
  mDim = 0;

  // active: mViolation <= 0 (C(q)-0.5<=0)
  if (mViolation <= 0.0)
  {
    if (mActive)
    {
      ++mLifeTime;
    }
    else
    {
      mActive = true;
      mLifeTime = 0;
    }

    // do back-propogation to obtain gradient
    layer* l;
    vec_t out_grad = {1};
    vec_t in_grad;
    for (int n = mNet.layer_size() - 1; n >= 0; n--)
    {
      // implement chain rule layer by layer
      l = mNet[n];
      if (l->layer_type() == "fully-connected")
      {
        auto Wb = l->weights();
        vec_t W = *(Wb[0]);
        in_grad.assign(W.size() / out_grad.size(), 0);
        for (size_t c = 0; c < in_grad.size(); c++)
        {
          in_grad[c] = vectorize::dot(
              &out_grad[0], &W[c * out_grad.size()], out_grad.size());
        }
      }
      else
      {
        // this is activation layer
        std::vector<const tensor_t*> out_t;
        l->output(out_t);
        vec_t out_v = (*(out_t[0]))[0];

        in_grad.assign(out_grad.begin(), out_grad.end());
        // first arg (x) is used only to infer the size of input, which should
        // be the same as output y
        (dynamic_cast<activation_layer*>(l))
            ->backward_activation(out_v, out_v, in_grad, out_grad);
      }
      out_grad.assign(in_grad.begin(), in_grad.end());
      in_grad.clear();
    }

    mJacobian[0] = out_grad[0] * (-sin(qz)) + out_grad[1] * (cos(qz));
    mJacobian[1] = out_grad[2] * (-sin(qx)) + out_grad[3] * (cos(qx));
    mJacobian[2] = out_grad[4] * (-sin(qy + pi2));
    mJacobian[3] = out_grad[5] * (-sin(qe));
    mJacobian[4] = out_grad[6] * (-sin(hx + pi2));
    mJacobian[5] = out_grad[7] * (-sin(hy + pi2));

    // note that we also need to take the mirror of the NN gradient for
    // right-leg
    if (mIsMirror)
    {
      mJacobian[0] = -mJacobian[0];
      mJacobian[2] = -mJacobian[2];
    }

    // TODO: Normalize grad seems unnecessary?

    Eigen::Vector6d q_d;
    q_d << qz_d, qx_d, qy_d, qe_d, hx_d, hy_d;
    mNegativeVel = -mJacobian.dot(q_d);

    mLowerBound = 0.0;
    mUpperBound = dInfinity;
    mDim = 1;
  }
}

//==============================================================================
void HumanLegJointLimitConstraint::getInformation(
    constraint::ConstraintInfo* lcp)
{
  // if non-active, should not call getInfo()
  assert(isActive());

  // assume caller will allocate enough space for _lcp variables
  assert(lcp->w[0] == 0.0);
  assert(lcp->findex[0] == -1);

  double bouncingVel = -mViolation - mErrorAllowance;
  if (bouncingVel < 0.0)
  {
    bouncingVel = 0.0;
  }
  bouncingVel *= lcp->invTimeStep * mErrorReductionParameter;
  if (bouncingVel > mMaxErrorReductionVelocity)
    bouncingVel = mMaxErrorReductionVelocity;

  lcp->b[0] = mNegativeVel + bouncingVel;
  lcp->lo[0] = mLowerBound;
  lcp->hi[0] = mUpperBound;

  if (mLifeTime)
    lcp->x[0] = mOldX;
  else
    lcp->x[0] = 0.0;
}

//==============================================================================
void HumanLegJointLimitConstraint::applyUnitImpulse(std::size_t index)
{
  // the dim of constraint = 1, valid _index can only be 0
  assert(index < mDim && "Invalid Index.");
  assert(isActive());

  const dynamics::SkeletonPtr& skeleton = mHipJoint->getSkeleton();
  skeleton->clearConstraintImpulses();

  for (std::size_t i = 0; i < 3; i++)
  {
    mHipJoint->setConstraintImpulse(i, mJacobian[i]);
  }
  mKneeJoint->setConstraintImpulse(0, mJacobian[3]);
  for (std::size_t i = 0; i < 2; i++)
  {
    mAnkleJoint->setConstraintImpulse(i, mJacobian[4 + i]);
  }

  // Use the body which is placed later in the list of body nodes in this
  // skeleton
  skeleton->updateBiasImpulse(mFootNode);
  skeleton->updateVelocityChange();

  for (std::size_t i = 0; i < 3; i++)
  {
    mHipJoint->setConstraintImpulse(i, 0.0);
  }
  mKneeJoint->setConstraintImpulse(0, 0.0);
  for (std::size_t i = 0; i < 2; i++)
  {
    mAnkleJoint->setConstraintImpulse(i, 0.0);
  }

  mAppliedImpulseIndex = index; // which is 0
}

//==============================================================================
void HumanLegJointLimitConstraint::getVelocityChange(
    double* delVel, bool withCfm)
{
  assert(delVel != nullptr && "Null pointer is not allowed.");
  delVel[0] = 0.0;

  if (mHipJoint->getSkeleton()->isImpulseApplied())
  {
    Eigen::Vector6d delq_d;
    for (std::size_t i = 0; i < 3; i++)
    {
      delq_d[i] = mHipJoint->getVelocityChange(i);
    }
    delq_d[3] = mKneeJoint->getVelocityChange(0);
    for (std::size_t i = 0; i < 2; i++)
    {
      delq_d[4 + i] = mAnkleJoint->getVelocityChange(i);
    }
    delVel[0] = mJacobian.dot(delq_d);
  }

  if (withCfm)
  {
    delVel[mAppliedImpulseIndex]
        += delVel[mAppliedImpulseIndex] * mConstraintForceMixing;
  }
}

//==============================================================================
void HumanLegJointLimitConstraint::excite()
{
  mHipJoint->getSkeleton()->setImpulseApplied(true);
}

//==============================================================================
void HumanLegJointLimitConstraint::unexcite()
{
  mHipJoint->getSkeleton()->setImpulseApplied(false);
}

//==============================================================================
void HumanLegJointLimitConstraint::applyImpulse(double* lambda)
{
  assert(isActive());

  // the dim of constraint = 1
  auto con_force = lambda[0];
  mOldX = con_force;

  for (std::size_t i = 0; i < 3; i++)
  {
    mHipJoint->setConstraintImpulse(
        i, mHipJoint->getConstraintImpulse(i) + mJacobian[i] * con_force);
  }
  mKneeJoint->setConstraintImpulse(
      0, mKneeJoint->getConstraintImpulse(0) + mJacobian[3] * con_force);
  for (std::size_t i = 0; i < 2; i++)
  {
    mAnkleJoint->setConstraintImpulse(
        i, mAnkleJoint->getConstraintImpulse(i) + mJacobian[4 + i] * con_force);
  }
}

//==============================================================================
dynamics::SkeletonPtr HumanLegJointLimitConstraint::getRootSkeleton() const
{
  return mHipJoint->getSkeleton()->mUnionRootSkeleton.lock();
}

//==============================================================================
bool HumanLegJointLimitConstraint::isActive() const
{
  return mActive;
}