Algorithm Search⌘K

Algorithmcore

Damped least squares inverse kinematics

Also called DLS inverse kinematics, Wampler's method.

Uses the step J^T (J J^T + l^2 I)^-1 e, which stays bounded near singularities at the cost of some tracking error.

Time
Θ(k m^2 n) worst
Space
Θ(m n) extra
Where
k = the number of iterations; m = the number of task coordinates; n = the number of joints with m at most n
Properties
deterministicofflineiterative
Origin
Charles W. Wampler, Yoshihiko Nakamura, Hideo Hanafusa, 1986

Damped least squares inverse kinematics moves the joints of an arm toward a target with the step Δθ=JT(JJT+λ2I)−1e\Delta\theta = J^{\mathsf T}(JJ^{\mathsf T} + \lambda^2I)^{-1}e, where JJ is the Jacobian and ee is the task error. The damping factor λ>0\lambda > 0 makes the matrix JJT+λ2IJJ^{\mathsf T} + \lambda^2I invertible at every configuration, also at a kinematic singularity. The step is never longer than ∣e∣/(2λ)|e|/(2\lambda), so the joints do not jump near a singularity, as they do with the pseudoinverse. The price is that one step does not remove the whole error, even where the pseudoinverse step would. The step is the Tikhonov regularization of the linear least squares problem JΔθ≈eJ\Delta\theta \approx e.

In plain words

To move the hand of an arm toward a target, you need to know how much to turn each joint. At some poses of the arm, a tiny motion of the hand needs a huge turn of the joints, for example when the arm is almost straight and the target is a little farther out. A method that insists on the exact motion then asks for wild joint motions. Damped least squares asks for a compromise instead. It looks for a joint motion that brings the hand close to where it should go, but it also pays a penalty for every large joint motion. Far from such poses, the penalty hardly matters, and the result is almost the exact motion. Near them, the penalty wins, and the joints move only a little. Repeating such steps brings the hand to the target, if it can be reached.

The problem

Input.

  • A task map x=f(θ)x = f(\theta) from nn joint values to mm task coordinates, with m≤nm \le n, and its Jacobian J(θ)J(\theta), an m×nm \times n matrix. For a full pose, ee is a twist error and JJ is the matching geometric Jacobian, as in Newton-Raphson inverse kinematics.
  • A target xdx_d, an initial guess θ0\theta^0, a damping factor λ>0\lambda > 0, a tolerance ε\varepsilon and a step limit kmax⁡k_{\max}.

Output. A θ\theta with ∣xd−f(θ)∣≤ε|x_d - f(\theta)| \le \varepsilon, or the last iterate with the report that the tolerance was not met. For a target out of reach, the last iterate is the useful answer, often an arm stretched toward the target.

One step. For a fixed JJ and ee, the damped least squares step is the unique minimizer of

ϕ(Δθ)=∣JΔθ−e∣2+λ2∣Δθ∣2.\phi(\Delta\theta) = |J\Delta\theta - e|^2 + \lambda^2|\Delta\theta|^2.

The algorithm

  1. DLS-IK(f, J, x_d, θ0, λ, ε, k_max)
  2. 1θ ← θ0
  3. 2for k ← 1 to k_max
  4. 3e ← x_d - f(θ)
  5. 4if |e| ≤ ε then return θ
  6. 5J ← JACOBIAN(θ)
  7. 6solve (J J^T + λ^2 I) y = e ▷ an m by m system, positive definite
  8. 7Δθ ← J^T y
  9. 8θ ← θ + Δθ
  10. 9return θ with the report that the tolerance was not met

Lines L6 and L7 can also be written Δθ=(JTJ+λ2I)−1JTe\Delta\theta = (J^{\mathsf T}J + \lambda^2I)^{-1}J^{\mathsf T}e, an n×nn \times n system with the same result. Use the smaller of the two systems. With the singular value decomposition J=∑iσiuiviTJ = \sum_i \sigma_iu_iv_i^{\mathsf T}, the step is

Δθ=∑iσiσi2+λ2(uiTe) vi.\Delta\theta = \sum_i \frac{\sigma_i}{\sigma_i^2 + \lambda^2}(u_i^{\mathsf T}e)\,v_i.

