/
InverseKinematics.hpp
1401 lines (1148 loc) · 55.6 KB
/
InverseKinematics.hpp
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2011-2024, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/main/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.
*/
#ifndef DART_DYNAMICS_INVERSEKINEMATICS_HPP_
#define DART_DYNAMICS_INVERSEKINEMATICS_HPP_
#include <dart/dynamics/JacobianNode.hpp>
#include <dart/dynamics/SmartPointer.hpp>
#include <dart/optimizer/Function.hpp>
#include <dart/optimizer/Problem.hpp>
#include <dart/optimizer/Solver.hpp>
#include <dart/math/Geometry.hpp>
#include <dart/common/Signal.hpp>
#include <dart/common/Subject.hpp>
#include <dart/common/sub_ptr.hpp>
#include <Eigen/SVD>
#include <functional>
#include <memory>
namespace dart {
namespace dynamics {
const double DefaultIKTolerance = 1e-6;
const double DefaultIKErrorClamp = 1.0;
const double DefaultIKGradientComponentClamp = 0.2;
const double DefaultIKGradientComponentWeight = 1.0;
const double DefaultIKDLSCoefficient = 0.05;
const double DefaultIKAngularWeight = 0.4;
const double DefaultIKLinearWeight = 1.0;
/// The InverseKinematics class provides a convenient way of setting up an IK
/// optimization problem. It generates constraint functions based on the
/// specified InverseKinematics::ErrorMethod and
/// InverseKinematics::GradientMethod. The optimization problem is then solved
/// by any classes derived from optimizer::Solver class. The default solver is
/// optimizer::GradientDescentSolver.
///
/// It also provides a convenient way of specifying a configuration space
/// objective and a null space objective. It is also possible to fully customize
/// the optimizer::Problem that the module creates, and the IK module can be
/// safely cloned over to another JacobianNode, as long as every
/// optimizer::Function that depends on the JacobianNode inherits the
/// InverseKinematics::Function class and correctly overloads the clone function
class InverseKinematics : public common::Subject
{
public:
/// Create an InverseKinematics module for a specified node
static InverseKinematicsPtr create(JacobianNode* _node);
/// Copying is not allowed
InverseKinematics(const InverseKinematics&) = delete;
/// Assignment is not allowed
InverseKinematics& operator=(const InverseKinematics&) = delete;
/// Virtual destructor
virtual ~InverseKinematics();
/// Solve the IK Problem.
///
/// The initial guess for the IK optimization problem is the current joint
/// positions of the target system. If the iterative solver fails to find a
/// successive solution, it attempts more to solve the problem with other seed
/// configurations or random configurations if enough seed is not provided.
///
/// Here is the pseudocode as described above:
///
/// \code
/// attempts <- 0
/// initial_guess <- current_joint_positions
/// while attempts <= max_attempts:
/// result <- solve(initial_guess)
/// if result = success:
/// return
/// else:
/// attempts <- attempts + 1
/// if attempts <= num_seed:
/// initial_guess <- seed[attempts - 1]
/// else:
/// initial_guess <- random_configuration // within the bounds
/// \endcode
///
/// By default, the max_attempts is 1, but this can be changed by calling
/// InverseKinematics::getSolver() and casting the SolverPtr to an
/// optimizer::GradientDescentSolver (unless you have changed the Solver type)
/// and then calling GradientDescentSolver::setMaxAttempts(std::size_t).
///
/// By default, the list of seeds is empty, but they can be added by calling
/// InverseKinematics::getProblem() and then using
/// Problem::addSeed(Eigen::VectorXd).
///
/// By default, the Skeleton itself will retain the solved joint positions.
/// If you pass in false for _applySolution, then the joint positions will be
/// returned to their original positions after the problem is solved.
///
/// Calling this function will automatically call Position::setLowerBounds(~)
/// and Position::setUpperBounds(~) with the lower/upper position bounds of
/// the corresponding Degrees Of Freedom. Problem::setDimension(~) will be
/// taken care of automatically, and Problem::setInitialGuess(~) will be
/// called with the current positions of the Degrees Of Freedom.
///
/// \deprecated Deprecated in DART 6.8. Please use solveAndApply() instead.
DART_DEPRECATED(6.8)
bool solve(bool applySolution = true);
/// Same as solve(bool), but the positions vector will be filled with the
/// solved positions.
///
/// \deprecated Deprecated in DART 6.8. Please use solveAndApply() or
/// findSolution() instead.
DART_DEPRECATED(6.8)
bool solve(Eigen::VectorXd& positions, bool applySolution = true);
/// Finds a solution of the IK problem without applying the solution.
///
/// The initial guess for the IK optimization problem is the current joint
/// positions of the target system. If the iterative solver fails to find a
/// successive solution, it attempts more to solve the problem with other seed
/// configurations or random configurations if enough seed is not provided.
///
/// Here is the pseudocode as described above:
///
/// \code
/// attempts <- 0
/// initial_guess <- current_joint_positions
/// while attempts <= max_attempts:
/// result <- solve(initial_guess)
/// if result = success:
/// return
/// else:
/// attempts <- attempts + 1
/// if attempts <= num_seed:
/// initial_guess <- seed[attempts - 1]
/// else:
/// initial_guess <- random_configuration // within the bounds
/// \endcode
///
/// By default, the max_attempts is 1, but this can be changed by calling
/// InverseKinematics::getSolver() and casting the SolverPtr to an
/// optimizer::GradientDescentSolver (unless you have changed the Solver type)
/// and then calling GradientDescentSolver::setMaxAttempts(std::size_t).
///
/// By default, the list of seeds is empty, but they can be added by calling
/// InverseKinematics::getProblem() and then using
/// Problem::addSeed(Eigen::VectorXd).
///
/// Calling this function will automatically call Position::setLowerBounds(~)
/// and Position::setUpperBounds(~) with the lower/upper position bounds of
/// the corresponding Degrees Of Freedom. Problem::setDimension(~) will be
/// taken care of automatically, and Problem::setInitialGuess(~) will be
/// called with the current positions of the Degrees Of Freedom.
///
/// \param[out] positions The solution of the IK problem. If the solver failed
/// to find a solution then it will still set the position with the best
/// guess. For example, iterative solvers will fill \c positions with the last
/// result of the iterations.
/// \return True if a solution is successfully found.
/// \sa solveAndApply()
bool findSolution(Eigen::VectorXd& positions);
/// Identical to findSolution(), but this function applies the solution when
/// the solver successfully found a solution or \c allowIncompleteResult is
/// set to true.
///
/// \param[in] allowIncompleteResult Allow to apply the solution even when
/// the solver failed to find solution. This option would be useful when an
/// iterative solver is used because they will often do a decent job of
/// getting a result close to a solution even if it failed to find the
/// solution.
/// \return True if a solution is successfully found
bool solveAndApply(bool allowIncompleteResult = true);
/// Identical to solveAndApply(bool), but \c position will be filled with the
/// solved positions.
///
/// \param[out] positions The solution of the IK problem. If the solver failed
/// to find a solution then it will still set the position with the best
/// guess. For example, iterative solvers will fill \c positions with the last
/// result of the iterations.
/// \param[in] allowIncompleteResult Allow to apply the solution even when
/// the solver failed to find solution. This option would be useful when an
/// iterative solver is used because they will often do a decent job of
/// getting a result close to a solution even if it failed to find the
/// solution.
/// \return True if a solution is successfully found
bool solveAndApply(
Eigen::VectorXd& positions, bool allowIncompleteResult = true);
/// Clone this IK module, but targeted at a new Node. Any Functions in the
/// Problem that inherit InverseKinematics::Function will be adapted to the
/// new IK module. Any generic optimizer::Function will just be copied over
/// by pointer instead of being cloned.
InverseKinematicsPtr clone(JacobianNode* _newNode) const;
// For the definitions of these classes, see the bottom of this header
class Function;
// Methods for computing IK error
class ErrorMethod;
class TaskSpaceRegion;
// Methods for computing IK gradient
class GradientMethod;
class JacobianDLS;
class JacobianTranspose;
class Analytical;
/// If this IK module is set to active, then it will be utilized by any
/// HierarchicalIK that has it in its list. If it is set to inactive, then it
/// will be ignored by any HierarchicalIK holding onto it, but you can still
/// use the solve() function with this.
void setActive(bool _active = true);
/// Equivalent to setActive(false)
void setInactive();
/// Returns true if this IK module is allowed to be active in a HierarchicalIK
bool isActive() const;
/// Set the hierarchy level of this module. Modules with a larger hierarchy
/// value will be projected through the null spaces of all modules with a
/// smaller hierarchy value. In other words, IK modules with a hierarchy level
/// closer to 0 are given higher priority.
void setHierarchyLevel(std::size_t _level);
/// Get the hierarchy level of this modle.
std::size_t getHierarchyLevel() const;
/// When solving the IK for this module's Node, use the longest available
/// dynamics::Chain that goes from this module's Node towards the root of the
/// Skeleton. Using this will prevent any other branches in the Skeleton from
/// being affected by this IK module.
void useChain();
/// Use all relevant joints on the Skeleton to solve the IK.
void useWholeBody();
/// Explicitly set which degrees of freedom should be used to solve the IK for
/// this module.
template <class DegreeOfFreedomT>
void setDofs(const std::vector<DegreeOfFreedomT*>& _dofs);
/// Explicitly set which degrees of freedom should be used to solve the IK for
/// this module. The values in the vector should correspond to the Skeleton
/// indices of each DOF.
void setDofs(const std::vector<std::size_t>& _dofs);
/// Get the indices of the DOFs that this IK module will use when solving.
const std::vector<std::size_t>& getDofs() const;
/// When a Jacobian is computed for a JacobianNode, it will include a column
/// for every DegreeOfFreedom that the node depends on. Given the column index
/// of one of those dependent coordinates, this map will return its location
/// in the mDofs vector. A value of -1 means that it is not present in the
/// mDofs vector and therefore should not be used when performing inverse
/// kinematics.
const std::vector<int>& getDofMap() const;
/// Set an objective function that should be minimized while satisfying the
/// inverse kinematics constraint. Pass in a nullptr to remove the objective
/// and make it a constant-zero function.
void setObjective(const std::shared_ptr<optimizer::Function>& _objective);
/// Get the objective function for this IK module
const std::shared_ptr<optimizer::Function>& getObjective();
/// Get the objective function for this IK module
std::shared_ptr<const optimizer::Function> getObjective() const;
/// Set an objective function that should be minimized within the null space
/// of the inverse kinematics constraint. The gradient of this function will
/// always be projected through the null space of this IK module's Jacobian.
/// Pass in a nullptr to remove the null space objective.
///
/// Note: The objectives given to setObjective() and setNullSpaceObjective()
/// will always be superimposed (added together) via the evalObjective()
/// function.
void setNullSpaceObjective(
const std::shared_ptr<optimizer::Function>& _nsObjective);
/// Get the null space objective for this IK module
const std::shared_ptr<optimizer::Function>& getNullSpaceObjective();
/// Get the null space objective for this IK module
std::shared_ptr<const optimizer::Function> getNullSpaceObjective() const;
/// Returns false if the null space objective does nothing
bool hasNullSpaceObjective() const;
/// Set the ErrorMethod for this IK module. You can pass in arguments for the
/// constructor, but you should ignore the constructor's first argument. The
/// first argument of the ErrorMethod's constructor must be a pointer to this
/// IK module, which will be automatically passed by this function.
template <class IKErrorMethod, typename... Args>
IKErrorMethod& setErrorMethod(Args&&... args);
/// Get the ErrorMethod for this IK module. Every IK module always has an
/// ErrorMethod available, so this is passed by reference.
ErrorMethod& getErrorMethod();
/// Get the ErrorMethod for this IK module. Every IK module always has an
/// ErrorMethod available, so this is passed by reference.
const ErrorMethod& getErrorMethod() const;
/// Set the GradientMethod for this IK module. You can pass in arguments for
/// the constructor, but you should ignore the constructor's first argument.
/// The first argument of the GradientMethod's constructor must be a pointer
/// to this IK module, which will be automatically passed by this function.
template <class IKGradientMethod, typename... Args>
IKGradientMethod& setGradientMethod(Args&&... args);
/// Get the GradientMethod for this IK module. Every IK module always has a
/// GradientMethod available, so this is passed by reference.
GradientMethod& getGradientMethod();
/// Get the GradientMethod for this IK module. Every IK module always has a
/// GradientMethod available, so this is passed by reference.
const GradientMethod& getGradientMethod() const;
/// Get the Analytical IK method for this module, if one is available.
/// Analytical methods are not provided by default. If this IK module does not
/// have an analytical method, then this will return a nullptr.
Analytical* getAnalytical();
/// Get the Analytical IK method for this module, if one is available.
/// Analytical methods are not provided by default. If this IK module does not
/// have an analytical method, then this will return a nullptr.
const Analytical* getAnalytical() const;
/// Get the Problem that is being maintained by this IK module.
const std::shared_ptr<optimizer::Problem>& getProblem();
/// Get the Problem that is being maintained by this IK module.
std::shared_ptr<const optimizer::Problem> getProblem() const;
/// Reset the Problem that is being maintained by this IK module. This will
/// clear out all Functions from the Problem and then configure the Problem to
/// use this IK module's Objective and Constraint functions.
///
/// Setting _clearSeeds to true will clear out any seeds that have been loaded
/// into the Problem.
void resetProblem(bool _clearSeeds = false);
/// Set the Solver that should be used by this IK module, and set it up with
/// the Problem that is configured by this IK module
void setSolver(const std::shared_ptr<optimizer::Solver>& _newSolver);
/// Get the Solver that is being used by this IK module.
const std::shared_ptr<optimizer::Solver>& getSolver();
/// Get the Solver that is being used by this IK module.
std::shared_ptr<const optimizer::Solver> getSolver() const;
/// Inverse kinematics can be performed on any point within the body frame.
/// The default point is the origin of the body frame. Use this function to
/// change the point that will be used. _offset must represent the offset of
/// the desired point from the body origin, expressed in coordinates of the
/// body frame.
void setOffset(const Eigen::Vector3d& _offset = Eigen::Vector3d::Zero());
/// Get the offset from the origin of the body frame that will be used when
/// performing inverse kinematics. The offset will be expressed in the
/// coordinates of the body frame.
const Eigen::Vector3d& getOffset() const;
/// This returns false if the offset for the inverse kinematics is a zero
/// vector. Otherwise, it returns true. Use setOffset() to set the offset and
/// getOffset() to get the offset.
bool hasOffset() const;
/// Set the target for this IK module.
///
/// Note that a target will automatically be created for the IK module upon
/// instantiation, so you typically do not need to use this function. If you
/// want to attach the target to an arbitrary (non-SimpleFrame) reference
/// frame, you can do getTarget()->setParentFrame(arbitraryFrame)
void setTarget(std::shared_ptr<SimpleFrame> _newTarget);
/// Get the target that is being used by this IK module. You never have to
/// check whether this is a nullptr, because it cannot ever be set to nullptr.
std::shared_ptr<SimpleFrame> getTarget();
/// Get the target that is being used by this IK module. You never have to
/// check whether this is a nullptr, because it cannot ever be set to nullptr.
std::shared_ptr<const SimpleFrame> getTarget() const;
/// Get the JacobianNode that this IK module operates on.
JacobianNode* getNode();
/// Get the JacobianNode that this IK module operates on.
const JacobianNode* getNode() const;
/// This is the same as getNode(). It is used by the InverseKinematicsPtr to
/// provide a common interface for the various IK smart pointer types.
JacobianNode* getAffiliation();
/// This is the same as getNode(). It is used by the InverseKinematicsPtr to
/// provide a common interface for the various IK smart pointer types.
const JacobianNode* getAffiliation() const;
/// Compute the Jacobian for this IK module's node, using the Skeleton's
/// current joint positions and the DOFs that have been assigned to the
/// module.
const math::Jacobian& computeJacobian() const;
/// Get the current joint positions of the Skeleton. This will only include
/// the DOFs that have been assigned to this IK module, and the components of
/// the vector will correspond to the components of getDofs().
Eigen::VectorXd getPositions() const;
/// Set the current joint positions of the Skeleton. This must only include
/// the DOFs that have been assigned to this IK module, and the components of
/// the vector must correspond to the components of getDofs().
void setPositions(const Eigen::VectorXd& _q);
/// Clear the caches of this IK module. It should generally not be necessary
/// to call this function. However, if you have some non-standard external
/// dependency for your error and/or gradient method computations, then you
/// will need to tie this function to something that tracks changes in that
/// dependency.
void clearCaches();
protected:
// For the definitions of these functions, see the bottom of this header
class Objective;
friend class Objective;
class Constraint;
friend class Constraint;
/// Constructor that accepts a JacobianNode
InverseKinematics(JacobianNode* _node);
/// Gets called during construction
void initialize();
/// Reset the signal connection for this IK module's target
void resetTargetConnection();
/// Reset the signal connection for this IK module's Node
void resetNodeConnection();
/// Connection to the target update
common::Connection mTargetConnection;
/// Connection to the node update
common::Connection mNodeConnection;
/// True if this IK module should be active in its IK hierarcy
bool mActive;
/// Hierarchy level for this IK module
std::size_t mHierarchyLevel;
/// A list of the DegreeOfFreedom Skeleton indices that will be used by this
/// IK module
std::vector<std::size_t> mDofs;
/// Map for the DOFs that are to be used by this IK module
std::vector<int> mDofMap;
/// Objective for the IK module
std::shared_ptr<optimizer::Function> mObjective;
/// Null space objective for the IK module
std::shared_ptr<optimizer::Function> mNullSpaceObjective;
/// The method that this IK module will use to compute errors
std::unique_ptr<ErrorMethod> mErrorMethod;
/// The method that this IK module will use to compute gradients
std::unique_ptr<GradientMethod> mGradientMethod;
/// If mGradientMethod is an Analytical extension, then this will have the
/// same value is mGradientMethod. Otherwise, this will be a nullptr.
///
/// Note that this pointer's memory does not need to be managed, because it is
/// always either nullptr or a reference to mGradientMethod.
Analytical* mAnalytical;
/// The Problem that will be maintained by this IK module
std::shared_ptr<optimizer::Problem> mProblem;
/// The solver that this IK module will use for iterative methods
std::shared_ptr<optimizer::Solver> mSolver;
/// The offset that this IK module should use when computing IK
Eigen::Vector3d mOffset;
/// True if the offset is non-zero
bool mHasOffset;
/// Target that this IK module should use
std::shared_ptr<SimpleFrame> mTarget;
/// JacobianNode that this IK module is associated with
sub_ptr<JacobianNode> mNode;
/// Jacobian cache for the IK module
mutable math::Jacobian mJacobian;
};
typedef InverseKinematics IK;
//==============================================================================
/// This class should be inherited by optimizer::Function classes that have a
/// dependency on the InverseKinematics module that they belong to. If you
/// pass an InverseKinematics::Function into the Problem of an
/// InverseKinematics module, then it will be properly cloned whenever the
/// InverseKinematics module that it belongs to gets cloned. Any Function
/// classes in the Problem that do not inherit InverseKinematics::Function
/// will just be copied over by reference.
class InverseKinematics::Function
{
public:
/// Enable this function to be cloned to a new IK module.
virtual optimizer::FunctionPtr clone(InverseKinematics* _newIK) const = 0;
/// Virtual destructor
virtual ~Function() = default;
};
//==============================================================================
/// ErrorMethod is a base class for different ways of computing the error of
/// an InverseKinematics module.
class InverseKinematics::ErrorMethod : public common::Subject
{
public:
typedef std::pair<Eigen::Vector6d, Eigen::Vector6d> Bounds;
/// The Properties struct contains settings that are commonly used by
/// methods that compute error for inverse kinematics.
struct Properties
{
/// Default constructor
Properties(
const Bounds& _bounds = Bounds(
Eigen::Vector6d::Constant(-DefaultIKTolerance),
Eigen::Vector6d::Constant(DefaultIKTolerance)),
double _errorClamp = DefaultIKErrorClamp,
const Eigen::Vector6d& _errorWeights = Eigen::compose(
Eigen::Vector3d::Constant(DefaultIKAngularWeight),
Eigen::Vector3d::Constant(DefaultIKLinearWeight)));
/// Bounds that define the acceptable range of the Node's transform
/// relative to its target frame.
std::pair<Eigen::Vector6d, Eigen::Vector6d> mBounds;
/// The error vector will be clamped to this length with each iteration.
/// This is used to enforce sane behavior, even when there are extremely
/// large error vectors.
double mErrorLengthClamp;
/// These weights will be applied to the error vector component-wise. This
/// allows you to set some components of error as more important than
/// others, or to scale their coordinate spaces. For example, you will
/// often want the first three components (orientation error) to have
/// smaller weights than the last three components (translation error).
Eigen::Vector6d mErrorWeights;
// To get byte-aligned Eigen vectors
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
/// Constructor
ErrorMethod(
InverseKinematics* _ik,
const std::string& _methodName,
const Properties& _properties = Properties());
/// Virtual destructor
virtual ~ErrorMethod() = default;
/// Enable this ErrorMethod to be cloned to a new IK module.
virtual std::unique_ptr<ErrorMethod> clone(
InverseKinematics* _newIK) const = 0;
/// Override this function with your implementation of the error vector
/// computation. The expectation is that the first three components of the
/// vector will correspond to orientation error (in an angle-axis format)
/// while the last three components correspond to translational error.
///
/// When implementing this function, you should assume that the Skeleton's
/// current joint positions corresponds to the positions that you
/// must use to compute the error. This function will only get called when
/// an update is needed.
virtual Eigen::Vector6d computeError() = 0;
/// Override this function with your implementation of computing the desired
/// given the current transform and error vector. If you want the desired
/// transform to always be equal to the Target's transform, you can simply
/// call ErrorMethod::computeDesiredTransform to implement this function.
virtual Eigen::Isometry3d computeDesiredTransform(
const Eigen::Isometry3d& _currentTf, const Eigen::Vector6d& _error)
= 0;
/// This function is used to handle caching the error vector.
const Eigen::Vector6d& evalError(const Eigen::VectorXd& _q);
/// Get the name of this ErrorMethod.
const std::string& getMethodName() const;
/// Set all the error bounds.
void setBounds(
const Eigen::Vector6d& _lower
= Eigen::Vector6d::Constant(-DefaultIKTolerance),
const Eigen::Vector6d& _upper
= Eigen::Vector6d::Constant(DefaultIKTolerance));
/// Set all the error bounds.
void setBounds(const std::pair<Eigen::Vector6d, Eigen::Vector6d>& _bounds);
/// Get all the error bounds.
const std::pair<Eigen::Vector6d, Eigen::Vector6d>& getBounds() const;
/// Set the error bounds for orientation.
void setAngularBounds(
const Eigen::Vector3d& _lower
= Eigen::Vector3d::Constant(-DefaultIKTolerance),
const Eigen::Vector3d& _upper
= Eigen::Vector3d::Constant(DefaultIKTolerance));
/// Set the error bounds for orientation.
void setAngularBounds(
const std::pair<Eigen::Vector3d, Eigen::Vector3d>& _bounds);
/// Get the error bounds for orientation.
std::pair<Eigen::Vector3d, Eigen::Vector3d> getAngularBounds() const;
/// Set the error bounds for translation.
void setLinearBounds(
const Eigen::Vector3d& _lower
= Eigen::Vector3d::Constant(-DefaultIKTolerance),
const Eigen::Vector3d& _upper
= Eigen::Vector3d::Constant(DefaultIKTolerance));
/// Set the error bounds for translation.
void setLinearBounds(
const std::pair<Eigen::Vector3d, Eigen::Vector3d>& _bounds);
/// Get the error bounds for translation.
std::pair<Eigen::Vector3d, Eigen::Vector3d> getLinearBounds() const;
/// Set the clamp that will be applied to the length of the error vector
/// each iteration.
void setErrorLengthClamp(double _clampSize = DefaultIKErrorClamp);
/// Set the clamp that will be applied to the length of the error vector
/// each iteration.
double getErrorLengthClamp() const;
/// Set the weights that will be applied to each component of the error
/// vector.
void setErrorWeights(const Eigen::Vector6d& _weights);
/// Get the weights that will be applied to each component of the error
/// vector.
const Eigen::Vector6d& getErrorWeights() const;
/// Set the weights that will be applied to each angular component of the
/// error vector.
void setAngularErrorWeights(
const Eigen::Vector3d& _weights
= Eigen::Vector3d::Constant(DefaultIKAngularWeight));
/// Get the weights that will be applied to each angular component of the
/// error vector.
Eigen::Vector3d getAngularErrorWeights() const;
/// Set the weights that will be applied to each linear component of the
/// error vector.
void setLinearErrorWeights(
const Eigen::Vector3d& _weights
= Eigen::Vector3d::Constant(DefaultIKLinearWeight));
/// Get the weights that will be applied to each linear component of the
/// error vector.
Eigen::Vector3d getLinearErrorWeights() const;
/// Get the Properties of this ErrorMethod
Properties getErrorMethodProperties() const;
/// Clear the cache to force the error to be recomputed. It should generally
/// not be necessary to call this function.
void clearCache();
protected:
/// Pointer to the IK module of this ErrorMethod
common::sub_ptr<InverseKinematics> mIK;
/// Name of this error method
std::string mMethodName;
/// The last joint positions passed into this ErrorMethod
Eigen::VectorXd mLastPositions;
/// The last error vector computed by this ErrorMethod
Eigen::Vector6d mLastError;
/// The properties of this ErrorMethod
Properties mErrorP;
public:
// To get byte-aligned Eigen vectors
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
//==============================================================================
/// The TaskSpaceRegion is a nicely generalized method for computing the error
/// of an IK Problem.
class InverseKinematics::TaskSpaceRegion : public ErrorMethod
{
public:
struct UniqueProperties
{
/// Setting this to true (which is default) will tell it to compute the
/// error based on the center of the Task Space Region instead of the edge
/// of the Task Space Region. This often results in faster convergence, as
/// the Node will enter the Task Space Region more aggressively.
///
/// Once the Node is inside the Task Space Region, the error vector will
/// drop to zero, regardless of whether this flag is true or false.
bool mComputeErrorFromCenter;
/// The reference frame that the task space region is expressed. If this
/// frame is set to nullptr, which is the default, then the parent frame of
/// the target frame is used instead.
SimpleFramePtr mReferenceFrame;
/// Default constructor
UniqueProperties(
bool computeErrorFromCenter = true,
SimpleFramePtr referenceFrame = nullptr);
};
struct Properties : ErrorMethod::Properties, UniqueProperties
{
/// Default constructor
Properties(
const ErrorMethod::Properties& errorProperties
= ErrorMethod::Properties(),
const UniqueProperties& taskSpaceProperties = UniqueProperties());
};
/// Default Constructor
explicit TaskSpaceRegion(
InverseKinematics* _ik, const Properties& _properties = Properties());
/// Virtual destructor
virtual ~TaskSpaceRegion() = default;
// Documentation inherited
std::unique_ptr<ErrorMethod> clone(InverseKinematics* _newIK) const override;
// Documentation inherited
Eigen::Isometry3d computeDesiredTransform(
const Eigen::Isometry3d& _currentTf,
const Eigen::Vector6d& _error) override;
// Documentation inherited
Eigen::Vector6d computeError() override;
/// Set whether this TaskSpaceRegion should compute its error vector from
/// the center of the region.
void setComputeFromCenter(bool computeFromCenter);
/// Get whether this TaskSpaceRegion is set to compute its error vector from
/// the center of the region.
bool isComputingFromCenter() const;
/// Set the reference frame that the task space region is expressed. Pass
/// nullptr to use the parent frame of the target frame instead.
void setReferenceFrame(SimpleFramePtr referenceFrame);
/// Get the reference frame that the task space region is expressed.
ConstSimpleFramePtr getReferenceFrame() const;
/// Get the Properties of this TaskSpaceRegion
Properties getTaskSpaceRegionProperties() const;
protected:
/// Properties of this TaskSpaceRegion
UniqueProperties mTaskSpaceP;
};
//==============================================================================
/// GradientMethod is a base class for different ways of computing the
/// gradient of an InverseKinematics module.
class InverseKinematics::GradientMethod : public common::Subject
{
public:
struct Properties
{
/// The component-wise clamp for this GradientMethod
double mComponentWiseClamp;
/// The weights for this GradientMethod
Eigen::VectorXd mComponentWeights;
/// Default constructor
Properties(
double clamp = DefaultIKGradientComponentClamp,
const Eigen::VectorXd& weights = Eigen::VectorXd());
};
/// Constructor
GradientMethod(
InverseKinematics* _ik,
const std::string& _methodName,
const Properties& _properties);
/// Virtual destructor
virtual ~GradientMethod() = default;
/// Enable this GradientMethod to be cloned to a new IK module
virtual std::unique_ptr<GradientMethod> clone(
InverseKinematics* _newIK) const = 0;
/// Override this function with your implementation of the gradient
/// computation. The direction that this gradient points in should make the
/// error **worse** if applied to the joint positions, because the
/// Problem is configured as a gradient **descent** error minimization
/// Problem.
///
/// The error vector that is passed in will be determined by the IK module's
/// ErrorMethod. The expectation is that the first three components of the
/// vector correspond to orientation error (in an angle-axis format) while
/// the last three components correspond to translational error.
///
/// When implementing this function, you should assume that the Skeleton's
/// current joint positions corresponds to the positions that you
/// must use to compute the error. This function will only get called when
/// an update is needed.
virtual void computeGradient(
const Eigen::Vector6d& _error, Eigen::VectorXd& _grad)
= 0;
/// This function is used to handle caching the gradient vector and
/// interfacing with the solver.
void evalGradient(
const Eigen::VectorXd& _q, Eigen::Map<Eigen::VectorXd> _grad);
/// Get the name of this GradientMethod.
const std::string& getMethodName() const;
/// Clamp the gradient based on the clamp settings of this GradientMethod.
void clampGradient(Eigen::VectorXd& _grad) const;
/// Set the component-wise clamp for this GradientMethod. Each component
/// of the gradient will be individually clamped to this size.
void setComponentWiseClamp(double _clamp = DefaultIKGradientComponentClamp);
/// Get the component-wise clamp for this GradientMethod.
double getComponentWiseClamp() const;
/// Apply weights to the gradient based on the weight settings of this
/// GradientMethod.
void applyWeights(Eigen::VectorXd& _grad) const;
/// Set the weights that will be applied to each component of the gradient.
/// If the number of components in _weights is smaller than the number of
/// components in the gradient, then a weight of 1.0 will be applied to all
/// components that are out of the range of _weights. Passing in an empty
/// vector for _weights will effectively make all the gradient components
/// unweighted.
void setComponentWeights(const Eigen::VectorXd& _weights);
/// Get the weights of this GradientMethod.
const Eigen::VectorXd& getComponentWeights() const;
/// Convert the gradient that gets generated by Jacobian methods into a
/// gradient that can be used by a GradientDescentSolver.
///
/// Not all Joint types can be integrated using standard addition (e.g.
/// FreeJoint and BallJoint), therefore Jacobian-based differential methods
/// will tend to generate gradients that cannot be correctly used by a
/// simple addition-based GradientDescentSolver. Running your gradient
/// through this function before returning it will make the gradient
/// suitable for a standard solver.
void convertJacobianMethodOutputToGradient(
Eigen::VectorXd& grad, const std::vector<std::size_t>& dofs);
/// Get the Properties of this GradientMethod
Properties getGradientMethodProperties() const;
/// Clear the cache to force the gradient to be recomputed. It should
/// generally not be necessary to call this function.
void clearCache();
/// Returns the IK module that this GradientMethod belongs to.
InverseKinematics* getIK();
/// Returns the IK module that this GradientMethod belongs to.
const InverseKinematics* getIK() const;
protected:
/// The IK module that this GradientMethod belongs to.
common::sub_ptr<InverseKinematics> mIK;
/// The name of this method
std::string mMethodName;
/// The last positions that was passed to this GradientMethod
Eigen::VectorXd mLastPositions;
/// The last gradient that was computed by this GradientMethod
Eigen::VectorXd mLastGradient;
/// Properties for this GradientMethod
Properties mGradientP;
private:
/// Cache used by convertJacobianMethodOutputToGradient to avoid
/// reallocating this vector on each iteration.
Eigen::VectorXd mInitialPositionsCache;
};
//==============================================================================
/// JacobianDLS refers to the Damped Least Squares Jacobian Pseudoinverse
/// (specifically, Moore-Penrose Pseudoinverse). This is a very precise method
/// for computing the gradient and is especially suitable for performing IK on
/// industrial manipulators that need to follow very exact workspace paths.
/// However, it is vulnerable to be jittery around singularities (though the
/// damping helps with this), and each cycle might take more time to compute
/// than the JacobianTranspose method (although the JacobianDLS method will
/// usually converge in fewer cycles than JacobianTranspose).
class InverseKinematics::JacobianDLS : public GradientMethod
{
public:
struct UniqueProperties
{
/// Damping coefficient
double mDamping;
/// Default constructor
UniqueProperties(double damping = DefaultIKDLSCoefficient);
};
struct Properties : GradientMethod::Properties, UniqueProperties
{
/// Default constructor
Properties(
const GradientMethod::Properties& gradientProperties
= GradientMethod::Properties(),
const UniqueProperties& dlsProperties = UniqueProperties());
};
/// Constructor
explicit JacobianDLS(
InverseKinematics* _ik, const Properties& properties = Properties());
/// Virtual destructor
virtual ~JacobianDLS() = default;
// Documentation inherited
std::unique_ptr<GradientMethod> clone(
InverseKinematics* _newIK) const override;
// Documentation inherited
void computeGradient(
const Eigen::Vector6d& _error, Eigen::VectorXd& _grad) override;
/// Set the damping coefficient. A higher damping coefficient will smooth
/// out behavior around singularities but will also result in less precision
/// in general. The default value is appropriate for most use cases.