Skip to content

Commit 7cb9827

Browse files
feat(kinematics): pick the nearest IK solution within the joint limits (#48)
* feat(kinematics): pick the nearest IK solution within the joint limits NearestSolution takes a solver's candidate set, wraps each revolute joint a full turn either way into its limits, and keeps the candidate nearest the current joints. It reports found, outsideLimits (a candidate exists but none fits the limits) or unreachable (no candidate). WrapIntoLimits does the per-candidate step. AnalyticalIkOpw::SolveNearest applies it to the eight OPW configurations, so streaming poses stay on the present branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014WUWh8Fw5EhcfvNuXz3jjU * fix(kinematics): cover the tested sizes and keep the README within 400 columns The coverage build only instantiated NearestSolution<float, 6, 8>, so the branches the two-joint tests exercise were not measured (86.5 % on new code); instantiate the tested sizes too, with qualified names so no empty namespace remains. Shorten the root README entry so the table stays within markdownlint's 400-column limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014WUWh8Fw5EhcfvNuXz3jjU --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5368191 commit 7cb9827

11 files changed

Lines changed: 303 additions & 9 deletions

‎README.md‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,15 @@ project already defines those targets. Includes are namespaced by domain, e.g.
3535

3636
## Documentation
3737

38-
| Category | Description |
39-
|--------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
40-
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics, Chain Pose Kinematics, Denavit-Hartenberg Parameters, Geometric Jacobian, Manipulability Index, Product of Exponentials, Redundancy Resolution, Inverse Kinematics (DLS), Pose Inverse Kinematics, Analytical IK (OPW), Continuum Kinematics, Parallel Manipulator Kinematics, Mobile-Manipulator Kinematics |
41-
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler (RNEA), Articulated Body Algorithm (ABA), Chain Dynamics Model, Composite Rigid Body Algorithm (CRBA), Coriolis Matrix and Inertial Regressor, Dynamic Parameter Identification, Forward-Dynamics Integration, Generic Joint Link, Generalized-Momentum Observer |
42-
| [Planning](doc/planning/README.md) | Primitive Distance Queries, Artificial Potential Fields, Self-Collision Checking, Convex Collision (GJK and EPA), Grid Search (A* and Dijkstra), RRT-Connect, Dubins Shortest Paths, Dynamic Window Approach, Reeds–Shepp Shortest Paths |
43-
| [Trajectory](doc/trajectory/README.md) | Cubic Spline Trajectory, Cartesian Path with SLERP Orientation, Time-Optimal Path Parameterization (TOPP-RA) |
44-
| [Mobile Robots](doc/mobile/README.md) | Planar Odometry, Differential-Drive Kinematics, Car-Like Kinematics, Omnidirectional Kinematics, Skid-Steer Kinematics, Pure-Pursuit Path Tracking, Kanayama Trajectory Tracking, Stanley Path Tracking |
45-
| [Localization & Mapping](doc/localization/README.md) | Occupancy-Grid Mapping, Odometry Fusion, EKF Landmark Localization, 2-D Scan Matching (ICP), Monte Carlo Localization |
46-
| [Manipulator Control](doc/controllers/manipulator/README.md) | PD Control with Gravity Compensation, Computed-Torque Control, Impedance Control, Operational-Space Control, Hybrid Position/Force Control, Slotine–Li Adaptive Control, Cable Tension Distribution |
38+
| Category | Description |
39+
|--------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
40+
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics, Chain Pose Kinematics, Denavit-Hartenberg Parameters, Geometric Jacobian, Manipulability Index, Product of Exponentials, Redundancy Resolution, Inverse Kinematics (DLS), Pose Inverse Kinematics, Analytical IK (OPW), Nearest IK, Continuum Kinematics, Parallel Manipulator Kinematics, Mobile-Manipulator Kinematics |
41+
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler (RNEA), Articulated Body Algorithm (ABA), Chain Dynamics Model, Composite Rigid Body Algorithm (CRBA), Coriolis Matrix and Inertial Regressor, Dynamic Parameter Identification, Forward-Dynamics Integration, Generic Joint Link, Generalized-Momentum Observer |
42+
| [Planning](doc/planning/README.md) | Primitive Distance Queries, Artificial Potential Fields, Self-Collision Checking, Convex Collision (GJK and EPA), Grid Search (A* and Dijkstra), RRT-Connect, Dubins Shortest Paths, Dynamic Window Approach, Reeds–Shepp Shortest Paths |
43+
| [Trajectory](doc/trajectory/README.md) | Cubic Spline Trajectory, Cartesian Path with SLERP Orientation, Time-Optimal Path Parameterization (TOPP-RA) |
44+
| [Mobile Robots](doc/mobile/README.md) | Planar Odometry, Differential-Drive Kinematics, Car-Like Kinematics, Omnidirectional Kinematics, Skid-Steer Kinematics, Pure-Pursuit Path Tracking, Kanayama Trajectory Tracking, Stanley Path Tracking |
45+
| [Localization & Mapping](doc/localization/README.md) | Occupancy-Grid Mapping, Odometry Fusion, EKF Landmark Localization, 2-D Scan Matching (ICP), Monte Carlo Localization |
46+
| [Manipulator Control](doc/controllers/manipulator/README.md) | PD Control with Gravity Compensation, Computed-Torque Control, Impedance Control, Operational-Space Control, Hybrid Position/Force Control, Slotine–Li Adaptive Control, Cable Tension Distribution |
4747

4848
Each category page lists its algorithms with a brief description and links to the detailed
4949
documentation.

‎doc/kinematics/AnalyticalIkOpw.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ A KUKA KR6 R700 sixx has $a_1 = 0.025$, $a_2 = -0.035$, $b = 0$, $c_1 = 0.400$,
8686

8787
## Connections to Other Algorithms
8888

89+
- [Nearest Inverse-Kinematics Solution](NearestSolution.md): picks, among the eight candidates, the one within the joint limits nearest the current joints.
8990
- [Pose Inverse Kinematics](PoseInverseKinematics.md): the iterative alternative for arbitrary geometries.
9091
- [Denavit-Hartenberg Parameters](DenavitHartenberg.md): the frame-based description that OPW avoids.
9192
- [Manipulability Index](ManipulabilityIndex.md): measures how close each returned configuration is to a singularity.

‎doc/kinematics/NearestSolution.md‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# Nearest Inverse-Kinematics Solution
2+
3+
## Overview & Motivation
4+
5+
A closed-form inverse-kinematics solver returns every joint configuration that reaches a pose: up to eight for an ortho-parallel arm with a spherical wrist. A controller can use only one. Two facts decide which:
6+
7+
- **Joint limits.** A solution the joints cannot reach is no solution at all. Revolute solvers return angles wrapped to $(-\pi, \pi]$, but a joint that turns further than half a revolution reaches the same pose at $\theta \pm 2\pi$, and that equivalent angle may be the one inside the limits.
8+
- **Continuity.** Streaming poses along a line or a jog calls the solver every control period. Picking the solution nearest the current joints keeps the arm on its present branch, so it never flips elbow or wrist between two samples.
9+
10+
The selection turns the solver's candidate set into one joint vector, or a reason why there is none.
11+
12+
## Mathematical Theory
13+
14+
### Equivalent Angles Within the Limits
15+
16+
For a revolute joint $j$ with limits $[q_{j,\min}, q_{j,\max}]$, a candidate angle $\theta_j$ has the equivalents
17+
18+
$$\theta_j + 2\pi k, \qquad k \in \{0, +1, -1\}$$
19+
20+
Among those inside the limits, the one closest to the current angle $q_j$ is kept:
21+
22+
$$\tilde{\theta}_j = \arg\min_{k \,:\, q_{j,\min} \le \theta_j + 2\pi k \le q_{j,\max}} \left| \theta_j + 2\pi k - q_j \right|$$
23+
24+
If no equivalent lies inside the limits, the candidate is rejected. One turn either way covers every joint whose range spans at most three revolutions.
25+
26+
### Nearest Candidate
27+
28+
Each candidate that survives the wrapping is compared with the current joints by squared Euclidean distance in joint space:
29+
30+
$$d = \lVert \tilde{\theta} - q \rVert^2$$
31+
32+
The candidate with the smallest $d$ is the result. The outcome is one of three:
33+
34+
| Outcome | Meaning |
35+
|----------------|-----------------------------------------------------------------------|
36+
| Found | At least one candidate fits the limits; the nearest is returned |
37+
| Outside limits | The pose is reachable, but every candidate leaves some joint's limits |
38+
| Unreachable | The solver returned no candidate at all |
39+
40+
The distinction matters to a caller: an unreachable pose is a planning error, while a pose outside the limits may be reachable with another tool orientation or with wider limits.
41+
42+
## Complexity Analysis
43+
44+
| Case | Time | Space | Notes |
45+
|------|-------------|--------|---------------------------------------------------------------|
46+
| Any | $O(c \, n)$ | $O(n)$ | $c$ candidates, $n$ joints, three equivalents tried per joint |
47+
48+
For an OPW arm, $c = 8$ and $n = 6$: at most 144 limit checks and eight distances.
49+
50+
## Step-by-Step Walkthrough
51+
52+
Two joints, limits $[-4, 4]$ rad on both, current joints $q = (3.0, 0)$, and one candidate $\theta = (-3.0, 0)$.
53+
54+
1. Joint 1: the equivalents are $-3.0$, $3.283$ and $-9.283$. The first two are inside the limits; $3.283$ is $0.283$ from the current $3.0$, against $6.0$ for $-3.0$. Keep $3.283$.
55+
2. Joint 2: $0$ is inside the limits and equal to the current angle. Keep $0$.
56+
3. The wrapped candidate is $(3.283, 0)$ at squared distance $0.080$. It is the only candidate, so it is the result.
57+
58+
Without the wrapping the arm would swing joint 1 through $6$ rad to reach the same pose.
59+
60+
## Pitfalls & Edge Cases
61+
62+
- **Revolute joints only**: the $2\pi$ shift assumes the joint is periodic. A prismatic joint must not be shifted; pass its candidate unchanged.
63+
- **Distance in mixed units**: squared joint distance weighs every joint equally. Joints whose motion is costlier, such as a heavy shoulder, may deserve a weighted metric.
64+
- **Singular wrist**: at a wrist singularity the solver fixes one wrist angle by convention. The nearest solution then keeps that convention; it does not search the free combination of the two wrist joints.
65+
- **Limits at exactly $\pm\pi$**: a candidate on the boundary is inside; the comparison is inclusive.
66+
67+
## Variants & Generalizations
68+
69+
- **Weighted distance**: $d = (\tilde{\theta} - q)^T W (\tilde{\theta} - q)$ with a diagonal $W$ of joint costs.
70+
- **More turns**: joints with a range beyond three revolutions need $k \in \{-2, \dots, 2\}$ or the closed-form $k = \operatorname{round}((q_j - \theta_j) / 2\pi)$ clamped into the limits.
71+
- **Branch locking**: keep the solver's configuration flags (shoulder, elbow, wrist) and choose only among candidates with the same flags.
72+
73+
## Applications
74+
75+
- Streaming Cartesian lines and jogs: one solve and one selection per control period.
76+
- Point-to-point moves to a Cartesian target from the present joints.
77+
- Reachability checks that tell an unreachable pose apart from one blocked by the joint limits.
78+
79+
## Connections to Other Algorithms
80+
81+
- [Analytical Inverse Kinematics (OPW)](AnalyticalIkOpw.md): supplies the eight candidates; its nearest solve applies this selection.
82+
- [Pose Inverse Kinematics](PoseInverseKinematics.md): an iterative solver that starts from the current joints and so stays near them by construction.
83+
- [Generic Joint Link](../dynamics/JointLink.md): carries the joint limits used here.
84+
85+
## References & Further Reading
86+
87+
- M. Brandstötter, A. Angerer, M. Hofbaur, "An Analytical Solution of the Inverse Kinematics Problem of Industrial Serial Manipulators with an Ortho-parallel Basis and a Spherical Wrist," Austrian Robotics Workshop, 2014.
88+
- B. Siciliano, L. Sciavicco, L. Villani, G. Oriolo, *Robotics: Modelling, Planning and Control*, Springer, 2009, §2.12.

‎doc/kinematics/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ Geometry and motion algorithms for serial kinematic chains.
1919
| [Inverse Kinematics](InverseKinematics.md) | Solves joint angles that place the tool point on a target via Damped Least Squares — $O(k \cdot n)$ iterative |
2020
| [Pose Inverse Kinematics](PoseInverseKinematics.md) | Full 6-DoF pose IK: damped least squares on the weighted log-map pose error with manipulability-adaptive damping, step clamping and joint limits |
2121
| [Analytical Inverse Kinematics (OPW)](AnalyticalIkOpw.md) | Closed-form IK for ortho-parallel 6R arms with a spherical wrist: all eight configurations in constant time, with wrist-singularity handling |
22+
| [Nearest Inverse-Kinematics Solution](NearestSolution.md) | Picks the candidate within the joint limits, a full turn either way, nearest the current joints, or reports why none fits |

‎robotics/kinematics/AnalyticalIkOpw.hpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "numerical/math/Math.hpp"
66
#include "numerical/math/Matrix.hpp"
77
#include "numerical/math/SE3Transform.hpp"
8+
#include "robotics/kinematics/NearestSolution.hpp"
89
#include <algorithm>
910
#include <array>
1011
#include <cstddef>
@@ -56,6 +57,7 @@ namespace kinematics
5657

5758
OPTIMIZE_FOR_SPEED OpwSolutions<T> Solve(const math::SE3Transform<T>& flange) const;
5859
math::SE3Transform<T> Forward(const JointVector& q) const;
60+
NearestSolutionResult<T, 6> SolveNearest(const math::SE3Transform<T>& flange, const JointVector& current, const JointLimitArray<T, 6>& limits) const;
5961

6062
private:
6163
using Matrix3 = math::Matrix3<T>;
@@ -147,6 +149,17 @@ namespace kinematics
147149
return solutions;
148150
}
149151