The pseudoinverse uses the factor 1/σi1/\sigma_i, which grows without bound as σi→0\sigma_i \to 0. The damped factor σi/(σi2+λ2)\sigma_i/(\sigma_i^2 + \lambda^2) is close to 1/σi1/\sigma_i when σi≫λ\sigma_i \gg \lambda, goes to 0 when σi→0\sigma_i \to 0, and is at most 1/(2λ)1/(2\lambda), with equality at σi=λ\sigma_i = \lambda.

Example

All examples use the planar 2R arm with L1=L2=1L_1 = L_2 = 1 m, with the hand at (cos⁡θ1+cos⁡(θ1+θ2),sin⁡θ1+sin⁡(θ1+θ2))(\cos\theta_1 + \cos(\theta_1 + \theta_2), \sin\theta_1 + \sin(\theta_1 + \theta_2)).

One step near a singularity. At θ=(0,0.01)\theta = (0, 0.01) rad the arm is almost straight, the hand is at (1.999950,0.009999)(1.999950, 0.009999) m and det⁡J=0.0099998\det J = 0.0099998. For the target (1.9,0.2)(1.9, 0.2) m the error is e=(−0.099950,0.190000)e = (-0.099950, 0.190000) m, with ∣e∣=0.2147|e| = 0.2147 m.

step Δθ\Delta\theta (rad) ∣Δθ∣\lvert\Delta\theta\rvert (rad) residual ∣e−JΔθ∣\lvert e - J\Delta\theta\rvert (m)
exact solve J−1eJ^{-1}e (−9.804667,19.799833)(-9.804667, 19.799833) 22.09 0
DLS, λ=0.01\lambda = 0.01 (−1.570567,3.331712)(-1.570567, 3.331712) 3.683 0.0823
DLS, λ=0.1\lambda = 0.1 (0.056365,0.077488)(0.056365, 0.077488) 0.0958 0.0986
DLS, λ=0.5\lambda = 0.5 (0.071818,0.037885)(0.071818, 0.037885) 0.0812 0.0992

The exact step turns the elbow by almost 20 rad, which is useless, since the linear model is only valid for small steps. The damped steps are small and point the right way.

Iteration to a reachable target. For the target (1,1)(1, 1) m from θ0=(0.3,1.2)\theta^0 = (0.3, 1.2) rad, both damping factors end at the solution (0,π/2)(0, \pi/2).

λ\lambda errors (m) at steps 0 to 4 steps to 10−1010^{-10}
0.1 0.294, 0.0415, 0.00138, 3.45e-5, 8.8e-7 7
0.5 0.294, 0.123, 0.051, 0.0206, 0.00823 24

The convergence is linear. At the solution, JTJJ^{\mathsf T}J has the eigenvalues (3±5)/2(3 \pm \sqrt 5)/2, so the least singular value is σmin⁡=0.618\sigma_{\min} = 0.618. The proof page shows that the error ratio tends to λ2/(σmin⁡2+λ2)\lambda^2/(\sigma_{\min}^2 + \lambda^2), which is 0.0255 for λ=0.1\lambda = 0.1 and 0.396 for λ=0.5\lambda = 0.5, and these are the ratios that the iteration shows.

A target out of reach. For the target (2.5,0)(2.5, 0) m, which is beyond the reach of 2 m, start at (0.2,0.5)(0.2, 0.5) rad. With λ=0.5\lambda = 0.5, the errors are 1.132, 0.5404, 0.5021, 0.5001, and the arm stops stretched along the x axis, with the hand at (2,0)(2, 0), the nearest point to the target. With λ=0.1\lambda = 0.1, the iteration does not settle: the error jumps between about 0.51 and 1.48 m for as long as it runs, and every step still obeys the bound ∣Δθ∣≤∣e∣/(2λ)|\Delta\theta| \le |e|/(2\lambda). With λ=0.2\lambda = 0.2 it falls into a cycle of two bent poses, mirror images of each other, with the error 0.601 m. These are measured results on this one arm, not general rules.

Correctness

