Repository navigation
chore: add inverse kinematics #136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| # Inverse Kinematics (Damped Least Squares) | ||
|
|
||
| ## Overview & Motivation | ||
|
|
||
| Inverse Kinematics (IK) solves the problem dual to Forward Kinematics: given a desired 3D end-effector position $p_{\text{target}}$, find joint angles $q$ such that the end-effector reaches that position. This is the core computational problem in robot arm control, motion planning, and teleoperation. | ||
|
|
||
| The **Damped Least Squares** (DLS) method, also known as the Levenberg-Marquardt approach, iteratively refines a joint-angle estimate by solving a small linear system at each step. Unlike the plain pseudoinverse, DLS adds a damping term $\lambda^2 I$ that keeps the system numerically stable even when the manipulator is near a singular configuration (such as a fully extended arm). | ||
|
|
||
| ## Mathematical Theory | ||
|
|
||
| ### Jacobian of a Serial Chain | ||
|
|
||
| For a serial revolute-joint chain with $n$ joints, the **geometric Jacobian** $J \in \mathbb{R}^{3 \times n}$ maps joint velocities $\dot{q}$ to end-effector linear velocity: | ||
|
|
||
| $$\dot{p}_{\text{ee}} = J(q) \, \dot{q}$$ | ||
|
|
||
| Column $i$ of $J$ is the linear velocity contribution of joint $i$: | ||
|
|
||
| $$J_i = a_i^w \times (p_{\text{ee}} - p_i)$$ | ||
|
|
||
| where: | ||
| - $a_i^w = R_{0 \to i} \, a_i^{\text{link}}$ is the joint axis in world frame (accumulated rotation applied to the link-frame axis) | ||
| - $p_i$ is the world-frame position of joint $i$ (from Forward Kinematics) | ||
| - $p_{\text{ee}}$ is the current end-effector position | ||
|
|
||
| ### DLS Update Rule | ||
|
|
||
| Define the position error: | ||
|
|
||
| $$e = p_{\text{target}} - p_{\text{ee}}(q) \in \mathbb{R}^3$$ | ||
|
|
||
| The DLS joint update per iteration is: | ||
|
|
||
| $$\Delta q = J^\top \bigl(J J^\top + \lambda^2 I\bigr)^{-1} e$$ | ||
|
|
||
| This is equivalent to solving the $3 \times 3$ linear system: | ||
|
|
||
| $$\underbrace{\bigl(J J^\top + \lambda^2 I\bigr)}_{A} \, y = e, \quad \Delta q = J^\top y$$ | ||
|
|
||
| where $A \in \mathbb{R}^{3 \times 3}$ is always symmetric positive definite (the damping $\lambda^2 I$ guarantees this), so `GaussianElimination<T, 3>` solves it reliably. | ||
|
|
||
| The updated joint angles are: | ||
|
|
||
| $$q_{k+1} = q_k + \Delta q$$ | ||
|
|
||
| ### Convergence | ||
|
|
||
| The loop terminates when: | ||
| - $\|e\| < \epsilon_{\text{tol}}$ (success), or | ||
| - The maximum iteration count is reached (failure to converge — target unreachable or tolerance too tight) | ||
|
|
||
| ### Why DLS over Plain Pseudoinverse | ||
|
|
||
| At a kinematic singularity (e.g., fully extended arm), $J J^\top$ becomes rank-deficient. The pseudoinverse $J^+ = J^\top (J J^\top)^{-1}$ would produce infinite joint velocities. The damping term $\lambda^2 I$ bounds the solution: | ||
|
|
||
| $$\|\Delta q\| \leq \frac{\|e\|}{\lambda}$$ | ||
|
|
||
| The cost is a small positional bias proportional to $\lambda$: the algorithm converges to within approximately $\lambda^2 \|e\|$ rather than exact zero. Choosing $\lambda \in [0.01, 0.2]$ balances stability and accuracy for typical robot geometries. | ||
|
|
||
| ## Complexity Analysis | ||
|
|
||
| | Case | Time | Space | Notes | | ||
| |---------------|----------------|--------|----------------------------------------| | ||
| | Per iteration | $O(n)$ | $O(n)$ | FK sweep + Jacobian + $3\times3$ solve | | ||
| | Total | $O(k \cdot n)$ | $O(n)$ | $k$ = iterations (typically 10–50) | | ||
|
|
||
| The $3 \times 3$ linear solve is $O(1)$ (constant-size), independent of the number of joints $n$. | ||
|
|
||
| ## Step-by-Step Walkthrough | ||
|
|
||
| Consider a 2-link planar arm with $l_1 = 1.0$, $l_2 = 0.8$, both joints rotating about the Z-axis, target $p_{\text{target}} = (0.5, 1.0, 0)$, initial guess $q = (0, 0)$, $\lambda = 0.1$. | ||
|
|
||
| **Iteration 1:** | ||
|
|
||
| 1. FK gives $p_{\text{ee}} = (1.8, 0, 0)$ (fully extended along X) | ||
| 2. Error: $e = (-1.3, 1.0, 0)$, $\|e\| \approx 1.64$ | ||
| 3. Jacobian (Z-axis joints, cross-product form): | ||
| - $J_1 = [0,0,1]^\top \times (p_{\text{ee}} - p_0) = [0,0,1]^\top \times [1.8, 0, 0]^\top = [0, 1.8, 0]^\top$ | ||
| - $J_2 = [0,0,1]^\top \times (p_{\text{ee}} - p_1) = [0,0,1]^\top \times [0.8, 0, 0]^\top = [0, 0.8, 0]^\top$ | ||
| - $J = \begin{bmatrix} 0 & 0 \\ 1.8 & 0.8 \\ 0 & 0 \end{bmatrix}$ (only Y-row is non-zero for planar X motion) | ||
| 4. $A = J J^\top + 0.01 I$ — a $3 \times 3$ SPD matrix | ||
| 5. Solve $Ay = e$, compute $\Delta q = J^\top y$ | ||
| 6. Update both joint angles toward a bent configuration | ||
|
|
||
| After ~40 iterations $q$ converges to joints that produce $p_{\text{ee}} \approx (0.5, 1.0, 0)$. | ||
|
|
||
| ## Pitfalls & Edge Cases | ||
|
|
||
| - **Unreachable targets**: If $\|p_{\text{target}}\|$ exceeds the total arm length, the algorithm reaches maximum iterations without converging. The returned result has `converged = false`; the end-effector will be as close as geometrically possible. | ||
| - **Singularity handling**: Near singularities (e.g., fully extended arm), the damping $\lambda$ prevents numerical blow-up but introduces a small steady-state error. Reduce $\lambda$ for higher accuracy away from singularities. | ||
| - **Local minima in redundant chains**: For $n > 3$ (redundant), DLS finds *a* solution (minimum-norm joint motion) but not necessarily the one with the best posture. Null-space techniques (projecting secondary objectives into $\ker(J)$) can improve this. | ||
| - **Initial guess sensitivity**: Starting closer to the expected solution reduces iterations and avoids winding through joint-limit regions. For repeated calls (e.g., tracking), use the previous solution as the initial guess. | ||
| - **Float-only**: Uses `std::cos`, `std::sin`, and `std::sqrt`; Q15/Q31 fixed-point types are not supported. | ||
| - **Configuration preconditions**: `dampingFactor` and `tolerance` must both be strictly positive. The damping term $\lambda^2 I$ ensures $A$ is symmetric positive definite only when $\lambda > 0$; both values are asserted in debug builds via `really_assert`. | ||
|
|
||
| ## Variants & Generalizations | ||
|
|
||
| - **Jacobian Transpose**: $\Delta q = \alpha J^\top e$ — no matrix solve, but slower convergence and step-size sensitive. Suitable for very constrained embedded targets. | ||
| - **Pseudoinverse (Moore-Penrose)**: DLS with $\lambda = 0$ — exact minimum-norm solution but numerically unstable at singularities. | ||
| - **FABRIK**: Forward-And-Backward Reaching IK — purely geometric, position-only, no Jacobian required. Very fast per iteration; preferred when orientation control is not needed. | ||
| - **Cyclic Coordinate Descent (CCD)**: Each joint independently minimizes error; simple but produces unnatural motion. | ||
| - **Full 6-DOF pose IK**: Extend $J$ to $6 \times n$ (stacking angular velocity rows) and $e$ to $\mathbb{R}^6$ to control both position and orientation. | ||
|
|
||
| ## Applications | ||
|
|
||
| - **Robot arm target tracking**: Drive the end-effector to follow a moving 3D target in real-time. | ||
| - **Teleoperation**: Map operator hand position to robot joint angles continuously. | ||
| - **Motion planning**: Compute joint-space waypoints from Cartesian-space paths. | ||
| - **Animation & simulation**: Pose limbs in a physically plausible configuration to reach a point of interest. | ||
|
|
||
| ## Connections to Other Algorithms | ||
|
|
||
| - [Forward Kinematics](ForwardKinematics.md): Called internally every iteration to compute current end-effector position and joint positions for the Jacobian. | ||
| - [GaussianElimination](../solvers/GaussianElimination.md): Solves the $3 \times 3$ DLS system $Ay = e$ at the core of each iteration. | ||
| - `numerical/math/Geometry3D.hpp`: Provides `CrossProduct` for Jacobian column computation, `RotationAboutAxis` for accumulated rotation, and `VectorNorm` for convergence check. | ||
|
|
||
| ## References & Further Reading | ||
|
|
||
| - Buss, S.R. (2004). *Introduction to Inverse Kinematics with Jacobian Transpose, Pseudoinverse and Damped Least Squares methods*. University of California, San Diego. [PDF](https://mathweb.ucsd.edu/~sbuss/ResearchWeb/ikmethods/iksurvey.pdf) | ||
| - Nakamura, Y. and Hanafusa, H. (1986). "Inverse kinematic solutions with singularity robustness for robot manipulator control". *Journal of Dynamic Systems, Measurement, and Control*, 108(3). | ||
| - Siciliano, B. et al. (2009). *Robotics: Modelling, Planning and Control*. Springer. Chapter 3. | ||
| - Craig, J.J. (2005). *Introduction to Robotics: Mechanics and Control*. 3rd ed. Chapter 4. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| #include "numerical/kinematics/InverseKinematics.hpp" | ||
|
|
||
| namespace kinematics | ||
| { | ||
| template class InverseKinematics<float, 1>; | ||
| template class InverseKinematics<float, 2>; | ||
| template class InverseKinematics<float, 3>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| #pragma once | ||
|
|
||
| #if defined(__GNUC__) || defined(__clang__) | ||
| #pragma GCC optimize("O3", "fast-math") | ||
| #endif | ||
|
|
||
| #include "infra/util/ReallyAssert.hpp" | ||
| #include "numerical/dynamics/RevoluteJointLink.hpp" | ||
| #include "numerical/kinematics/ForwardKinematics.hpp" | ||
| #include "numerical/math/CompilerOptimizations.hpp" | ||
| #include "numerical/math/Geometry3D.hpp" | ||
| #include "numerical/math/Matrix.hpp" | ||
| #include "numerical/solvers/GaussianElimination.hpp" | ||
| #include <array> | ||
| #include <cmath> | ||
| #include <cstddef> | ||
|
|
||
| namespace kinematics | ||
| { | ||
| template<typename T> | ||
| struct InverseKinematicsConfig | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, | ||
| "InverseKinematicsConfig only supports floating-point types"); | ||
|
|
||
| T dampingFactor = T(0.1); | ||
| T tolerance = T(1e-4); | ||
| std::size_t maxIterations = 100; | ||
| }; | ||
|
|
||
| template<typename T, std::size_t NumLinks> | ||
| struct InverseKinematicsResult | ||
| { | ||
| math::Vector<T, NumLinks> q; | ||
| T finalError; | ||
| std::size_t iterations; | ||
| bool converged; | ||
| }; | ||
|
|
||
| template<typename T, std::size_t NumLinks> | ||
| class InverseKinematics | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, | ||
| "InverseKinematics only supports floating-point types"); | ||
| static_assert(NumLinks > 0, "Number of links must be positive"); | ||
|
|
||
| public: | ||
| using Vector3 = math::Vector3<T>; | ||
| using Matrix3 = math::Matrix3<T>; | ||
| using JointVector = math::Vector<T, NumLinks>; | ||
| using Jacobian = math::Matrix<T, 3, NumLinks>; | ||
| using LinkArray = std::array<dynamics::RevoluteJointLink<T>, NumLinks>; | ||
| using PositionArray = std::array<Vector3, NumLinks + 1>; | ||
|
|
||
| explicit InverseKinematics(InverseKinematicsConfig<T> cfg = {}); | ||
|
|
||
| OPTIMIZE_FOR_SPEED InverseKinematicsResult<T, NumLinks> Solve( | ||
| const LinkArray& links, | ||
| const Vector3& target, | ||
| const JointVector& initialQ) const; | ||
|
|
||
| private: | ||
| Jacobian ComputeJacobian( | ||
| const LinkArray& links, | ||
| const JointVector& q, | ||
| const PositionArray& positions) const; | ||
|
|
||
| InverseKinematicsConfig<T> config; | ||
| ForwardKinematics<T, NumLinks> fk; | ||
|
Check warning on line 69 in numerical/kinematics/InverseKinematics.hpp
|
||
| mutable solvers::GaussianElimination<T, 3> solver; | ||
| }; | ||
|
|
||
| template<typename T, std::size_t NumLinks> | ||
| InverseKinematics<T, NumLinks>::InverseKinematics(InverseKinematicsConfig<T> cfg) | ||
| : config(cfg) | ||
| { | ||
| really_assert(config.dampingFactor > T(0)); | ||
| really_assert(config.tolerance > T(0)); | ||
| } | ||
|
|
||
| template<typename T, std::size_t NumLinks> | ||
| OPTIMIZE_FOR_SPEED | ||
| InverseKinematicsResult<T, NumLinks> | ||
| InverseKinematics<T, NumLinks>::Solve( | ||
| const LinkArray& links, | ||
| const Vector3& target, | ||
| const JointVector& initialQ) const | ||
| { | ||
| JointVector q = initialQ; | ||
|
|
||
| std::size_t iter = 0; | ||
| T error = T(0); | ||
|
|
||
| for (; iter < config.maxIterations; ++iter) | ||
| { | ||
| auto positions = fk.Compute(links, q); | ||
| const Vector3& eePos = positions[NumLinks]; | ||
|
|
||
| Vector3 e = target - eePos; | ||
| error = math::VectorNorm(e); | ||
|
|
||
| if (error < config.tolerance) | ||
| return { q, error, iter, true }; | ||
|
|
||
| Jacobian J = ComputeJacobian(links, q, positions); | ||
|
|
||
| math::SquareMatrix<T, 3> JJt{}; | ||
| for (std::size_t r = 0; r < 3; ++r) | ||
| for (std::size_t c = 0; c < 3; ++c) | ||
| { | ||
| T sum = T(0); | ||
| for (std::size_t k = 0; k < NumLinks; ++k) | ||
|
Check failure on line 112 in numerical/kinematics/InverseKinematics.hpp
|
||
| sum += J.at(r, k) * J.at(c, k); | ||
| JJt.at(r, c) = sum; | ||
| } | ||
|
|
||
| T lambda2 = config.dampingFactor * config.dampingFactor; | ||
| JJt.at(0, 0) += lambda2; | ||
| JJt.at(1, 1) += lambda2; | ||
| JJt.at(2, 2) += lambda2; | ||
|
|
||
| Vector3 y = solver.Solve(JJt, e); | ||
|
|
||
| for (std::size_t i = 0; i < NumLinks; ++i) | ||
| { | ||
| T dq = T(0); | ||
| for (std::size_t r = 0; r < 3; ++r) | ||
| dq += J.at(r, i) * y.at(r, 0); | ||
| q.at(i, 0) += dq; | ||
| } | ||
| } | ||
|
|
||
| auto positions = fk.Compute(links, q); | ||
| Vector3 e = target - positions[NumLinks]; | ||
| error = math::VectorNorm(e); | ||
|
|
||
| return { q, error, iter, false }; | ||
| } | ||
|
|
||
| template<typename T, std::size_t NumLinks> | ||
| typename InverseKinematics<T, NumLinks>::Jacobian | ||
| InverseKinematics<T, NumLinks>::ComputeJacobian( | ||
| const LinkArray& links, | ||
| const JointVector& q, | ||
| const PositionArray& positions) const | ||
| { | ||
| const Vector3& eePos = positions[NumLinks]; | ||
|
|
||
| Matrix3 R = Matrix3::Identity(); | ||
| Jacobian J{}; | ||
|
|
||
| for (std::size_t i = 0; i < NumLinks; ++i) | ||
| { | ||
| Vector3 worldAxis = R * links[i].jointAxis; | ||
| Vector3 jointToEe = eePos - positions[i]; | ||
| Vector3 col = math::CrossProduct(worldAxis, jointToEe); | ||
|
|
||
| J.at(0, i) = col.at(0, 0); | ||
| J.at(1, i) = col.at(1, 0); | ||
| J.at(2, i) = col.at(2, 0); | ||
|
|
||
| R = R * math::RotationAboutAxis(links[i].jointAxis, q.at(i, 0)); | ||
| } | ||
|
|
||
| return J; | ||
| } | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| extern template class InverseKinematics<float, 1>; | ||
| extern template class InverseKinematics<float, 2>; | ||
| extern template class InverseKinematics<float, 3>; | ||
| #endif | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.