-
Notifications
You must be signed in to change notification settings - Fork 14
/
ScrewTheoryIkProblemBuilder.cpp
639 lines (526 loc) · 20 KB
/
ScrewTheoryIkProblemBuilder.cpp
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
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
503
504
505
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#include "ScrewTheoryIkProblem.hpp"
#include <algorithm> // std::copy, std::count_if, std::find_if
#include <iterator> // std::advance, std::distance
#include <set>
#include <vector>
#include "ScrewTheoryIkSubproblems.hpp"
using namespace roboticslab;
// -----------------------------------------------------------------------------
namespace
{
inline bool liesOnAxis(const MatrixExponential & exp, const KDL::Vector & p)
{
return KDL::Equal((p - exp.getOrigin()) * exp.getAxis(), KDL::Vector::Zero());
}
inline bool parallelAxes(const MatrixExponential & exp1, const MatrixExponential & exp2)
{
return KDL::Equal(exp1.getAxis() * exp2.getAxis(), KDL::Vector::Zero());
}
inline bool perpendicularAxes(const MatrixExponential & exp1, const MatrixExponential & exp2)
{
return KDL::Equal(KDL::dot(exp1.getAxis(), exp2.getAxis()), 0);
}
inline bool colinearAxes(const MatrixExponential & exp1, const MatrixExponential & exp2)
{
return parallelAxes(exp1, exp2) && liesOnAxis(exp1, exp2.getOrigin());
}
bool intersectingAxes(const MatrixExponential & exp1, const MatrixExponential & exp2, KDL::Vector & p)
{
// "Intersection of Two Lines in Three-Space" by Ronald Goldman, University of Waterloo (Waterloo, Ontario, Canada)
// published in: "Graphic Gems", edited by Andrew S. Glassner, 1 ed., ch. 5, "3D Geometry" (p. 304)
// referenced in: https://stackoverflow.com/a/565282
KDL::Vector cross = exp1.getAxis() * exp2.getAxis();
KDL::Vector diff = exp2.getOrigin() - exp1.getOrigin();
double den = KDL::pow(cross.Norm(), 2);
double t = KDL::dot(cross, diff * exp2.getAxis()) / den;
double s = KDL::dot(cross, diff * exp1.getAxis()) / den;
KDL::Vector L1 = exp1.getOrigin() + exp1.getAxis() * t;
KDL::Vector L2 = exp2.getOrigin() + exp2.getAxis() * s;
p = L1;
return KDL::Equal(L1, L2);
}
inline bool planarMovement(const MatrixExponential & exp1, const MatrixExponential & exp2)
{
bool sameMotionType = exp1.getMotionType() == exp2.getMotionType();
return sameMotionType ? parallelAxes(exp1, exp2) : perpendicularAxes(exp1, exp2);
}
inline bool normalPlaneMovement(const MatrixExponential & exp1, const MatrixExponential & exp2)
{
bool sameMotionType = exp1.getMotionType() == exp2.getMotionType();
return sameMotionType ? perpendicularAxes(exp1, exp2) : parallelAxes(exp1, exp2);
}
struct compare_vectors
{
bool operator()(const KDL::Vector & lhs, const KDL::Vector & rhs) const
{
if (KDL::Equal(lhs.x(), rhs.x()))
{
if (KDL::Equal(lhs.y(), rhs.y()))
{
if (KDL::Equal(lhs.z(), rhs.z()))
{
// treat as equal per !comp(a, b) && !comp(b, a) == true
// https://en.cppreference.com/w/cpp/container/set
return false;
}
else if (lhs.z() < rhs.z())
{
return true;
}
}
else if (lhs.y() < rhs.y())
{
return true;
}
}
else if (lhs.x() < rhs.x())
{
return true;
}
return false;
}
};
class poe_term_candidate
{
public:
poe_term_candidate(bool _expectedKnown)
: expectedKnown(_expectedKnown),
expectedSimplified(false),
ignoreSimplifiedState(true)
{}
poe_term_candidate(bool _expectedKnown, bool _expectedSimplified)
: expectedKnown(_expectedKnown),
expectedSimplified(_expectedSimplified),
ignoreSimplifiedState(false)
{}
bool operator()(const ScrewTheoryIkProblemBuilder::PoeTerm & poeTerm)
{
return poeTerm.known == expectedKnown && (ignoreSimplifiedState || poeTerm.simplified == expectedSimplified);
}
private:
bool expectedKnown, expectedSimplified, ignoreSimplifiedState;
};
// Can't inline into previous definition, Doxygen output is messed up by the first variable.
poe_term_candidate knownTerm(true), unknownTerm(false), knownNotSimplifiedTerm(true, false), unknownNotSimplifiedTerm(false, false);
void clearSteps(ScrewTheoryIkProblem::Steps & steps)
{
for (auto it = steps.begin(); it != steps.end(); ++it)
{
delete (*it);
}
steps.clear();
}
}
// -----------------------------------------------------------------------------
ScrewTheoryIkProblemBuilder::ScrewTheoryIkProblemBuilder(const PoeExpression & _poe)
: poe(_poe),
poeTerms(poe.size())
{}
// -----------------------------------------------------------------------------
std::vector<KDL::Vector> ScrewTheoryIkProblemBuilder::searchPoints(const PoeExpression & poe)
{
std::set<KDL::Vector, compare_vectors> set;
// Add origin.
set.insert(KDL::Vector::Zero());
for (int i = 0; i < poe.size(); i++)
{
const MatrixExponential & exp = poe.exponentialAtJoint(i);
if (exp.getMotionType() != MatrixExponential::ROTATION)
{
continue;
}
// Add some point of this axis.
set.insert(exp.getOrigin());
// Find intersection between axes.
for (int j = 1; j < poe.size(); j++)
{
const MatrixExponential & exp2 = poe.exponentialAtJoint(j);
if (exp2.getMotionType() != MatrixExponential::ROTATION)
{
continue;
}
if (parallelAxes(exp, exp2))
{
continue;
}
if (colinearAxes(exp, exp2))
{
continue;
}
KDL::Vector p;
if (intersectingAxes(exp, exp2, p))
{
set.insert(p);
}
}
}
// Find one additional random point on each axis.
for (int i = 0; i < poe.size(); i++)
{
const MatrixExponential & exp = poe.exponentialAtJoint(i);
if (exp.getMotionType() != MatrixExponential::ROTATION)
{
continue;
}
double factor;
KDL::Vector randomPointOnAxis;
do
{
KDL::random(factor);
randomPointOnAxis = exp.getOrigin() + factor * exp.getAxis();
}
while (!set.insert(randomPointOnAxis).second);
}
// Add TCP.
set.insert(poe.getTransform().p);
std::vector<KDL::Vector> points(set.size());
std::copy(set.begin(), set.end(), points.begin());
return points;
}
// -----------------------------------------------------------------------------
ScrewTheoryIkProblem * ScrewTheoryIkProblemBuilder::build()
{
// Reset state, mark all PoE terms as unknown.
for (auto it = poeTerms.begin(); it != poeTerms.end(); ++it)
{
it->known = false;
}
// Find solutions, if available.
ScrewTheoryIkProblem::Steps steps = searchSolutions();
if (std::count_if(poeTerms.begin(), poeTerms.end(), knownTerm) == poe.size())
{
// Instantiate solver class.
return ScrewTheoryIkProblem::create(poe, steps);
}
else
{
// Free memory allocations.
clearSteps(steps);
}
// No solution found, try with reversed PoE.
poe.reverseSelf();
for (auto it = poeTerms.begin(); it != poeTerms.end(); ++it)
{
it->known = false;
}
steps = searchSolutions();
if (std::count_if(poeTerms.begin(), poeTerms.end(), knownTerm) == poe.size())
{
return ScrewTheoryIkProblem::create(poe, steps, true);
}
else
{
clearSteps(steps);
}
return nullptr;
}
// -----------------------------------------------------------------------------
ScrewTheoryIkProblem::Steps ScrewTheoryIkProblemBuilder::searchSolutions()
{
points = searchPoints(poe);
// Shared collection of characteristic points to work with.
testPoints.assign(MAX_SIMPLIFICATION_DEPTH, points[0]);
ScrewTheoryIkProblem::Steps steps;
// Vector of iterators (for iterating more than once over the same collection).
// Size is number of characteristic points being considered at once.
std::vector<std::vector<KDL::Vector>::const_iterator> iterators(MAX_SIMPLIFICATION_DEPTH, points.begin());
// 0: try one point, 1: try two points simultaneously, and so on...
int depth = 0;
do
{
// Start over.
refreshSimplificationState();
// For the current set of characteristic points, try to simplify the PoE.
simplify(depth);
// Find a solution if available.
if (auto * subproblem = trySolve(depth))
{
// Solution found, reset and start again. We'll iterate over the same points, taking
// into account that some terms are already known.
steps.push_back(subproblem);
iterators.assign(iterators.size(), points.begin());
testPoints[0] = points[0];
depth = 0;
continue;
}
// Advance iterators at each stage (first point, second point (if used), ...).
for (int stage = 0; stage < iterators.size(); stage++)
{
++iterators[stage];
if (iterators[stage] == points.end())
{
// We've tried all points for this stage, reset and pick first point again.
iterators[stage] = points.begin();
testPoints[stage] = *iterators[stage];
if (stage == depth)
{
// We are ready to try another point simultaneously, increase "depth" level.
depth++;
break;
}
}
else
{
// Still more points available, quit from here and proceed once more with the outer loop.
testPoints[stage] = *iterators[stage];
break;
}
}
}
// Stop if we can't test more points or all terms are known (solution found).
while (depth < MAX_SIMPLIFICATION_DEPTH && std::count_if(poeTerms.begin(), poeTerms.end(), unknownTerm) != 0);
return steps;
}
// -----------------------------------------------------------------------------
void ScrewTheoryIkProblemBuilder::refreshSimplificationState()
{
// Reset simplification mark on all terms.
for (auto it = poeTerms.begin(); it != poeTerms.end(); ++it)
{
it->simplified = false;
}
// Leading known terms can be simplified (pre-multiply).
for (auto it = poeTerms.begin(); it != poeTerms.end(); ++it)
{
if (it->known)
{
it->simplified = true;
}
else
{
break;
}
}
// Trailing known terms can be simplified as well (post-multiply).
for (auto rit = poeTerms.rbegin(); rit != poeTerms.rend(); ++rit)
{
if (rit->known)
{
rit->simplified = true;
}
else
{
break;
}
}
}
// -----------------------------------------------------------------------------
ScrewTheoryIkSubproblem * ScrewTheoryIkProblemBuilder::trySolve(int depth)
{
int unknownsCount = std::count_if(poeTerms.begin(), poeTerms.end(), unknownNotSimplifiedTerm);
if (unknownsCount == 0 || unknownsCount > 2) // TODO: hardcoded
{
// Can't solve yet, too many unknowns or oversimplified.
return nullptr;
}
// Find rightmost unknown and not simplified PoE term.
auto lastUnknown = std::find_if(poeTerms.rbegin(), poeTerms.rend(), unknownNotSimplifiedTerm);
int lastExpId = std::distance(poeTerms.begin(), lastUnknown.base()) - 1;
const MatrixExponential & lastExp = poe.exponentialAtJoint(lastExpId);
// Select the most adequate subproblem, if available.
if (unknownsCount == 1)
{
if (depth == 0)
{
if (lastExp.getMotionType() == MatrixExponential::ROTATION
&& !liesOnAxis(lastExp, testPoints[0]))
{
poeTerms[lastExpId].known = true;
return new PadenKahanOne(lastExpId, lastExp, testPoints[0]);
}
if (lastExp.getMotionType() == MatrixExponential::TRANSLATION)
{
poeTerms[lastExpId].known = true;
return new PardosGotorOne(lastExpId, lastExp, testPoints[0]);
}
}
if (depth == 1)
{
// There can be no other non-simplified terms to the left of our unknown.
if (std::find_if(poeTerms.begin(), poeTerms.end(), knownNotSimplifiedTerm) != poeTerms.end())
{
return nullptr;
}
if (lastExp.getMotionType() == MatrixExponential::ROTATION
&& !liesOnAxis(lastExp, testPoints[0])
&& !liesOnAxis(lastExp, testPoints[1]))
{
poeTerms[lastExpId].known = true;
return new PadenKahanThree(lastExpId, lastExp, testPoints[0], testPoints[1]);
}
if (lastExp.getMotionType() == MatrixExponential::TRANSLATION)
{
poeTerms[lastExpId].known = true;
return new PardosGotorThree(lastExpId, lastExp, testPoints[0], testPoints[1]);
}
}
}
else if (unknownsCount == 2 && lastUnknown != poeTerms.rend())
{
// Pick the previous PoE term.
auto nextToLastUnknown = lastUnknown;
std::advance(nextToLastUnknown, 1);
if (!unknownNotSimplifiedTerm(*nextToLastUnknown))
{
return nullptr;
}
int nextToLastExpId = lastExpId - 1;
const MatrixExponential & nextToLastExp = poe.exponentialAtJoint(nextToLastExpId);
if (depth == 0)
{
KDL::Vector r;
if (lastExp.getMotionType() == MatrixExponential::ROTATION
&& nextToLastExp.getMotionType() == MatrixExponential::ROTATION
&& !parallelAxes(lastExp, nextToLastExp)
&& intersectingAxes(lastExp, nextToLastExp, r))
{
poeTerms[lastExpId].known = poeTerms[nextToLastExpId].known = true;
return new PadenKahanTwo(nextToLastExpId, lastExpId, nextToLastExp, lastExp, testPoints[0], r);
}
if (lastExp.getMotionType() == MatrixExponential::TRANSLATION
&& nextToLastExp.getMotionType() == MatrixExponential::TRANSLATION
&& !parallelAxes(lastExp, nextToLastExp))
{
poeTerms[lastExpId].known = poeTerms[nextToLastExpId].known = true;
return new PardosGotorTwo(nextToLastExpId, lastExpId, nextToLastExp, lastExp, testPoints[0]);
}
if (lastExp.getMotionType() == MatrixExponential::ROTATION
&& nextToLastExp.getMotionType() == MatrixExponential::ROTATION
&& parallelAxes(lastExp, nextToLastExp)
&& !colinearAxes(lastExp, nextToLastExp))
{
poeTerms[lastExpId].known = poeTerms[nextToLastExpId].known = true;
return new PardosGotorFour(nextToLastExpId, lastExpId, nextToLastExp, lastExp, testPoints[0]);
}
}
}
return nullptr;
}
// -----------------------------------------------------------------------------
void ScrewTheoryIkProblemBuilder::simplify(int depth)
{
simplifyWithPadenKahanOne(testPoints[0]);
if (depth == 1)
{
simplifyWithPadenKahanThree(testPoints[1]);
}
else
{
for (int i = 0; i < poe.size(); i++)
{
if (poe.exponentialAtJoint(i).getMotionType() == MatrixExponential::TRANSLATION)
{
simplifyWithPardosOne();
break;
}
}
}
}
// -----------------------------------------------------------------------------
void ScrewTheoryIkProblemBuilder::simplifyWithPadenKahanOne(const KDL::Vector & point)
{
// Pick first rightmost unknown PoE term.
auto ritUnknown = std::find_if(poeTerms.rbegin(), poeTerms.rend(), unknownTerm);
for (auto rit = ritUnknown; rit != poeTerms.rend(); ++rit)
{
int i = std::distance(rit, poeTerms.rend()) - 1;
const MatrixExponential & exp = poe.exponentialAtJoint(i);
if (exp.getMotionType() == MatrixExponential::ROTATION && liesOnAxis(exp, point))
{
rit->simplified = true;
}
else
{
break;
}
}
}
// -----------------------------------------------------------------------------
void ScrewTheoryIkProblemBuilder::simplifyWithPadenKahanThree(const KDL::Vector & point)
{
// Pick first leftmost unknown PoE term.
auto itUnknown = std::find_if(poeTerms.begin(), poeTerms.end(), unknownTerm);
for (auto it = itUnknown; it != poeTerms.end(); ++it)
{
int i = std::distance(poeTerms.begin(), it);
const MatrixExponential & exp = poe.exponentialAtJoint(i);
if (exp.getMotionType() == MatrixExponential::ROTATION && liesOnAxis(exp, point))
{
it->simplified = true;
}
else
{
break;
}
}
}
// -----------------------------------------------------------------------------
void ScrewTheoryIkProblemBuilder::simplifyWithPardosOne()
{
// Pick first leftmost and rightmost unknown PoE terms.
auto itUnknown = std::find_if(poeTerms.begin(), poeTerms.end(), unknownNotSimplifiedTerm);
auto ritUnknown = std::find_if(poeTerms.rbegin(), poeTerms.rend(), unknownNotSimplifiedTerm);
int idStart = std::distance(poeTerms.begin(), itUnknown);
int idEnd = std::distance(ritUnknown, poeTerms.rend()) - 1;
if (idStart >= idEnd)
{
// Same term or something went wrong (all terms have been already simplified).
return;
}
const MatrixExponential & firstExp = poe.exponentialAtJoint(idStart);
const MatrixExponential & lastExp = poe.exponentialAtJoint(idEnd);
if (firstExp.getMotionType() == MatrixExponential::TRANSLATION)
{
// Advance from the leftmost PoE term.
for (int i = idEnd - 1; i >= idStart; i--)
{
const MatrixExponential & nextExp = poe.exponentialAtJoint(i + 1);
// Compare two consecutive PoE terms.
if (i != idStart)
{
const MatrixExponential & currentExp = poe.exponentialAtJoint(i);
if (planarMovement(currentExp, nextExp))
{
// Might be ultimately simplified, let's find out in the next iterations.
continue;
}
}
else if (normalPlaneMovement(firstExp, nextExp))
{
// Can simplify everything to the *right* of this PoE term.
for (int j = idStart + 1; j <= idEnd; j++)
{
poeTerms[j].simplified = true;
}
}
break;
}
}
else if (lastExp.getMotionType() == MatrixExponential::TRANSLATION)
{
// Advance from the rightmost PoE term.
for (int i = idStart + 1; i <= idEnd; i++)
{
const MatrixExponential & prevExp = poe.exponentialAtJoint(i - 1);
if (i != idEnd)
{
const MatrixExponential & currentExp = poe.exponentialAtJoint(i);
if (planarMovement(prevExp, currentExp))
{
continue;
}
}
else if (normalPlaneMovement(prevExp, lastExp))
{
// Can simplify everything to the *left* of this PoE term.
for (int j = idEnd - 1; j >= idStart; j--)
{
poeTerms[j].simplified = true;
}
}
break;
}
}
}
// -----------------------------------------------------------------------------