The proof page proves these facts for λ>0\lambda > 0.

  • The matrices JJT+λ2IJJ^{\mathsf T} + \lambda^2I and JTJ+λ2IJ^{\mathsf T}J + \lambda^2I are positive definite, so L6 always has one solution, and the two forms of the step are equal.
  • The step is the unique minimizer of ϕ\phi.
  • The step has the singular value form above, so ∣Δθ∣≤∣e∣/(2λ)|\Delta\theta| \le |e|/(2\lambda) for every JJ.
  • As λ→0\lambda \to 0, the step tends to the pseudoinverse step J+eJ^{+}e, for every JJ.
  • The residual after one linear step is e−JΔθ=λ2(JJT+λ2I)−1ee - J\Delta\theta = \lambda^2(JJ^{\mathsf T} + \lambda^2I)^{-1}e, which is not zero unless e=0e = 0. This is the tracking error that the damping costs.
  • If JJ has full row rank, the step is zero only when e=0e = 0, so the iteration can stop only at a solution.
  • If m=nm = n and J(θ∗)J(\theta^*) is invertible at a solution θ∗\theta^*, the iteration converges to θ∗\theta^* from every start close enough, and the error falls by a factor that tends to at most λ2/(σmin⁡2+λ2)<1\lambda^2/(\sigma_{\min}^2 + \lambda^2) < 1 per step.

There is no global guarantee. From a far start, or for a target out of reach, the iteration can cycle, as in the example.

Proof: The damped least squares step is the bounded minimizer of the damped objective, and the iteration converges linearly near a regular solutionfull

We use the notation of the page, in exact arithmetic, with λ>0\lambda > 0. JJ is an m×nm \times n real matrix, e∈Rme \in \mathbb R^m, and norms are Euclidean norms or the matching operator norms.

Claim 1. JJT+λ2IJJ^{\mathsf T} + \lambda^2I and JTJ+λ2IJ^{\mathsf T}J + \lambda^2I are symmetric positive definite, and

JT(JJT+λ2I)−1=(JTJ+λ2I)−1JT.J^{\mathsf T}(JJ^{\mathsf T} + \lambda^2I)^{-1} = (J^{\mathsf T}J + \lambda^2I)^{-1}J^{\mathsf T}.

Proof. For every y≠0y \ne 0, yT(JJT+λ2I)y=∣JTy∣2+λ2∣y∣2>0y^{\mathsf T}(JJ^{\mathsf T} + \lambda^2I)y = |J^{\mathsf T}y|^2 + \lambda^2|y|^2 > 0, and the same holds for the other matrix. The identity (JTJ+λ2I)JT=JT(JJT+λ2I)(J^{\mathsf T}J + \lambda^2I)J^{\mathsf T} = J^{\mathsf T}(JJ^{\mathsf T} + \lambda^2I) holds by expanding both sides. Multiply it on the left by (JTJ+λ2I)−1(J^{\mathsf T}J + \lambda^2I)^{-1} and on the right by (JJT+λ2I)−1(JJ^{\mathsf T} + \lambda^2I)^{-1}. □\square

So line L6 always has exactly one solution, and the two forms of the step on the page are equal.

Claim 2. The step Δθ=(JTJ+λ2I)−1JTe\Delta\theta = (J^{\mathsf T}J + \lambda^2I)^{-1}J^{\mathsf T}e is the unique minimizer of ϕ(x)=∣Jx−e∣2+λ2∣x∣2\phi(x) = |Jx - e|^2 + \lambda^2|x|^2.

Proof. ϕ(x)=xT(JTJ+λ2I)x−2eTJx+∣e∣2\phi(x) = x^{\mathsf T}(J^{\mathsf T}J + \lambda^2I)x - 2e^{\mathsf T}Jx + |e|^2 is a quadratic function with a positive definite Hessian 2(JTJ+λ2I)2(J^{\mathsf T}J + \lambda^2I), so it is strictly convex. Its gradient 2(JTJ+λ2I)x−2JTe2(J^{\mathsf T}J + \lambda^2I)x - 2J^{\mathsf T}e is zero exactly at Δθ\Delta\theta. □\square

Claim 3. Let J=∑i=1rσiuiviTJ = \sum_{i=1}^r \sigma_iu_iv_i^{\mathsf T} be a singular value decomposition with σi>0\sigma_i > 0, orthonormal uiu_i and orthonormal viv_i. Then Δθ=∑iσiσi2+λ2(uiTe)vi\Delta\theta = \sum_i \frac{\sigma_i}{\sigma_i^2 + \lambda^2}(u_i^{\mathsf T}e)v_i and ∣Δθ∣≤∣e∣/(2λ)|\Delta\theta| \le |e|/(2\lambda).

