diff --git a/doc/kinematics/InverseKinematics.md b/doc/kinematics/InverseKinematics.md new file mode 100644 index 00000000..307a871d --- /dev/null +++ b/doc/kinematics/InverseKinematics.md @@ -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` 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. diff --git a/doc/kinematics/README.md b/doc/kinematics/README.md index 4d9e015c..4393d6fa 100644 --- a/doc/kinematics/README.md +++ b/doc/kinematics/README.md @@ -4,6 +4,7 @@ Geometry and motion algorithms for serial kinematic chains. ## Algorithms -| Algorithm | Description | -|--------------------------------------------|-------------------------------------------------------------------------------------| -| [Forward Kinematics](ForwardKinematics.md) | Computes 3D joint positions from joint angles for serial chains — $O(n)$ complexity | +| Algorithm | Description | +|--------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| [Forward Kinematics](ForwardKinematics.md) | Computes 3D joint positions from joint angles for serial chains — $O(n)$ complexity | +| [Inverse Kinematics](InverseKinematics.md) | Solves joint angles from a target end-effector position via Damped Least Squares — $O(k \cdot n)$ iterative | diff --git a/numerical/kinematics/CMakeLists.txt b/numerical/kinematics/CMakeLists.txt index c5776621..effff4f2 100644 --- a/numerical/kinematics/CMakeLists.txt +++ b/numerical/kinematics/CMakeLists.txt @@ -8,14 +8,17 @@ target_include_directories(numerical.kinematics ${NUMERICAL_VISIBILITY} target_link_libraries(numerical.kinematics ${NUMERICAL_VISIBILITY} numerical.dynamics numerical.math + numerical.solver ) target_sources(numerical.kinematics PRIVATE ForwardKinematics.hpp + InverseKinematics.hpp ) numerical_add_coverage_sources(numerical.kinematics ForwardKinematics.cpp + InverseKinematics.cpp ) add_subdirectory(test) diff --git a/numerical/kinematics/InverseKinematics.cpp b/numerical/kinematics/InverseKinematics.cpp new file mode 100644 index 00000000..dbefe127 --- /dev/null +++ b/numerical/kinematics/InverseKinematics.cpp @@ -0,0 +1,8 @@ +#include "numerical/kinematics/InverseKinematics.hpp" + +namespace kinematics +{ + template class InverseKinematics; + template class InverseKinematics; + template class InverseKinematics; +} diff --git a/numerical/kinematics/InverseKinematics.hpp b/numerical/kinematics/InverseKinematics.hpp new file mode 100644 index 00000000..db346739 --- /dev/null +++ b/numerical/kinematics/InverseKinematics.hpp @@ -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 +#include +#include + +namespace kinematics +{ + template + struct InverseKinematicsConfig + { + static_assert(std::is_floating_point_v, + "InverseKinematicsConfig only supports floating-point types"); + + T dampingFactor = T(0.1); + T tolerance = T(1e-4); + std::size_t maxIterations = 100; + }; + + template + struct InverseKinematicsResult + { + math::Vector q; + T finalError; + std::size_t iterations; + bool converged; + }; + + template + class InverseKinematics + { + static_assert(std::is_floating_point_v, + "InverseKinematics only supports floating-point types"); + static_assert(NumLinks > 0, "Number of links must be positive"); + + public: + using Vector3 = math::Vector3; + using Matrix3 = math::Matrix3; + using JointVector = math::Vector; + using Jacobian = math::Matrix; + using LinkArray = std::array, NumLinks>; + using PositionArray = std::array; + + explicit InverseKinematics(InverseKinematicsConfig cfg = {}); + + OPTIMIZE_FOR_SPEED InverseKinematicsResult 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 config; + ForwardKinematics fk; + mutable solvers::GaussianElimination solver; + }; + + template + InverseKinematics::InverseKinematics(InverseKinematicsConfig cfg) + : config(cfg) + { + really_assert(config.dampingFactor > T(0)); + really_assert(config.tolerance > T(0)); + } + + template + OPTIMIZE_FOR_SPEED + InverseKinematicsResult + InverseKinematics::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 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) + 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 InverseKinematics::Jacobian + InverseKinematics::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; + extern template class InverseKinematics; + extern template class InverseKinematics; +#endif +} diff --git a/numerical/kinematics/test/CMakeLists.txt b/numerical/kinematics/test/CMakeLists.txt index 030eb5bb..8a618827 100644 --- a/numerical/kinematics/test/CMakeLists.txt +++ b/numerical/kinematics/test/CMakeLists.txt @@ -9,4 +9,5 @@ target_link_libraries(numerical.kinematics_test PUBLIC target_sources(numerical.kinematics_test PRIVATE TestForwardKinematics.cpp + TestInverseKinematics.cpp ) diff --git a/numerical/kinematics/test/TestInverseKinematics.cpp b/numerical/kinematics/test/TestInverseKinematics.cpp new file mode 100644 index 00000000..3937c109 --- /dev/null +++ b/numerical/kinematics/test/TestInverseKinematics.cpp @@ -0,0 +1,270 @@ +#include "numerical/kinematics/ForwardKinematics.hpp" +#include "numerical/kinematics/InverseKinematics.hpp" +#include +#include +#include + +namespace +{ + constexpr float tolerance = 1e-3f; + constexpr float pi = std::numbers::pi_v; + + dynamics::RevoluteJointLink MakeLink(float mass, float length, + const math::Vector& axis, + const math::Vector& parentToJoint, + const math::Vector& jointToCoM) + { + float I = mass * length * length / 12.0f; + + return dynamics::RevoluteJointLink{ + mass, + math::SquareMatrix{ + { I, 0.0f, 0.0f }, + { 0.0f, I, 0.0f }, + { 0.0f, 0.0f, I } }, + axis, + parentToJoint, + jointToCoM + }; + } + + dynamics::RevoluteJointLink MakePlanarLink(float mass, float length, + const math::Vector& parentToJoint) + { + return MakeLink(mass, length, + math::Vector{ 0.0f, 0.0f, 1.0f }, + parentToJoint, + math::Vector{ length / 2.0f, 0.0f, 0.0f }); + } + + class TestInverseKinematics : public ::testing::Test + { + protected: + kinematics::InverseKinematics ik1; + kinematics::InverseKinematics ik2; + kinematics::InverseKinematics ik3; + kinematics::ForwardKinematics fk1; + kinematics::ForwardKinematics fk2; + kinematics::ForwardKinematics fk3; + }; +} + +TEST_F(TestInverseKinematics, single_link_reaches_target_on_arc) +{ + float length = 1.0f; + auto link = MakePlanarLink(1.0f, length, math::Vector{}); + std::array, 1> links = { link }; + + math::Vector referenceQ{ pi / 3.0f }; + auto fkRef = fk1.Compute(links, referenceQ); + math::Vector target = fkRef[1]; + + math::Vector initialQ{ 0.0f }; + auto result = ik1.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + EXPECT_NEAR(result.q.at(0, 0), pi / 3.0f, 1e-3f); + + auto positions = fk1.Compute(links, result.q); + EXPECT_NEAR(positions[1].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[1].at(1, 0), target.at(1, 0), tolerance); + EXPECT_NEAR(positions[1].at(2, 0), target.at(2, 0), tolerance); +} + +TEST_F(TestInverseKinematics, starts_at_solution_converges_immediately) +{ + float length = 1.0f; + auto link = MakePlanarLink(1.0f, length, math::Vector{}); + std::array, 1> links = { link }; + + math::Vector initialQ{ pi / 4.0f }; + auto fkPositions = fk1.Compute(links, initialQ); + math::Vector target = fkPositions[1]; + + auto result = ik1.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + EXPECT_LT(result.iterations, 2u); + EXPECT_LT(result.finalError, 1e-4f); +} + +TEST_F(TestInverseKinematics, two_link_planar_reaches_known_position) +{ + float l1 = 1.0f, l2 = 0.8f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.8f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ 0.0f, 0.0f }; + math::Vector target{ 0.5f, 1.0f, 0.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk2.Compute(links, result.q); + EXPECT_NEAR(positions[2].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[2].at(1, 0), target.at(1, 0), tolerance); + EXPECT_NEAR(positions[2].at(2, 0), target.at(2, 0), tolerance); +} + +TEST_F(TestInverseKinematics, two_link_planar_fully_extended) +{ + float l1 = 1.0f, l2 = 0.5f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.5f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ 0.1f, 0.1f }; + math::Vector target{ l1 + l2 - 0.05f, 0.0f, 0.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk2.Compute(links, result.q); + EXPECT_NEAR(positions[2].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[2].at(1, 0), 0.0f, tolerance); +} + +TEST_F(TestInverseKinematics, two_link_planar_folded_elbow_up) +{ + float l1 = 1.0f, l2 = 0.8f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.8f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ pi / 4.0f, -pi / 4.0f }; + math::Vector target{ 1.2f, 0.5f, 0.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk2.Compute(links, result.q); + EXPECT_NEAR(positions[2].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[2].at(1, 0), target.at(1, 0), tolerance); +} + +TEST_F(TestInverseKinematics, unreachable_target_does_not_converge) +{ + float l1 = 1.0f, l2 = 0.5f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.5f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ 0.0f, 0.0f }; + math::Vector target{ 10.0f, 10.0f, 10.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_FALSE(result.converged); + EXPECT_GT(result.finalError, 1e-4f); + EXPECT_EQ(result.iterations, 100u); +} + +TEST_F(TestInverseKinematics, result_contains_populated_iteration_count_and_error) +{ + float l1 = 1.0f, l2 = 0.8f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.8f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ 0.0f, 0.0f }; + math::Vector target{ 0.5f, 1.0f, 0.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_GT(result.iterations, 0u); + EXPECT_LT(result.finalError, 1e-4f); +} + +TEST_F(TestInverseKinematics, custom_damping_factor_still_converges) +{ + float l1 = 1.0f, l2 = 0.8f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.8f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + kinematics::InverseKinematicsConfig cfg; + cfg.dampingFactor = 0.5f; + cfg.tolerance = 1e-4f; + cfg.maxIterations = 500; + kinematics::InverseKinematics ikHighDamping{ cfg }; + + math::Vector initialQ{ 0.0f, 0.0f }; + math::Vector target{ 0.5f, 1.0f, 0.0f }; + + auto result = ikHighDamping.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk2.Compute(links, result.q); + EXPECT_NEAR(positions[2].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[2].at(1, 0), target.at(1, 0), tolerance); +} + +TEST_F(TestInverseKinematics, three_link_spatial_reaches_target) +{ + float l1 = 0.5f, l2 = 0.4f, l3 = 0.3f; + + auto link1 = MakeLink(1.0f, l1, + math::Vector{ 0.0f, 0.0f, 1.0f }, + math::Vector{}, + math::Vector{ l1 / 2.0f, 0.0f, 0.0f }); + auto link2 = MakeLink(0.8f, l2, + math::Vector{ 0.0f, 1.0f, 0.0f }, + math::Vector{ l1, 0.0f, 0.0f }, + math::Vector{ l2 / 2.0f, 0.0f, 0.0f }); + auto link3 = MakeLink(0.6f, l3, + math::Vector{ 0.0f, 1.0f, 0.0f }, + math::Vector{ l2, 0.0f, 0.0f }, + math::Vector{ l3 / 2.0f, 0.0f, 0.0f }); + std::array, 3> links = { link1, link2, link3 }; + + kinematics::InverseKinematicsConfig cfg; + cfg.dampingFactor = 0.05f; + cfg.tolerance = 1e-4f; + cfg.maxIterations = 300; + kinematics::InverseKinematics ik3Spatial{ cfg }; + + math::Vector referenceQ{ pi / 4.0f, pi / 6.0f, -pi / 3.0f }; + auto fkRef = fk3.Compute(links, referenceQ); + math::Vector target = fkRef[3]; + + math::Vector initialQ{ 0.0f, 0.0f, 0.0f }; + auto result = ik3Spatial.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk3.Compute(links, result.q); + EXPECT_NEAR(positions[3].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[3].at(1, 0), target.at(1, 0), tolerance); + EXPECT_NEAR(positions[3].at(2, 0), target.at(2, 0), tolerance); +} + +TEST_F(TestInverseKinematics, two_link_target_at_origin_region) +{ + float l1 = 1.0f, l2 = 0.8f; + + auto link1 = MakePlanarLink(1.0f, l1, math::Vector{}); + auto link2 = MakePlanarLink(0.8f, l2, math::Vector{ l1, 0.0f, 0.0f }); + std::array, 2> links = { link1, link2 }; + + math::Vector initialQ{ pi / 3.0f, -2.0f * pi / 3.0f }; + math::Vector target{ 0.4f, 0.0f, 0.0f }; + + auto result = ik2.Solve(links, target, initialQ); + + EXPECT_TRUE(result.converged); + + auto positions = fk2.Compute(links, result.q); + EXPECT_NEAR(positions[2].at(0, 0), target.at(0, 0), tolerance); + EXPECT_NEAR(positions[2].at(1, 0), target.at(1, 0), tolerance); +} diff --git a/numerical/math/Geometry3D.hpp b/numerical/math/Geometry3D.hpp index b2c4d269..b3e9be86 100644 --- a/numerical/math/Geometry3D.hpp +++ b/numerical/math/Geometry3D.hpp @@ -76,4 +76,16 @@ namespace math result.at(r, c) = a.at(r, 0) * b.at(c, 0); return result; } + + template + ALWAYS_INLINE_HOT T DotProduct(const Vector3& a, const Vector3& b) + { + return a.at(0, 0) * b.at(0, 0) + a.at(1, 0) * b.at(1, 0) + a.at(2, 0) * b.at(2, 0); + } + + template + ALWAYS_INLINE_HOT T VectorNorm(const Vector3& v) + { + return std::sqrt(DotProduct(v, v)); + } }