152+
template<typename T>
153+
NearestSolutionResult<T, 6> AnalyticalIkOpw<T>::SolveNearest(const math::SE3Transform<T>& flange, const JointVector& current, const JointLimitArray<T, 6>& limits) const
154+
{
155+
const auto solutions{ Solve(flange) };
156+
std::array<std::optional<JointVector>, 8> candidates{};
157+
for (std::size_t slot = 0; slot < solutions.size(); ++slot)
158+
if (solutions[slot].has_value())
159+
candidates[slot] = solutions[slot]->q;
160+
return NearestSolution(candidates, current, limits);
161+
}
162+
150163
template<typename T>
151164
math::SE3Transform<T> AnalyticalIkOpw<T>::Forward(const JointVector& q) const
152165
{

‎robotics/kinematics/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ target_sources(robotics.kinematics PRIVATE
2626
JacobianProvider.hpp
2727
ManipulabilityIndex.hpp
2828
MobileManipulatorKinematics.hpp
29+
NearestSolution.hpp
2930
PoseInverseKinematics.hpp
3031
ProductOfExponentials.hpp
3132
RedundancyResolution.hpp
@@ -43,6 +44,7 @@ robotics_add_coverage_sources(robotics.kinematics
4344
InverseKinematics.cpp
4445
ManipulabilityIndex.cpp
4546
MobileManipulatorKinematics.cpp
47+
NearestSolution.cpp
4648
PoseInverseKinematics.cpp
4749
ProductOfExponentials.cpp
4850
RedundancyResolution.cpp
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include "robotics/kinematics/NearestSolution.hpp"
2+
3+
template std::optional<math::Vector<float, 2>> kinematics::WrapIntoLimits<float, 2>(const math::Vector<float, 2>&, const math::Vector<float, 2>&,
4+
const kinematics::JointLimitArray<float, 2>&);
5+
template std::optional<math::Vector<float, 6>> kinematics::WrapIntoLimits<float, 6>(const math::Vector<float, 6>&, const math::Vector<float, 6>&,
6+
const kinematics::JointLimitArray<float, 6>&);
7+
template kinematics::NearestSolutionResult<float, 2> kinematics::NearestSolution<float, 2, 3>(const std::array<std::optional<math::Vector<float, 2>>, 3>&,
8+
const math::Vector<float, 2>&, const kinematics::JointLimitArray<float, 2>&);
9+
template kinematics::NearestSolutionResult<float, 6> kinematics::NearestSolution<float, 6, 8>(const std::array<std::optional<math::Vector<float, 6>>, 8>&,
10+
const math::Vector<float, 6>&, const kinematics::JointLimitArray<float, 6>&);

0 commit comments

Comments
 (0)