Proof. Complete the viv_i to an orthonormal basis of Rn\mathbb R^n. In this basis JTJ+λ2IJ^{\mathsf T}J + \lambda^2I is diagonal, with σi2+λ2\sigma_i^2 + \lambda^2 on viv_i and λ2\lambda^2 on the other basis vectors. Since JTe=∑iσi(uiTe)viJ^{\mathsf T}e = \sum_i \sigma_i(u_i^{\mathsf T}e)v_i, applying the inverse gives the formula. By the inequality of the arithmetic and geometric means, σ2+λ2≥2σλ\sigma^2 + \lambda^2 \ge 2\sigma\lambda, so each factor is at most 1/(2λ)1/(2\lambda), with equality at σ=λ\sigma = \lambda. Then ∣Δθ∣2=∑i(σiσi2+λ2)2(uiTe)2≤14λ2∑i(uiTe)2≤∣e∣24λ2|\Delta\theta|^2 = \sum_i \bigl(\frac{\sigma_i}{\sigma_i^2 + \lambda^2}\bigr)^2(u_i^{\mathsf T}e)^2 \le \frac{1}{4\lambda^2}\sum_i(u_i^{\mathsf T}e)^2 \le \frac{|e|^2}{4\lambda^2}. □\square

The bound does not depend on JJ, so it holds at singular configurations too. It is reached when JJ has a singular value equal to λ\lambda and ee is along the matching uiu_i.

Claim 4. As λ→0\lambda \to 0, Δθ→J+e=∑i1σi(uiTe)vi\Delta\theta \to J^{+}e = \sum_i \frac{1}{\sigma_i}(u_i^{\mathsf T}e)v_i, for every JJ.

Proof. There are finitely many terms, and each factor σi/(σi2+λ2)\sigma_i/(\sigma_i^2 + \lambda^2) tends to 1/σi1/\sigma_i since σi>0\sigma_i > 0. □\square

Claim 5. e−JΔθ=λ2(JJT+λ2I)−1ee - J\Delta\theta = \lambda^2(JJ^{\mathsf T} + \lambda^2I)^{-1}e. In particular the residual is zero only when e=0e = 0.

Proof. With y=(JJT+λ2I)−1ey = (JJ^{\mathsf T} + \lambda^2I)^{-1}e, JΔθ=JJTy=(JJT+λ2I)y−λ2y=e−λ2yJ\Delta\theta = JJ^{\mathsf T}y = (JJ^{\mathsf T} + \lambda^2I)y - \lambda^2y = e - \lambda^2y. □\square

Claim 6. If JJ has full row rank, then Δθ=0\Delta\theta = 0 only if e=0e = 0.

Proof. Δθ=JTy\Delta\theta = J^{\mathsf T}y, and JTJ^{\mathsf T} is injective when JJ has full row rank, so Δθ=0\Delta\theta = 0 gives y=0y = 0 and e=(JJT+λ2I)y=0e = (JJ^{\mathsf T} + \lambda^2I)y = 0. □\square

So a fixed point of the iteration at a configuration with full row rank is a solution. At a singular configuration, a fixed point with e≠0e \ne 0 can exist, such as the stretched arm with a target out of reach on the page, where ee is orthogonal to the range of JJ.

Local convergence

Claim 7. Let m=nm = n, let ff be twice continuously differentiable, and let θ∗\theta^* be a solution, f(θ∗)=xdf(\theta^*) = x_d, with J(θ∗)J(\theta^*) invertible and least singular value σmin⁡\sigma_{\min}. Let ρ=λ2/(σmin⁡2+λ2)<1\rho = \lambda^2/(\sigma_{\min}^2 + \lambda^2) < 1. For every ρ′∈(ρ,1)\rho' \in (\rho, 1) there is r>0r > 0 such that every start with ∣θ0−θ∗∣≤r|\theta^0 - \theta^*| \le r gives iterates with ∣θk+1−θ∗∣≤ρ′∣θk−θ∗∣|\theta^{k+1} - \theta^*| \le \rho'|\theta^k - \theta^*|, so the iteration converges to θ∗\theta^*.

Proof. The iteration is θk+1=Φ(θk)\theta^{k+1} = \Phi(\theta^k) with Φ(θ)=θ+J(θ)T(J(θ)J(θ)T+λ2I)−1(xd−f(θ))\Phi(\theta) = \theta + J(\theta)^{\mathsf T}(J(\theta)J(\theta)^{\mathsf T} + \lambda^2I)^{-1}(x_d - f(\theta)). Φ\Phi is continuously differentiable, since the inverse exists everywhere by Claim 1, and Φ(θ∗)=θ∗\Phi(\theta^*) = \theta^*. At θ∗\theta^* the term with xd−fx_d - f vanishes, so only the derivative of xd−fx_d - f, which is −J-J, contributes:

DΦ(θ∗)=I−(JTJ+λ2I)−1JTJ=λ2(JTJ+λ2I)−1,D\Phi(\theta^*) = I - (J^{\mathsf T}J + \lambda^2I)^{-1}J^{\mathsf T}J = \lambda^2(J^{\mathsf T}J + \lambda^2I)^{-1},

with J=J(θ∗)J = J(\theta^*), using Claim 1. This matrix is symmetric with the eigenvalues λ2/(σi2+λ2)\lambda^2/(\sigma_i^2 + \lambda^2), all in (0,1)(0, 1), and the largest is ρ\rho. So ∣DΦ(θ∗)∣=ρ|D\Phi(\theta^*)| = \rho. By continuity of DΦD\Phi, there is r>0r > 0 with ∣DΦ(θ)∣≤ρ′|D\Phi(\theta)| \le \rho' on the ball of radius rr around θ∗\theta^*. On this convex ball, the mean value inequality gives ∣Φ(θ)−θ∗∣=∣Φ(θ)−Φ(θ∗)∣≤ρ′∣θ−θ∗∣|\Phi(\theta) - \theta^*| = |\Phi(\theta) - \Phi(\theta^*)| \le \rho'|\theta - \theta^*|, so each iterate stays in the ball and the distance falls by at least the factor ρ′\rho'. □\square

For the 2R arm of the page at (0,π/2)(0, \pi/2), JTJ=[[2,1],[1,1]]J^{\mathsf T}J = [[2, 1], [1, 1]] has the eigenvalues (3±5)/2(3 \pm \sqrt 5)/2, so ρ=0.0255\rho = 0.0255 for λ=0.1\lambda = 0.1 and ρ=0.396\rho = 0.396 for λ=0.5\lambda = 0.5. For a generic start the error along the eigenvector of ρ\rho dominates, and the measured ratios of the errors approach ρ\rho, as the tests check.

For m<nm < n the solutions form a manifold, and DΦD\Phi has the eigenvalue 1 along its tangent space, so the claim does not apply as stated, and we do not prove a result for that case here. The result is local, and nothing is claimed for far starts or for targets out of reach.

Complexity

One step forms JJTJJ^{\mathsf T} in Θ(m2n)\Theta(m^2n), solves the m×mm \times m system in Θ(m3)\Theta(m^3), and forms JTyJ^{\mathsf T}y in Θ(mn)\Theta(mn), in the real RAM. With m≤nm \le n, this is Θ(m2n)\Theta(m^2n) per step, plus the cost of ff and JJ, which is Θ(mn)\Theta(mn) for a serial chain. So kk steps cost Θ(km2n)\Theta(km^2n). The extra space is the Jacobian and the m×mm \times m matrix, Θ(mn)\Theta(mn). The number of steps kk is not bounded in general; near a regular solution, it grows like log⁡(1/ε)\log(1/\varepsilon) with the rate above.

Properties

  • Always defined. The step exists at every configuration and for every error, also at singularities and for targets out of reach.
  • Bounded steps. ∣Δθ∣≤∣e∣/(2λ)|\Delta\theta| \le |e|/(2\lambda).
  • Slower than Newton. Near a regular solution the convergence is linear, not quadratic, and slower for larger λ\lambda.
  • A trade-off in one number. Small λ\lambda gives accurate but possibly large steps; large λ\lambda gives small steps and slow progress.
  • Redundant arms. For m<nm < n, the step has no component in the null space of JJ, as for the pseudoinverse.

Variants and improvements

  • Variable damping. Nakamura and Hanafusa let the damping grow as the arm approaches a singularity and vanish far from it, using a measure of the distance to the singularity such as the manipulability.
  • Damping only where needed. Using the singular value form, one can damp only the small singular values, or add damping only along the directions of the least singular vectors.
  • Selectively damped least squares. Buss and Kim (2005) choose a separate damping for each singular direction from the size of the joint motion it would cause.
  • Levenberg-Marquardt. Choosing λ\lambda at each step from the decrease of the error gives the Levenberg-Marquardt method, which behaves like Newton near a regular solution and like gradient descent far from it.
  • With a secondary task. For a redundant arm, a null space term (I−J+J)z(I - J^{+}J)z can be added to the step. If the projector is built from the damped inverse instead of J+J^{+}, the term is no longer exactly in the null space.

When to use it

Use damped least squares when the arm may pass near a singularity, or when the target may be out of reach, and a smooth, bounded joint motion matters more than exact tracking at each step. This is the usual case for real time control of an arm and for character animation. Use Newton-Raphson inverse kinematics when the solution is regular and a fast final convergence matters. Use the Jacobian transpose method when even the small linear solve is too costly.

Pitfalls

  • Choosing λ\lambda. The damping factor is a tuning parameter, and no value is best for all arms and tasks. Nakamura and Hanafusa make it depend on the distance to a singularity, and Buss says that it must be chosen for the arm and the targets at hand.
  • Units. The penalty λ2∣Δθ∣2\lambda^2|\Delta\theta|^2 and the error ∣JΔθ−e∣2|J\Delta\theta - e|^2 mix rad and m, so the value of λ\lambda changes with the units of the task.
  • Oscillation. A small λ\lambda with a target out of reach can make the arm jump back and forth, as in the example; a larger λ\lambda or a limit on the step length helps.
  • Tracking error. In real time control, each step leaves the residual λ2(JJT+λ2I)−1e\lambda^2(JJ^{\mathsf T} + \lambda^2I)^{-1}e, so the hand lags behind a moving target.
  • The wrong form. The n×nn \times n form is wasteful for a redundant arm with n≫mn \gg m; use the m×mm \times m form.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

damped_least_squares_inverse_kinematics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/damped-least-squares-inverse-kinematics/. The authors are listed in prov/J6EXM0.jsonl.
"""Inverse kinematics by damped least squares steps.

- dls_step(j, e, lam) returns dq = J^T (J J^T + lam^2 I)^-1 e, the step of
  the page. It solves an m by m system, where m is the number of task
  coordinates.
- dls_step_normal(j, e, lam) returns the same step in the form
  (J^T J + lam^2 I)^-1 J^T e, which solves an n by n system.
- ik_dls(fk, jac, x_d, q0, lam, ...) is the iteration of the page. It
  returns (q, history, ok): the last joint vector, the error norms before
  each step, and whether the tolerance was met. When the target is out of
  reach, q is the last iterate, which is the useful answer of the method.
- planar_fk and planar_jacobian give a planar arm with n revolute joints,
  used by the tests and the example of the page.

Matrices are lists of rows, as in the shared helper rbm.
"""

import math

import rbm


def dls_step(j, e, lam):
    """Return J^T (J J^T + lam^2 I)^-1 e."""
    m = len(j)
    jt = rbm.transpose(j)
    a = rbm.add(rbm.mul(j, jt), rbm.scale(rbm.eye(m), lam * lam))  # @line L6
    y = rbm.solve(a, e)  # @line L6
    return rbm.matvec(jt, y)  # @line L7


def dls_step_normal(j, e, lam):
    """Return (J^T J + lam^2 I)^-1 J^T e, the same step as dls_step."""
    jt = rbm.transpose(j)
    n = len(jt)
    a = rbm.add(rbm.mul(jt, j), rbm.scale(rbm.eye(n), lam * lam))
    return rbm.solve(a, rbm.matvec(jt, e))


def ik_dls(fk, jac, x_d, q0, lam, eps=1e-10, max_iter=500):
    """Return (q, history, ok) for the task fk(q) = x_d by damped least squares steps."""
    q = [float(x) for x in q0]  # @line L1
    history = []
    for _ in range(max_iter):  # @line L2
        e = rbm.sub(x_d, fk(q))  # @line L3
        history.append(rbm.norm(e))
        if history[-1] <= eps:  # @line L4
            return q, history, True
        j = jac(q)  # @line L5
        dq = dls_step(j, e, lam)
        q = [x + d for x, d in zip(q, dq)]  # @line L8
    return q, history, False  # @line L9


def planar_fk(lengths, q):
    """Return the hand position of a planar arm with the given link lengths."""
    x = y = a = 0.0
    for length, t in zip(lengths, q):
        a += t
        x += length * math.cos(a)
        y += length * math.sin(a)
    return [x, y]


def planar_jacobian(lengths, q):
    """Return the 2 by n Jacobian of planar_fk."""
    angles = []
    a = 0.0
    for t in q:
        a += t
        angles.append(a)
    n = len(q)
    row_x = [-sum(lengths[k] * math.sin(angles[k]) for k in range(i, n)) for i in range(n)]
    row_y = [sum(lengths[k] * math.cos(angles[k]) for k in range(i, n)) for i in range(n)]
    return [row_x, row_y]
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_damped_least_squares_inverse_kinematics.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/damped-least-squares-inverse-kinematics/. The authors are listed in prov/J6EXM0.jsonl.
"""Tests of damped least squares inverse kinematics: the two forms of the
step, the step as the minimizer of the damped objective (against random
perturbations), the bound |dq| <= |e| / (2 lam), the limit lam -> 0 against
the pseudoinverse, the example of the page, the local linear rate, random
reachable targets, and a target out of reach."""

import math
import random

import rbm
from damped_least_squares_inverse_kinematics import dls_step, dls_step_normal, ik_dls, planar_fk, planar_jacobian


def rand_matrix(rng, m, n):
    return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]


def objective(j, e, lam, dq):
    r = rbm.sub(rbm.matvec(j, dq), e)
    return rbm.dot(r, r) + lam * lam * rbm.dot(dq, dq)


def maxdiff(a, b):
    return max(abs(x - y) for x, y in zip(a, b))


def test_two_forms_agree():
    rng = random.Random(1)
    for m, n in ((2, 2), (2, 3), (3, 2), (6, 6), (3, 7), (6, 4)):
        for _ in range(10):
            j = rand_matrix(rng, m, n)
            e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
            lam = rng.uniform(0.01, 1.0)
            assert maxdiff(dls_step(j, e, lam), dls_step_normal(j, e, lam)) < 1e-9


def test_step_minimizes_damped_objective():
    rng = random.Random(2)
    for m, n in ((2, 3), (3, 3), (6, 7), (3, 2)):
        for _ in range(10):
            j = rand_matrix(rng, m, n)
            e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
            lam = rng.uniform(0.05, 1.0)
            dq = dls_step(j, e, lam)
            best = objective(j, e, lam, dq)
            # The gradient J^T (J dq - e) + lam^2 dq is zero.
            r = rbm.sub(rbm.matvec(j, dq), e)
            grad = [g + lam * lam * d for g, d in zip(rbm.matvec(rbm.transpose(j), r), dq)]
            assert rbm.norm(grad) < 1e-10
            # No random perturbation does better.
            for _ in range(50):
                s = rng.choice((1e-3, 1e-1, 1.0))
                trial = [d + rng.uniform(-s, s) for d in dq]
                assert objective(j, e, lam, trial) >= best - 1e-12


def test_step_bound():
    rng = random.Random(3)
    for _ in range(200):
        m, n = rng.choice(((2, 2), (2, 3), (3, 6), (6, 6)))
        if rng.random() < 0.5:
            j = rand_matrix(rng, m, n)
        else:
            # rank one, so that J J^T is singular
            u = [rng.uniform(-3.0, 3.0) for _ in range(m)]
            v = [rng.uniform(-3.0, 3.0) for _ in range(n)]
            j = [[a * b for b in v] for a in u]
        e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
        lam = rng.uniform(0.01, 1.0)
        assert rbm.norm(dls_step(j, e, lam)) <= rbm.norm(e) / (2.0 * lam) * (1.0 + 1e-9)
    # The bound is reached: one singular value equal to lam, and e along it.
    j = [[0.3, 0.0], [0.0, 2.0]]
    dq = dls_step(j, [1.0, 0.0], 0.3)
    assert abs(rbm.norm(dq) - 1.0 / 0.6) < 1e-12


def test_small_lambda_gives_pseudoinverse():
    rng = random.Random(4)
    for m, n in ((2, 2), (2, 3), (3, 5), (6, 7)):
        for _ in range(5):
            j = rand_matrix(rng, m, n)
            e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
            ref = rbm.matvec(rbm.pinv_right(j), e)
            assert maxdiff(dls_step(j, e, 1e-7), ref) < 1e-6 * (1.0 + rbm.norm(ref))


L2 = [1.0, 1.0]


def fk2(q):
    return planar_fk(L2, q)


def jac2(q):
    return planar_jacobian(L2, q)


def test_planar_jacobian_against_finite_differences():
    rng = random.Random(5)
    lengths = [1.0, 0.8, 0.5, 0.3]
    for _ in range(10):
        q = [rng.uniform(-math.pi, math.pi) for _ in range(4)]
        num = rbm.num_jacobian(lambda x: planar_fk(lengths, x), q, 1e-6)
        got = planar_jacobian(lengths, q)
        assert max(abs(a - b) for ra, rb in zip(num, got) for a, b in zip(ra, rb)) < 1e-6
    j = jac2([0.0, math.pi / 2.0])
    assert maxdiff(j[0] + j[1], [-1.0, -1.0, 1.0, 0.0]) < 1e-15
    assert maxdiff(fk2([0.0, math.pi / 2.0]), [1.0, 1.0]) < 1e-15


def test_example_of_the_page():
    q = [0.0, 0.01]
    e = rbm.sub([1.9, 0.2], fk2(q))
    j = jac2(q)
    newton = rbm.solve(j, e)
    assert maxdiff(newton, [-9.804667, 19.799833]) < 1e-6
    dq = dls_step(j, e, 0.1)
    assert maxdiff(dq, [0.056365, 0.077488]) < 1e-6
    assert rbm.norm(dq) <= rbm.norm(e) / 0.2
    q, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], 0.1)
    assert ok and len(hist) == 8
    for got, want in zip(hist, [0.294, 0.0415, 0.00138, 3.45e-5]):
        assert abs(got - want) < 0.005 * want
    assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-10
    q, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], 0.5)
    assert ok and len(hist) == 25


def test_local_linear_rate():
    # Near the solution (0, pi/2), the error ratio tends to lam^2 / (s^2 + lam^2), s the least singular value.
    s2 = (3.0 - math.sqrt(5.0)) / 2.0
    for lam in (0.1, 0.5):
        _, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], lam)
        assert ok
        rate = lam * lam / (s2 + lam * lam)
        ratios = [b / a for a, b in zip(hist, hist[1:]) if 1e-9 < b and a < 1e-3]
        assert ratios and all(abs(r - rate) < 0.02 * rate for r in ratios)


def test_random_reachable_targets():
    rng = random.Random(6)
    lengths = [1.0, 0.8, 0.5]
    for _ in range(30):
        q_star = [rng.uniform(-math.pi, math.pi) for _ in range(3)]
        x_d = planar_fk(lengths, q_star)
        q0 = [rng.uniform(-math.pi, math.pi) for _ in range(3)]
        q, hist, ok = ik_dls(lambda x: planar_fk(lengths, x), lambda x: planar_jacobian(lengths, x), x_d, q0, 0.1, max_iter=2000)
        assert ok
        assert maxdiff(planar_fk(lengths, q), x_d) < 1e-9


def test_out_of_reach():
    # With lam = 0.5 the arm stretches toward the target and stops at the nearest point.
    q, hist, ok = ik_dls(fk2, jac2, [2.5, 0.0], [0.2, 0.5], 0.5, max_iter=200)
    assert not ok
    assert abs(hist[-1] - 0.5) < 1e-12
    assert maxdiff(fk2(q), [2.0, 0.0]) < 1e-12
    # Every step stays bounded by |e| / (2 lam).
    q = [0.2, 0.5]
    for _ in range(50):
        e = rbm.sub([2.5, 0.0], fk2(q))
        dq = dls_step(jac2(q), e, 0.1)
        assert rbm.norm(dq) <= rbm.norm(e) / 0.2 * (1.0 + 1e-9)
        q = [a + b for a, b in zip(q, dq)]

History

Wampler (1986) and Nakamura and Hanafusa (1986) brought the damped least squares step to the inverse kinematics of arms in the same year, independently. Wampler derived it as the minimizer of a sum of the squared error and the squared joint motion. Nakamura and Hanafusa called it the singularity robust inverse and studied its behavior near singularities with a damping that changes with the configuration. The same regularization was known much earlier in numerical analysis as Tikhonov regularization, and in nonlinear least squares as the Levenberg-Marquardt method. Buss (2004) compared the transpose, pseudoinverse and damped least squares methods in a survey that is often cited in computer animation.

References

  1. Charles W. Wampler II, Manipulator inverse kinematic solutions based on vector formulations and damped least-squares methods, IEEE Transactions on Systems, Man, and Cybernetics 16(1), 93-101, 1986, the damped least squares formulation of the inverse kinematics step
  2. Yoshihiko Nakamura and Hideo Hanafusa, Inverse kinematic solutions with singularity robustness for robot manipulator control, Journal of Dynamic Systems, Measurement, and Control 108(3), 163-171, 1986, the singularity robust inverse and its damping factor
  3. Samuel R. Buss, Introduction to Inverse Kinematics with Jacobian Transpose, Pseudoinverse and Damped Least Squares methods, unpublished survey, University of California, San Diego, 2004, the sections on damped least squares and on the singular value decomposition of the step

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example